From 0c1a1ed7ca8e0a9f711cada1a7a232b99cc845db Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Wed, 6 May 2026 02:12:51 -0600 Subject: [PATCH] Initial commit: v0.9.0 release --- .github/workflows/ci.yml | 47 + .github/workflows/release.yml | 99 + .gitignore | 9 + Cargo.lock | 2826 ++++++++ Cargo.toml | 89 + LICENSE | 661 ++ README.md | 245 + crates/rns-crypto/Cargo.toml | 29 + crates/rns-crypto/src/aes_cbc.rs | 181 + crates/rns-crypto/src/ed25519.rs | 173 + crates/rns-crypto/src/hkdf.rs | 88 + crates/rns-crypto/src/hmac.rs | 60 + crates/rns-crypto/src/lib.rs | 30 + crates/rns-crypto/src/pkcs7.rs | 127 + crates/rns-crypto/src/random.rs | 52 + crates/rns-crypto/src/sha.rs | 80 + crates/rns-crypto/src/token.rs | 253 + crates/rns-crypto/src/x25519.rs | 121 + crates/rns-identity/Cargo.toml | 21 + crates/rns-identity/src/announce.rs | 441 ++ crates/rns-identity/src/destination.rs | 859 +++ crates/rns-identity/src/identity.rs | 461 ++ crates/rns-identity/src/ifac.rs | 139 + crates/rns-identity/src/known_destinations.rs | 664 ++ crates/rns-identity/src/lib.rs | 12 + crates/rns-identity/src/name_hash.rs | 32 + crates/rns-identity/src/persistence.rs | 68 + crates/rns-identity/src/ratchet.rs | 658 ++ crates/rns-interface/Cargo.toml | 77 + crates/rns-interface/src/android_usb.rs | 658 ++ crates/rns-interface/src/auto.rs | 1601 +++++ crates/rns-interface/src/ax25kiss.rs | 680 ++ crates/rns-interface/src/backbone.rs | 609 ++ crates/rns-interface/src/ble_central_apple.rs | 932 +++ .../src/ble_central_apple_connect.rs | 1296 ++++ .../src/ble_central_lifecycle.rs | 487 ++ crates/rns-interface/src/ble_peer.rs | 5981 +++++++++++++++++ .../rns-interface/src/ble_peer_lifecycle.rs | 675 ++ crates/rns-interface/src/ble_rnode.rs | 2259 +++++++ crates/rns-interface/src/hdlc.rs | 298 + crates/rns-interface/src/i2p.rs | 1058 +++ crates/rns-interface/src/kiss.rs | 483 ++ crates/rns-interface/src/kiss_iface.rs | 292 + crates/rns-interface/src/lib.rs | 39 + crates/rns-interface/src/local.rs | 749 +++ crates/rns-interface/src/pipe.rs | 251 + crates/rns-interface/src/rnode.rs | 641 ++ crates/rns-interface/src/rnode_admin.rs | 170 + crates/rns-interface/src/rnode_multi.rs | 1237 ++++ crates/rns-interface/src/serial.rs | 222 + crates/rns-interface/src/socket_tuning.rs | 208 + crates/rns-interface/src/tcp.rs | 799 +++ crates/rns-interface/src/traits.rs | 244 + crates/rns-interface/src/udp.rs | 286 + crates/rns-interface/src/weave.rs | 491 ++ crates/rns-link/Cargo.toml | 24 + crates/rns-link/src/constants.rs | 99 + crates/rns-link/src/encryption.rs | 112 + crates/rns-link/src/handshake.rs | 574 ++ crates/rns-link/src/keepalive.rs | 285 + crates/rns-link/src/key_derivation.rs | 109 + crates/rns-link/src/lib.rs | 12 + crates/rns-link/src/link.rs | 2239 ++++++ crates/rns-link/src/mtu_discovery.rs | 116 + crates/rns-link/src/request.rs | 248 + crates/rns-protocol/Cargo.toml | 21 + crates/rns-protocol/src/buffer.rs | 499 ++ crates/rns-protocol/src/channel.rs | 1184 ++++ crates/rns-protocol/src/channel_message.rs | 50 + crates/rns-protocol/src/compression.rs | 101 + crates/rns-protocol/src/lib.rs | 12 + crates/rns-protocol/src/resource.rs | 4384 ++++++++++++ crates/rns-protocol/src/resource_adv.rs | 423 ++ crates/rns-protocol/src/rnsh.rs | 740 ++ crates/rns-protocol/src/stream_data.rs | 201 + crates/rns-ratkey/Cargo.toml | 31 + crates/rns-ratkey/HARDWARE_STATUS.md | 23 + .../certs/yubico-attestation-root-1.pem | 20 + .../certs/yubico-piv-root-ca-legacy.pem | 19 + crates/rns-ratkey/src/apdu.rs | 685 ++ crates/rns-ratkey/src/attestation.rs | 445 ++ crates/rns-ratkey/src/detect.rs | 176 + crates/rns-ratkey/src/error.rs | 58 + crates/rns-ratkey/src/hardware.rs | 369 + crates/rns-ratkey/src/hwid.rs | 332 + crates/rns-ratkey/src/lib.rs | 24 + crates/rns-ratkey/src/mock.rs | 628 ++ crates/rns-ratkey/src/pin.rs | 131 + crates/rns-ratkey/src/provision.rs | 255 + crates/rns-ratkey/src/session.rs | 174 + crates/rns-runtime/Cargo.toml | 32 + crates/rns-runtime/src/config.rs | 942 +++ crates/rns-runtime/src/constants.rs | 40 + crates/rns-runtime/src/interface_factory.rs | 1986 ++++++ crates/rns-runtime/src/jobs.rs | 112 + crates/rns-runtime/src/lib.rs | 19 + crates/rns-runtime/src/lifecycle.rs | 147 + crates/rns-runtime/src/link_client.rs | 680 ++ crates/rns-runtime/src/link_manager.rs | 3435 ++++++++++ crates/rns-runtime/src/platform.rs | 173 + crates/rns-runtime/src/probe.rs | 602 ++ crates/rns-runtime/src/remote_management.rs | 634 ++ .../src/remote_management_schema.rs | 94 + crates/rns-runtime/src/reticulum.rs | 3795 +++++++++++ crates/rns-runtime/src/rncp.rs | 1568 +++++ crates/rns-runtime/src/rnsh.rs | 2146 ++++++ crates/rns-runtime/src/rpc.rs | 1713 +++++ crates/rns-runtime/src/rpc_server.rs | 917 +++ crates/rns-tools/Cargo.toml | 65 + crates/rns-tools/src/bin/rncp-rs.rs | 6 + crates/rns-tools/src/bin/rnid-rs.rs | 6 + crates/rns-tools/src/bin/rnodeconf-rs.rs | 6 + crates/rns-tools/src/bin/rnpath-rs.rs | 6 + crates/rns-tools/src/bin/rnprobe-rs.rs | 6 + crates/rns-tools/src/bin/rnsd-rs.rs | 6 + crates/rns-tools/src/bin/rnsh-rs.rs | 6 + crates/rns-tools/src/bin/rnstatus-rs.rs | 6 + crates/rns-tools/src/commands/rncp.rs | 816 +++ .../src/commands/rnid/hw_commands.rs | 377 ++ crates/rns-tools/src/commands/rnid/main.rs | 1033 +++ crates/rns-tools/src/commands/rnodeconf.rs | 1061 +++ .../src/commands/rnodeconf/eeprom.rs | 352 + .../src/commands/rnodeconf/firmware.rs | 170 + .../rns-tools/src/commands/rnodeconf/flash.rs | 351 + .../rns-tools/src/commands/rnodeconf/model.rs | 556 ++ .../rns-tools/src/commands/rnodeconf/trust.rs | 87 + crates/rns-tools/src/commands/rnpath.rs | 1291 ++++ crates/rns-tools/src/commands/rnprobe.rs | 290 + crates/rns-tools/src/commands/rnsd.rs | 466 ++ crates/rns-tools/src/commands/rnsh.rs | 997 +++ crates/rns-tools/src/commands/rnstatus.rs | 1179 ++++ crates/rns-tools/src/format.rs | 131 + crates/rns-tools/src/hash.rs | 63 + crates/rns-tools/src/lib.rs | 4 + crates/rns-transport/Cargo.toml | 32 + crates/rns-transport/src/actor/inbound.rs | 1044 +++ crates/rns-transport/src/actor/maintenance.rs | 463 ++ crates/rns-transport/src/actor/mod.rs | 5778 ++++++++++++++++ crates/rns-transport/src/actor/outbound.rs | 677 ++ crates/rns-transport/src/actor/persistence.rs | 593 ++ crates/rns-transport/src/actor/rpc.rs | 410 ++ crates/rns-transport/src/announce.rs | 161 + crates/rns-transport/src/await_path.rs | 131 + crates/rns-transport/src/blackhole.rs | 293 + crates/rns-transport/src/constants.rs | 247 + .../rns-transport/src/discovery/announcer.rs | 564 ++ .../rns-transport/src/discovery/app_data.rs | 534 ++ .../src/discovery/blackhole_manifest.rs | 482 ++ .../src/discovery/blackhole_subscriber.rs | 189 + .../rns-transport/src/discovery/constants.rs | 93 + crates/rns-transport/src/discovery/mod.rs | 37 + .../rns-transport/src/discovery/receiver.rs | 601 ++ crates/rns-transport/src/discovery/stamper.rs | 50 + crates/rns-transport/src/discovery/storage.rs | 599 ++ crates/rns-transport/src/hashlist.rs | 137 + crates/rns-transport/src/ifac.rs | 362 + crates/rns-transport/src/ingress.rs | 384 ++ crates/rns-transport/src/lib.rs | 24 + crates/rns-transport/src/link_messages.rs | 146 + crates/rns-transport/src/link_table.rs | 334 + crates/rns-transport/src/messages.rs | 675 ++ crates/rns-transport/src/path_table.rs | 371 + crates/rns-transport/src/persistence.rs | 1227 ++++ crates/rns-transport/src/rate_limit.rs | 273 + crates/rns-transport/src/reverse_table.rs | 197 + crates/rns-transport/src/traffic.rs | 63 + crates/rns-transport/src/tunnel.rs | 355 + crates/rns-wire/Cargo.toml | 18 + crates/rns-wire/src/constants.rs | 81 + crates/rns-wire/src/context.rs | 148 + crates/rns-wire/src/flags.rs | 194 + crates/rns-wire/src/hash.rs | 148 + crates/rns-wire/src/header.rs | 251 + crates/rns-wire/src/lib.rs | 19 + crates/rns-wire/src/packet.rs | 198 + crates/rns-wire/src/proof.rs | 97 + crates/rns-wire/src/receipt.rs | 180 + crates/rns-wire/src/types.rs | 262 + 178 files changed, 93545 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 crates/rns-crypto/Cargo.toml create mode 100644 crates/rns-crypto/src/aes_cbc.rs create mode 100644 crates/rns-crypto/src/ed25519.rs create mode 100644 crates/rns-crypto/src/hkdf.rs create mode 100644 crates/rns-crypto/src/hmac.rs create mode 100644 crates/rns-crypto/src/lib.rs create mode 100644 crates/rns-crypto/src/pkcs7.rs create mode 100644 crates/rns-crypto/src/random.rs create mode 100644 crates/rns-crypto/src/sha.rs create mode 100644 crates/rns-crypto/src/token.rs create mode 100644 crates/rns-crypto/src/x25519.rs create mode 100644 crates/rns-identity/Cargo.toml create mode 100644 crates/rns-identity/src/announce.rs create mode 100644 crates/rns-identity/src/destination.rs create mode 100644 crates/rns-identity/src/identity.rs create mode 100644 crates/rns-identity/src/ifac.rs create mode 100644 crates/rns-identity/src/known_destinations.rs create mode 100644 crates/rns-identity/src/lib.rs create mode 100644 crates/rns-identity/src/name_hash.rs create mode 100644 crates/rns-identity/src/persistence.rs create mode 100644 crates/rns-identity/src/ratchet.rs create mode 100644 crates/rns-interface/Cargo.toml create mode 100644 crates/rns-interface/src/android_usb.rs create mode 100644 crates/rns-interface/src/auto.rs create mode 100644 crates/rns-interface/src/ax25kiss.rs create mode 100644 crates/rns-interface/src/backbone.rs create mode 100644 crates/rns-interface/src/ble_central_apple.rs create mode 100644 crates/rns-interface/src/ble_central_apple_connect.rs create mode 100644 crates/rns-interface/src/ble_central_lifecycle.rs create mode 100644 crates/rns-interface/src/ble_peer.rs create mode 100644 crates/rns-interface/src/ble_peer_lifecycle.rs create mode 100644 crates/rns-interface/src/ble_rnode.rs create mode 100644 crates/rns-interface/src/hdlc.rs create mode 100644 crates/rns-interface/src/i2p.rs create mode 100644 crates/rns-interface/src/kiss.rs create mode 100644 crates/rns-interface/src/kiss_iface.rs create mode 100644 crates/rns-interface/src/lib.rs create mode 100644 crates/rns-interface/src/local.rs create mode 100644 crates/rns-interface/src/pipe.rs create mode 100644 crates/rns-interface/src/rnode.rs create mode 100644 crates/rns-interface/src/rnode_admin.rs create mode 100644 crates/rns-interface/src/rnode_multi.rs create mode 100644 crates/rns-interface/src/serial.rs create mode 100644 crates/rns-interface/src/socket_tuning.rs create mode 100644 crates/rns-interface/src/tcp.rs create mode 100644 crates/rns-interface/src/traits.rs create mode 100644 crates/rns-interface/src/udp.rs create mode 100644 crates/rns-interface/src/weave.rs create mode 100644 crates/rns-link/Cargo.toml create mode 100644 crates/rns-link/src/constants.rs create mode 100644 crates/rns-link/src/encryption.rs create mode 100644 crates/rns-link/src/handshake.rs create mode 100644 crates/rns-link/src/keepalive.rs create mode 100644 crates/rns-link/src/key_derivation.rs create mode 100644 crates/rns-link/src/lib.rs create mode 100644 crates/rns-link/src/link.rs create mode 100644 crates/rns-link/src/mtu_discovery.rs create mode 100644 crates/rns-link/src/request.rs create mode 100644 crates/rns-protocol/Cargo.toml create mode 100644 crates/rns-protocol/src/buffer.rs create mode 100644 crates/rns-protocol/src/channel.rs create mode 100644 crates/rns-protocol/src/channel_message.rs create mode 100644 crates/rns-protocol/src/compression.rs create mode 100644 crates/rns-protocol/src/lib.rs create mode 100644 crates/rns-protocol/src/resource.rs create mode 100644 crates/rns-protocol/src/resource_adv.rs create mode 100644 crates/rns-protocol/src/rnsh.rs create mode 100644 crates/rns-protocol/src/stream_data.rs create mode 100644 crates/rns-ratkey/Cargo.toml create mode 100644 crates/rns-ratkey/HARDWARE_STATUS.md create mode 100644 crates/rns-ratkey/certs/yubico-attestation-root-1.pem create mode 100644 crates/rns-ratkey/certs/yubico-piv-root-ca-legacy.pem create mode 100644 crates/rns-ratkey/src/apdu.rs create mode 100644 crates/rns-ratkey/src/attestation.rs create mode 100644 crates/rns-ratkey/src/detect.rs create mode 100644 crates/rns-ratkey/src/error.rs create mode 100644 crates/rns-ratkey/src/hardware.rs create mode 100644 crates/rns-ratkey/src/hwid.rs create mode 100644 crates/rns-ratkey/src/lib.rs create mode 100644 crates/rns-ratkey/src/mock.rs create mode 100644 crates/rns-ratkey/src/pin.rs create mode 100644 crates/rns-ratkey/src/provision.rs create mode 100644 crates/rns-ratkey/src/session.rs create mode 100644 crates/rns-runtime/Cargo.toml create mode 100644 crates/rns-runtime/src/config.rs create mode 100644 crates/rns-runtime/src/constants.rs create mode 100644 crates/rns-runtime/src/interface_factory.rs create mode 100644 crates/rns-runtime/src/jobs.rs create mode 100644 crates/rns-runtime/src/lib.rs create mode 100644 crates/rns-runtime/src/lifecycle.rs create mode 100644 crates/rns-runtime/src/link_client.rs create mode 100644 crates/rns-runtime/src/link_manager.rs create mode 100644 crates/rns-runtime/src/platform.rs create mode 100644 crates/rns-runtime/src/probe.rs create mode 100644 crates/rns-runtime/src/remote_management.rs create mode 100644 crates/rns-runtime/src/remote_management_schema.rs create mode 100644 crates/rns-runtime/src/reticulum.rs create mode 100644 crates/rns-runtime/src/rncp.rs create mode 100644 crates/rns-runtime/src/rnsh.rs create mode 100644 crates/rns-runtime/src/rpc.rs create mode 100644 crates/rns-runtime/src/rpc_server.rs create mode 100644 crates/rns-tools/Cargo.toml create mode 100644 crates/rns-tools/src/bin/rncp-rs.rs create mode 100644 crates/rns-tools/src/bin/rnid-rs.rs create mode 100644 crates/rns-tools/src/bin/rnodeconf-rs.rs create mode 100644 crates/rns-tools/src/bin/rnpath-rs.rs create mode 100644 crates/rns-tools/src/bin/rnprobe-rs.rs create mode 100644 crates/rns-tools/src/bin/rnsd-rs.rs create mode 100644 crates/rns-tools/src/bin/rnsh-rs.rs create mode 100644 crates/rns-tools/src/bin/rnstatus-rs.rs create mode 100644 crates/rns-tools/src/commands/rncp.rs create mode 100644 crates/rns-tools/src/commands/rnid/hw_commands.rs create mode 100644 crates/rns-tools/src/commands/rnid/main.rs create mode 100644 crates/rns-tools/src/commands/rnodeconf.rs create mode 100644 crates/rns-tools/src/commands/rnodeconf/eeprom.rs create mode 100644 crates/rns-tools/src/commands/rnodeconf/firmware.rs create mode 100644 crates/rns-tools/src/commands/rnodeconf/flash.rs create mode 100644 crates/rns-tools/src/commands/rnodeconf/model.rs create mode 100644 crates/rns-tools/src/commands/rnodeconf/trust.rs create mode 100644 crates/rns-tools/src/commands/rnpath.rs create mode 100644 crates/rns-tools/src/commands/rnprobe.rs create mode 100644 crates/rns-tools/src/commands/rnsd.rs create mode 100644 crates/rns-tools/src/commands/rnsh.rs create mode 100644 crates/rns-tools/src/commands/rnstatus.rs create mode 100644 crates/rns-tools/src/format.rs create mode 100644 crates/rns-tools/src/hash.rs create mode 100644 crates/rns-tools/src/lib.rs create mode 100644 crates/rns-transport/Cargo.toml create mode 100644 crates/rns-transport/src/actor/inbound.rs create mode 100644 crates/rns-transport/src/actor/maintenance.rs create mode 100644 crates/rns-transport/src/actor/mod.rs create mode 100644 crates/rns-transport/src/actor/outbound.rs create mode 100644 crates/rns-transport/src/actor/persistence.rs create mode 100644 crates/rns-transport/src/actor/rpc.rs create mode 100644 crates/rns-transport/src/announce.rs create mode 100644 crates/rns-transport/src/await_path.rs create mode 100644 crates/rns-transport/src/blackhole.rs create mode 100644 crates/rns-transport/src/constants.rs create mode 100644 crates/rns-transport/src/discovery/announcer.rs create mode 100644 crates/rns-transport/src/discovery/app_data.rs create mode 100644 crates/rns-transport/src/discovery/blackhole_manifest.rs create mode 100644 crates/rns-transport/src/discovery/blackhole_subscriber.rs create mode 100644 crates/rns-transport/src/discovery/constants.rs create mode 100644 crates/rns-transport/src/discovery/mod.rs create mode 100644 crates/rns-transport/src/discovery/receiver.rs create mode 100644 crates/rns-transport/src/discovery/stamper.rs create mode 100644 crates/rns-transport/src/discovery/storage.rs create mode 100644 crates/rns-transport/src/hashlist.rs create mode 100644 crates/rns-transport/src/ifac.rs create mode 100644 crates/rns-transport/src/ingress.rs create mode 100644 crates/rns-transport/src/lib.rs create mode 100644 crates/rns-transport/src/link_messages.rs create mode 100644 crates/rns-transport/src/link_table.rs create mode 100644 crates/rns-transport/src/messages.rs create mode 100644 crates/rns-transport/src/path_table.rs create mode 100644 crates/rns-transport/src/persistence.rs create mode 100644 crates/rns-transport/src/rate_limit.rs create mode 100644 crates/rns-transport/src/reverse_table.rs create mode 100644 crates/rns-transport/src/traffic.rs create mode 100644 crates/rns-transport/src/tunnel.rs create mode 100644 crates/rns-wire/Cargo.toml create mode 100644 crates/rns-wire/src/constants.rs create mode 100644 crates/rns-wire/src/context.rs create mode 100644 crates/rns-wire/src/flags.rs create mode 100644 crates/rns-wire/src/hash.rs create mode 100644 crates/rns-wire/src/header.rs create mode 100644 crates/rns-wire/src/lib.rs create mode 100644 crates/rns-wire/src/packet.rs create mode 100644 crates/rns-wire/src/proof.rs create mode 100644 crates/rns-wire/src/receipt.rs create mode 100644 crates/rns-wire/src/types.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ce3beab --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + test: + name: Test (${{ matrix.os }}) + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Install system deps (Linux) + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config + - name: Test (default features) + run: cargo test --workspace + - name: Test BLE interface features (Linux) + if: runner.os == 'Linux' + run: cargo test -p rns-interface --features ble,ble_peer + + lint: + name: Lint + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy, rustfmt + - name: Install system deps + run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config + - run: cargo fmt --all -- --check + - run: cargo clippy --workspace --all-targets -- -D warnings + - run: cargo clippy -p rns-interface --features ble,ble_peer --all-targets -- -D warnings diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..52aa38d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,99 @@ +name: Release + +on: + push: + tags: + - "v*" + workflow_dispatch: + inputs: + tag_name: + description: "Release tag to create or update" + required: true + +permissions: + contents: read + +env: + RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }} + PACKAGE_ROOT: rsReticulum + RETICULUM_BINS: rnsd-rs rnstatus-rs rnpath-rs rnid-rs rnprobe-rs rncp-rs rnsh-rs rnodeconf-rs + +jobs: + build: + name: Build ${{ matrix.artifact_suffix }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + artifact_suffix: linux-x86_64 + archive: tar.gz + - os: macos-latest + artifact_suffix: macos + archive: tar.gz + - os: windows-latest + artifact_suffix: windows-x86_64 + archive: zip + runs-on: ${{ matrix.os }} + env: + ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.RELEASE_TAG }} + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Install system deps (Linux) + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config + - name: Build release binaries + run: cargo build -p rns-tools --release --bins + - name: Stage archive contents + shell: bash + run: | + set -euo pipefail + mkdir -p "dist/${PACKAGE_ROOT}/bin" + for bin in ${RETICULUM_BINS}; do + if [[ "${RUNNER_OS}" == "Windows" ]]; then + cp "target/release/${bin}.exe" "dist/${PACKAGE_ROOT}/bin/${bin}.exe" + else + cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}" + fi + done + cp README.md LICENSE "dist/${PACKAGE_ROOT}/" + - name: Create tar archive + if: runner.os != 'Windows' + shell: bash + run: tar -czf "${ARCHIVE_NAME}.tar.gz" -C dist "${PACKAGE_ROOT}" + - name: Create zip archive + if: runner.os == 'Windows' + shell: pwsh + run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force + - uses: actions/upload-artifact@v4 + with: + name: ${{ env.ARCHIVE_NAME }} + path: | + *.tar.gz + *.zip + if-no-files-found: error + + publish: + name: Publish GitHub release + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + path: release-assets + merge-multiple: true + - name: Generate checksums + working-directory: release-assets + run: sha256sum * > SHA256SUMS + - uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ env.RELEASE_TAG }} + prerelease: true + files: release-assets/* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..46ec2fc --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/target/ +*.swp +.DS_Store +__pycache__/ +*.pyc +/interop_artifacts/ +/rust_artifacts/ +proptest-regressions/ +/tools/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..ce2d793 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2826 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2", +] + +[[package]] +name = "bluer" +version = "0.17.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af68112f5c60196495c8b0eea68349817855f565df5b04b2477916d09fb1a901" +dependencies = [ + "custom_debug", + "dbus", + "dbus-crossroads", + "dbus-tokio", + "displaydoc", + "futures", + "hex", + "lazy_static", + "libc", + "log", + "macaddr", + "nix 0.29.0", + "num-derive", + "num-traits", + "pin-project", + "serde", + "serde_json", + "strum", + "tokio", + "tokio-stream", + "uuid", +] + +[[package]] +name = "bluez-async" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84ae4213cc2a8dc663acecac67bbdad05142be4d8ef372b6903abf878b0c690a" +dependencies = [ + "bitflags 2.11.0", + "bluez-generated", + "dbus", + "dbus-tokio", + "futures", + "itertools", + "log", + "serde", + "serde-xml-rs", + "thiserror 2.0.18", + "tokio", + "uuid", +] + +[[package]] +name = "bluez-generated" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9676783265eadd6f11829982792c6f303f3854d014edfba384685dcf237dd062" +dependencies = [ + "dbus", +] + +[[package]] +name = "btleplug" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9a11621cb2c8c024e444734292482b1ad86fb50ded066cf46252e46643c8748" +dependencies = [ + "async-trait", + "bitflags 2.11.0", + "bluez-async", + "dashmap 6.1.0", + "dbus", + "futures", + "jni", + "jni-utils", + "log", + "objc2", + "objc2-core-bluetooth", + "objc2-foundation", + "once_cell", + "static_assertions", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "uuid", + "windows 0.61.3", + "windows-future", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "bzip2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47" +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", +] + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "custom_debug" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da7d1ad9567b3e11e877f1d7a0fa0360f04162f94965fc4448fbed41a65298e" +dependencies = [ + "custom_debug_derive", +] + +[[package]] +name = "custom_debug_derive" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a707ceda8652f6c7624f2be725652e9524c815bf3b9d55a0b2320be2303f9c11" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "dashmap" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "dbus" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b3aa68d7e7abee336255bd7248ea965cc393f3e70411135a6f6a4b651345d4" +dependencies = [ + "futures-channel", + "futures-util", + "libc", + "libdbus-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "dbus-crossroads" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64bff0bd181fba667660276c6b7ebdc50cff37ce593e7adf9e734f89c8f444e8" +dependencies = [ + "dbus", +] + +[[package]] +name = "dbus-tokio" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007688d459bc677131c063a3a77fb899526e17b7980f390b69644bdbc41fad13" +dependencies = [ + "dbus", + "libc", + "tokio", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "rand_core 0.6.4", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "if-addrs" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "io-kit-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617ee6cf8e3f66f3b4ea67a4058564628cde41901316e19f559e14c7c72c5e7b" +dependencies = [ + "core-foundation-sys", + "mach2", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec" +dependencies = [ + "cesu8", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "jni-utils" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "259e9f2c3ead61de911f147000660511f07ab00adeed1d84f5ac4d0386e7a6c4" +dependencies = [ + "dashmap 5.5.3", + "futures", + "jni", + "log", + "once_cell", + "static_assertions", + "uuid", +] + +[[package]] +name = "js-sys" +version = "0.3.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.183" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libudev" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0" +dependencies = [ + "libc", + "libudev-sys", +] + +[[package]] +name = "libudev-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "macaddr" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baee0bbc17ce759db233beb01648088061bf678383130602a298e6998eedb2d8" + +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.11.0", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2-core-bluetooth" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111" +dependencies = [ + "bitflags 2.11.0", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.11.0", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link 0.2.1", +] + +[[package]] +name = "pcsc" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd833ecf8967e65934c49d3521a175929839bf6d0e497f3bd0d3a2ca08943da" +dependencies = [ + "bitflags 2.11.0", + "pcsc-sys", +] + +[[package]] +name = "pcsc-sys" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14ef017e15d2e5592a9e39a346c1dbaea5120bab7ed7106b210ef58ebd97003" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "pin-project" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags 2.11.0", + "num-traits", + "rand 0.9.4", + "rand_chacha 0.9.0", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core 0.9.5", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.11.0", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rmpv" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" +dependencies = [ + "rmp", + "serde", + "serde_bytes", +] + +[[package]] +name = "rns-crypto" +version = "0.9.0" +dependencies = [ + "aes", + "cbc", + "ed25519-dalek", + "hex", + "hkdf", + "hmac", + "rand 0.8.5", + "rand_core 0.6.4", + "serde", + "serde_json", + "sha2", + "subtle", + "thiserror 2.0.18", + "x25519-dalek", + "zeroize", +] + +[[package]] +name = "rns-identity" +version = "0.9.0" +dependencies = [ + "hex", + "proptest", + "rand 0.8.5", + "rmp-serde", + "rmpv", + "rns-crypto", + "rns-wire", + "serde", + "thiserror 2.0.18", + "tracing", + "zeroize", +] + +[[package]] +name = "rns-interface" +version = "0.9.0" +dependencies = [ + "bluer", + "btleplug", + "bytes", + "futures", + "hex", + "if-addrs", + "jni", + "libc", + "objc2", + "objc2-core-bluetooth", + "objc2-foundation", + "rand 0.8.5", + "rns-crypto", + "rns-transport", + "rns-wire", + "serde", + "serde_json", + "serialport", + "socket2 0.5.10", + "thiserror 2.0.18", + "tokio", + "tracing", + "uuid", + "windows 0.58.0", +] + +[[package]] +name = "rns-link" +version = "0.9.0" +dependencies = [ + "hex", + "proptest", + "rand 0.8.5", + "rmpv", + "rns-crypto", + "rns-identity", + "rns-wire", + "thiserror 2.0.18", + "tracing", + "zeroize", +] + +[[package]] +name = "rns-protocol" +version = "0.9.0" +dependencies = [ + "bzip2", + "hex", + "proptest", + "rmp-serde", + "rmpv", + "rns-crypto", + "rns-link", + "rns-wire", + "thiserror 2.0.18", + "tokio", + "tracing", +] + +[[package]] +name = "rns-ratkey" +version = "0.9.0" +dependencies = [ + "hex", + "pcsc", + "rns-crypto", + "rns-identity", + "rns-link", + "serde", + "thiserror 2.0.18", + "toml", + "tracing", + "zeroize", +] + +[[package]] +name = "rns-runtime" +version = "0.9.0" +dependencies = [ + "bytes", + "hex", + "hmac", + "nix 0.29.0", + "rmp-serde", + "rmpv", + "rns-crypto", + "rns-identity", + "rns-interface", + "rns-link", + "rns-protocol", + "rns-transport", + "rns-wire", + "serde", + "sha2", + "subtle", + "thiserror 2.0.18", + "tokio", + "tracing", +] + +[[package]] +name = "rns-tools" +version = "0.9.0" +dependencies = [ + "base64", + "bytes", + "clap", + "hex", + "nix 0.29.0", + "rmp-serde", + "rmpv", + "rns-crypto", + "rns-identity", + "rns-interface", + "rns-ratkey", + "rns-runtime", + "rns-transport", + "rns-wire", + "serde", + "serde_json", + "serialport", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "rns-transport" +version = "0.9.0" +dependencies = [ + "bytes", + "hex", + "proptest", + "rand 0.8.5", + "rmp-serde", + "rmpv", + "rns-crypto", + "rns-identity", + "rns-wire", + "serde", + "subtle", + "thiserror 2.0.18", + "tokio", + "tracing", +] + +[[package]] +name = "rns-wire" +version = "0.9.0" +dependencies = [ + "proptest", + "rns-crypto", + "sha2", + "thiserror 2.0.18", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.11.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-xml-rs" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc2215ce3e6a77550b80a1c37251b7d294febaf42e36e21b7b411e0bf54d540d" +dependencies = [ + "log", + "serde", + "thiserror 2.0.18", + "xml", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serialport" +version = "4.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4d91116f97173694f1642263b2ff837f80d933aa837e2314969f6728f661df3" +dependencies = [ + "bitflags 2.11.0", + "cfg-if", + "core-foundation", + "core-foundation-sys", + "io-kit-sys", + "libudev", + "mach2", + "nix 0.26.4", + "scopeguard", + "unescaper", + "windows-sys 0.52.0", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.6.3", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unescaper" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4064ed685c487dbc25bd3f0e9548f2e34bab9d18cefc700f9ec2dba74ba1138e" +dependencies = [ + "thiserror 2.0.18", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9" +dependencies = [ + "getrandom 0.4.2", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags 2.11.0", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" +dependencies = [ + "windows-core 0.58.0", + "windows-targets", +] + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core 0.61.2", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement 0.58.0", + "windows-interface 0.58.0", + "windows-result 0.2.0", + "windows-strings 0.1.0", + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result 0.2.0", + "windows-targets", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags 2.11.0", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[package]] +name = "xml" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8aa498d22c9bbaf482329839bc5620c46be275a19a812e9a22a2b07529a642a" + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..eaff8d2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,89 @@ +[workspace] +resolver = "2" +members = [ + "crates/rns-crypto", + "crates/rns-wire", + "crates/rns-identity", + "crates/rns-transport", + "crates/rns-link", + "crates/rns-protocol", + "crates/rns-interface", + "crates/rns-runtime", + "crates/rns-tools", + "crates/rns-ratkey", +] + +[workspace.package] +version = "0.9.0" +edition = "2024" +license = "AGPL-3.0-or-later" +rust-version = "1.85" + +[workspace.dependencies] +# Crypto +x25519-dalek = { version = "2", features = ["static_secrets"] } +ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] } +aes = "0.8" +cbc = { version = "0.1", features = ["alloc"] } +hkdf = "0.12" +hmac = "0.12" +sha2 = "0.10" +subtle = "2" +zeroize = { version = "1", features = ["derive"] } +rand = "0.8" +rand_core = { version = "0.6", features = ["getrandom"] } + +# Encoding +base64 = "0.22" + +# Serialization +rmp-serde = "1" +rmpv = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +# Async +tokio = { version = "1", features = ["full"] } + +# Compression +bzip2 = "0.5" + +# Serial +serialport = "4" + +# BLE +btleplug = "0.11" + +# Networking +if-addrs = "0.13" +socket2 = { version = "0.5", features = ["all"] } + +# CLI +clap = { version = "4", features = ["derive"] } + +# Logging +tracing = "0.1" +tracing-subscriber = "0.3" + +# Error handling +thiserror = "2" + +# Misc +hex = "0.4" +byteorder = "1" +bytes = "1" +nix = { version = "0.29", features = ["term", "fs"] } + +# Testing +proptest = "1" + +# Workspace crates +rns-crypto = { path = "crates/rns-crypto", default-features = false } +rns-wire = { path = "crates/rns-wire", default-features = false } +rns-identity = { path = "crates/rns-identity" } +rns-transport = { path = "crates/rns-transport" } +rns-link = { path = "crates/rns-link" } +rns-protocol = { path = "crates/rns-protocol" } +rns-interface = { path = "crates/rns-interface" } +rns-runtime = { path = "crates/rns-runtime" } +rns-ratkey = { path = "crates/rns-ratkey" } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a0f6796 --- /dev/null +++ b/README.md @@ -0,0 +1,245 @@ +
+ +# rsReticulum + +**A Rust implementation of Reticulum.** + + +[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE) +[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org) +[![Reticulum 1.2.2](https://img.shields.io/badge/target-Reticulum%201.2.2-success.svg)](https://reticulum.network/) +[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status) + +[Reticulum Manual](https://reticulum.network/manual/) | +[Ratspeak](https://github.com/ratspeak/Ratspeak) | +[rsLXMF](https://github.com/ratspeak/rsLXMF) | +[Reticulum](https://github.com/markqvist/Reticulum) + +
+ +--- + +rsReticulum is a Rust implementation of Reticulum. This is not a fork of +Reticulum; it is Reticulum written in a different language, focused on staying +interoperable. It is not the source-of-truth implementation, do not treat it as one. + +Commands are intentionally namespaced for Rust with `*-rs` command names, so +rsReticulum can live beside other Reticulum tools on `PATH` without worry. + +## Contents + +- [Build It](#build-it) +- [Tool Usage](#tool-usage) +- [Configuration](#configuration) +- [Interface Support](#interface-support) +- [Compatibility Notes](#compatibility-notes) +- [Contributing](#contributing) +- [License](#license) + +## Build It + +### macOS + +Install Rust with `rustup`, then install Apple's command-line build tools: + +```bash +xcode-select --install +``` + +Build the tools: + +```bash +cd rsReticulum +cargo build --release +``` + +### Linux, Raspberry Pi, and VPS Hosts + +##### Install Rust with `rustup`, then install the needed packages: + +Debian, Ubuntu, and Raspberry Pi OS: + +```bash +sudo apt update +sudo apt install -y build-essential pkg-config libudev-dev +``` + +Fedora: + +```bash +sudo dnf install gcc make pkgconf-pkg-config systemd-devel +``` + +Arch: + +```bash +sudo pacman -S --needed base-devel pkgconf systemd +``` + +##### Build the tools: + +```bash +cd rsReticulum +cargo build --release +``` + +### Windows + +Install Rust with the MSVC toolchain. If Rust or Cargo asks for Visual Studio +Build Tools, install the "Desktop development with C++" workload. + +Build from PowerShell: + +```powershell +cd rsReticulum +cargo build --release +``` + +After the build, use the commands below with `./target/release/` on +macOS/Linux or `.\target\release\.exe` on Windows. + +## Tool Usage + +The `rns-tools` crate builds Rust-namespaced Reticulum utilities: + +| Binary | Purpose | +| --- | --- | +| rnsd-rs | Shared Reticulum daemon. Owns interfaces and local control sockets. | +| rnstatus-rs | Interface, announce, path, link, and aggregate status. | +| rnpath-rs | Path lookup, path table inspection, rates, drops, and blackhole actions. | +| rnid-rs | Identity generation, inspection, signing, verification, encryption, decryption, and export. | +| rnprobe-rs | Destination probe utility with loss and round-trip reporting. | +| rncp-rs | File transfer utility with send, listen, and authenticated fetch modes. | +| rnodeconf-rs | RNode inspection, safe configuration, EEPROM backup, and trust utility. | +| rnsh-rs | Reticulum shell listener/client. | + +#### Commands: + +```text +rnsd-rs [-c CONFIG_DIR] [-v|-q]... [--service] [--exampleconfig] [--version] +rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|held] + [--reverse] [--announce-stats] [--link-stats] [--totals] [--json] + [--discovered|-D] [-m [-I SECONDS]] [FILTER] + [-R -i ] +rnpath-rs [--table|--rates] [destination_hash] [--max HOPS] +rnpath-rs +rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] +rnid-rs generate|show|sign|verify|encrypt|decrypt|export ... +rncp-rs +rncp-rs -l [-b SECONDS] [-s DEST_DIR] [-a ]... +rncp-rs -l -F [-j ] [-a |-n]... +rncp-rs -f [-s DEST_DIR] +``` + +Add the release `bin/` directory or `target/release` to `PATH` if +you want to call them without a path prefix. + +`rncp-rs` follows the established listener authentication model: without `-n`, +incoming senders must match `-a ` or an `allowed_identities` file. +`rncp-rs -F` can serve fetch requests to authenticated clients; use +`-j ` to bound file access unless unrestricted fetch paths are +intentional. + +`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM +dump/backup, and trusted-key storage. + +## Configuration + +`rnsd-rs` reads Reticulum INI config from `/config`. If no config +directory is supplied, the default is: + +| Platform | Default config file | +| --- | --- | +| Linux/macOS | `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then `~/.rsReticulum/config` | +| Windows | `%APPDATA%\rsReticulum\config` | + +Generate the annotated starter file: + +```bash +rnsd-rs --exampleconfig +``` + +Minimal TCP client example: + +```ini +[reticulum] +share_instance = yes +instance_control_socket = yes +enable_transport = no + +[interfaces] + + [[Default TCP]] + type = TCPClientInterface + enabled = yes + target_host = rns.ratspeak.org + target_port = 4242 +``` + +Existing Python Reticulum configs should work if every requested interface +is implemented here. Unknown or not-yet-wired interfaces should be removed or +disabled until support lands. + +The default shared-instance data/control ports are `37428`/`37429`. Ratspeak +uses app-private `37430`/`37431` ports. If you run two daemons at the same +time, give one config a distinct port pair to avoid confliction, like: + +```ini +[reticulum] +shared_instance_port = 37432 +instance_control_port = 37433 +``` + +## Interface Support + +###### Note: This is alpha, if something doesn't work, open an issue with enough context/information to help contribute to fixing it. + +| Interface | Current behavior | +| --- | --- | +| TCP client/server | Config-backed IPv4 and IPv6 paths. | +| UDP | Config-backed unicast and multicast paths. | +| Auto | Config-backed UDP discovery plus TCP fallback. | +| Local shared instance | Config-backed TCP loopback or Unix socket depending on platform. | +| I2P | Config-backed SAM v3.1 path. | +| Pipe | Config-backed subprocess stdio pipe. | +| Backbone | Config-backed high-latency WAN-style tunnel. | +| Serial, KISS, RNode, RNode Multi, AX.25 KISS | Config-backed with the `serial` feature. | +| BLE RNode | Config-backed with the `ble` feature. | +| Bluetooth Peer | Runtime API used by Ratspeak. | +| Android USB-OTG | Runtime API for Android app embeddings. | +| Weave | Not implemented. | +| Bluetooth Classic RFCOMM | Not implemented. | + +## Compatibility Notes + +Most daemon and utility flows are implemented for the public `*-rs` tools: +`rnsd-rs`, `rnstatus-rs`, `rnpath-rs`, `rnid-rs`, `rnprobe-rs`, `rncp-rs`, +`rnsh-rs`, and `rnodeconf-rs`. + +Known gaps and intentional limits: + +- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented. There is on-going work in progress for supporting these. +- `rnodeconf-rs` is partial; safe inspection/configuration and EEPROM + dump/backup are furthest along. Firmware flashing, autoinstall/update, ROM + bootstrap, destructive EEPROM wipe, and full signing-key management are not + implemented. +- `rnstatus-rs` covers the practical operator surface, but does not implement + every display/API behavior from upstream. +- `rnpath-rs` remote mode is read-only for table/rates, including destination + filters, apart from the remote blackhole-list query path. Remote mutations + and remote active path requests are full gaps. +- `rncp-rs` implements the listener `-b` announce interval. `-P/--phy-rates` + is not supported for the time being. +- `rns-ratkey` hardware identity support is feature-gated and still has known + hardware-verification gaps before it should be described as release-ready. + +## Contributing + +If the issue or contribution belongs upstream as well, start there. Python LXMF +and Reticulum remain the reference implementations. + +PRs are closed for now until I have time to catch up on everything. I'm tired. + +## License + +GNU Affero General Public License v3.0 or later. See [LICENSE](LICENSE). diff --git a/crates/rns-crypto/Cargo.toml b/crates/rns-crypto/Cargo.toml new file mode 100644 index 0000000..56d1bff --- /dev/null +++ b/crates/rns-crypto/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "rns-crypto" +description = "Cryptographic primitives for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[features] +default = ["std"] +std = [] + +[dependencies] +x25519-dalek = { workspace = true } +ed25519-dalek = { workspace = true } +aes = { workspace = true } +cbc = { workspace = true } +hkdf = { workspace = true } +hmac = { workspace = true } +sha2 = { workspace = true } +subtle = { workspace = true } +rand = { workspace = true } +rand_core = { workspace = true } +zeroize = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +hex = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/rns-crypto/src/aes_cbc.rs b/crates/rns-crypto/src/aes_cbc.rs new file mode 100644 index 0000000..da97b69 --- /dev/null +++ b/crates/rns-crypto/src/aes_cbc.rs @@ -0,0 +1,181 @@ +//! AES-CBC, no padding (callers use [`crate::pkcs7`]). Key length selects: +//! 16 → AES-128, 32 → AES-256. Wire negotiates AES-256; AES-128 kept for +//! legacy Token material. + +use aes::{Aes128, Aes256}; +use alloc::vec::Vec; +use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit}; +use cbc::{Decryptor, Encryptor}; +use thiserror::Error; + +/// Errors surfaced by [`encrypt`] and [`decrypt`]. +#[derive(Debug, Error)] +pub enum AesCbcError { + /// Key must be exactly 16 bytes (AES-128) or 32 bytes (AES-256). + #[error("invalid key length: expected 16 or 32, got {0}")] + InvalidKeyLength(usize), + /// IV must be exactly 16 bytes. + #[error("invalid IV length: expected 16, got {0}")] + InvalidIvLength(usize), + /// Input length is not a non-zero multiple of 16. + #[error("input not aligned to 16-byte block boundary")] + NotBlockAligned, + /// Underlying cipher reported a decrypt failure. + #[error("decryption failed")] + DecryptionFailed, + /// Underlying cipher reported an encrypt failure. + #[error("encryption failed")] + EncryptionFailed, +} + +/// AES-CBC encrypt. Caller pads; `plaintext.len()` must be a non-zero +/// multiple of 16. IV must be 16 bytes. +pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result, AesCbcError> { + if iv.len() != 16 { + return Err(AesCbcError::InvalidIvLength(iv.len())); + } + if plaintext.is_empty() || !plaintext.len().is_multiple_of(16) { + return Err(AesCbcError::NotBlockAligned); + } + + let mut buf = plaintext.to_vec(); + match key.len() { + 16 => { + let enc = Encryptor::::new_from_slices(key, iv) + .map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?; + enc.encrypt_padded_mut::( + &mut buf, + plaintext.len(), + ) + .map_err(|_| AesCbcError::EncryptionFailed)?; + } + 32 => { + let enc = Encryptor::::new_from_slices(key, iv) + .map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?; + enc.encrypt_padded_mut::( + &mut buf, + plaintext.len(), + ) + .map_err(|_| AesCbcError::EncryptionFailed)?; + } + n => return Err(AesCbcError::InvalidKeyLength(n)), + } + Ok(buf) +} + +/// AES-CBC decrypt. Output is still PKCS7-padded; caller strips it. +pub fn decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result, AesCbcError> { + if iv.len() != 16 { + return Err(AesCbcError::InvalidIvLength(iv.len())); + } + if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) { + return Err(AesCbcError::NotBlockAligned); + } + + let mut buf = ciphertext.to_vec(); + match key.len() { + 16 => { + let dec = Decryptor::::new_from_slices(key, iv) + .map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?; + dec.decrypt_padded_mut::(&mut buf) + .map_err(|_| AesCbcError::DecryptionFailed)?; + } + 32 => { + let dec = Decryptor::::new_from_slices(key, iv) + .map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?; + dec.decrypt_padded_mut::(&mut buf) + .map_err(|_| AesCbcError::DecryptionFailed)?; + } + n => return Err(AesCbcError::InvalidKeyLength(n)), + } + Ok(buf) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_roundtrip() { + let key = [0x42u8; 32]; + let iv = [0x01u8; 16]; + let plaintext = [0xABu8; 16]; + + let ct = encrypt(&key, &iv, &plaintext).unwrap(); + assert_eq!(ct.len(), 16); + assert_ne!(&ct[..], &plaintext[..]); + + let pt = decrypt(&key, &iv, &ct).unwrap(); + assert_eq!(&pt[..], &plaintext[..]); + } + + #[test] + fn test_roundtrip_multi_block() { + let key = [0x42u8; 32]; + let iv = [0x01u8; 16]; + let plaintext = [0xABu8; 48]; + + let ct = encrypt(&key, &iv, &plaintext).unwrap(); + assert_eq!(ct.len(), 48); + + let pt = decrypt(&key, &iv, &ct).unwrap(); + assert_eq!(&pt[..], &plaintext[..]); + } + + #[test] + fn test_invalid_key_length() { + // 24-byte (AES-192) keys are not part of the RNS Token spec. + let key = [0u8; 24]; + let iv = [0u8; 16]; + let data = [0u8; 16]; + assert!(encrypt(&key, &iv, &data).is_err()); + } + + #[test] + fn test_not_block_aligned() { + let key = [0u8; 32]; + let iv = [0u8; 16]; + let data = [0u8; 15]; + assert!(encrypt(&key, &iv, &data).is_err()); + } + + #[test] + fn test_aes128_roundtrip() { + let key = [0x42u8; 16]; + let iv = [0x01u8; 16]; + let plaintext = [0xABu8; 16]; + + let ct = encrypt(&key, &iv, &plaintext).unwrap(); + assert_eq!(ct.len(), 16); + assert_ne!(&ct[..], &plaintext[..]); + + let pt = decrypt(&key, &iv, &ct).unwrap(); + assert_eq!(&pt[..], &plaintext[..]); + } + + #[test] + fn test_aes128_multi_block() { + let key = [0x42u8; 16]; + let iv = [0x01u8; 16]; + let plaintext = [0xABu8; 48]; + + let ct = encrypt(&key, &iv, &plaintext).unwrap(); + assert_eq!(ct.len(), 48); + + let pt = decrypt(&key, &iv, &ct).unwrap(); + assert_eq!(&pt[..], &plaintext[..]); + } + + /// Different key sizes must produce different ciphertexts for the same input. + #[test] + fn test_aes128_vs_aes256_distinct_ciphertexts() { + let key128 = [0x42u8; 16]; + let key256 = [0x42u8; 32]; + let iv = [0x01u8; 16]; + let plaintext = [0xABu8; 16]; + + let ct128 = encrypt(&key128, &iv, &plaintext).unwrap(); + let ct256 = encrypt(&key256, &iv, &plaintext).unwrap(); + assert_ne!(ct128, ct256); + } +} diff --git a/crates/rns-crypto/src/ed25519.rs b/crates/rns-crypto/src/ed25519.rs new file mode 100644 index 0000000..8b8e4e8 --- /dev/null +++ b/crates/rns-crypto/src/ed25519.rs @@ -0,0 +1,173 @@ +//! Ed25519 signing and verification. + +use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use rand_core::OsRng; +use thiserror::Error; +use zeroize::Zeroize; + +/// Errors surfaced by Ed25519 sign/verify. +#[derive(Debug, Error)] +pub enum Ed25519Error { + /// `verify` rejected the signature. + #[error("signature verification failed")] + VerificationFailed, + /// Public key bytes were not a valid Ed25519 point. + #[error("invalid public key bytes")] + InvalidPublicKey, + /// Signature bytes could not be decoded as an Ed25519 signature. + #[error("invalid signature bytes")] + InvalidSignature, +} + +/// Ed25519 private key (32-byte seed). +/// +/// Key material is zeroized on drop. +pub struct Ed25519PrivateKey { + key: SigningKey, +} + +impl Zeroize for Ed25519PrivateKey { + fn zeroize(&mut self) { + // Assignment drops the prior `SigningKey` (ZeroizeOnDrop), leaving a zero seed. + self.key = SigningKey::from_bytes(&[0u8; 32]); + } +} + +impl Drop for Ed25519PrivateKey { + fn drop(&mut self) { + self.zeroize(); + } +} + +/// Ed25519 public key (32 bytes, compressed Edwards point). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Ed25519PublicKey { + key: VerifyingKey, +} + +impl Ed25519PrivateKey { + /// Generate a random key from the OS CSPRNG. + pub fn generate() -> Self { + Self { + key: SigningKey::generate(&mut OsRng), + } + } + + /// Construct from a 32-byte seed. + pub fn from_bytes(seed: &[u8; 32]) -> Self { + Self { + key: SigningKey::from_bytes(seed), + } + } + + /// Return the 32-byte seed. + pub fn to_bytes(&self) -> [u8; 32] { + self.key.to_bytes() + } + + /// Derive the corresponding public key. + pub fn public_key(&self) -> Ed25519PublicKey { + Ed25519PublicKey { + key: self.key.verifying_key(), + } + } + + /// Produce a 64-byte Ed25519 signature (R || S) over `message`. + pub fn sign(&self, message: &[u8]) -> [u8; 64] { + let sig = self.key.sign(message); + sig.to_bytes() + } +} + +impl Ed25519PublicKey { + /// Parse a 32-byte compressed Edwards point. + pub fn from_bytes(bytes: &[u8; 32]) -> Result { + let key = VerifyingKey::from_bytes(bytes).map_err(|_| Ed25519Error::InvalidPublicKey)?; + Ok(Self { key }) + } + + /// Return the 32-byte encoded public key. + pub fn to_bytes(&self) -> [u8; 32] { + self.key.to_bytes() + } + + /// Verify a 64-byte Ed25519 signature over `message`. + pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> Result<(), Ed25519Error> { + let sig = Signature::from_bytes(signature); + self.key + .verify(message, &sig) + .map_err(|_| Ed25519Error::VerificationFailed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_key_generation() { + let prv = Ed25519PrivateKey::generate(); + let pub_key = prv.public_key(); + assert_ne!(pub_key.to_bytes(), [0u8; 32]); + } + + #[test] + fn test_sign_verify() { + let prv = Ed25519PrivateKey::generate(); + let pub_key = prv.public_key(); + let msg = b"test message"; + + let sig = prv.sign(msg); + assert!(pub_key.verify(msg, &sig).is_ok()); + } + + #[test] + fn test_wrong_message() { + let prv = Ed25519PrivateKey::generate(); + let pub_key = prv.public_key(); + + let sig = prv.sign(b"correct"); + assert!(pub_key.verify(b"wrong", &sig).is_err()); + } + + #[test] + fn test_wrong_key() { + let prv1 = Ed25519PrivateKey::generate(); + let prv2 = Ed25519PrivateKey::generate(); + let msg = b"test"; + + let sig = prv1.sign(msg); + assert!(prv2.public_key().verify(msg, &sig).is_err()); + } + + #[test] + fn test_deterministic_from_seed() { + let seed = [42u8; 32]; + let prv1 = Ed25519PrivateKey::from_bytes(&seed); + let prv2 = Ed25519PrivateKey::from_bytes(&seed); + + let msg = b"deterministic"; + assert_eq!(prv1.sign(msg), prv2.sign(msg)); + assert_eq!(prv1.public_key().to_bytes(), prv2.public_key().to_bytes()); + } + + #[test] + fn test_seed_roundtrip() { + let prv = Ed25519PrivateKey::generate(); + let seed = prv.to_bytes(); + let prv2 = Ed25519PrivateKey::from_bytes(&seed); + assert_eq!(prv.public_key().to_bytes(), prv2.public_key().to_bytes()); + } + + #[test] + fn test_public_key_roundtrip() { + let prv = Ed25519PrivateKey::generate(); + let pub_bytes = prv.public_key().to_bytes(); + let pub_key = Ed25519PublicKey::from_bytes(&pub_bytes).unwrap(); + assert_eq!(pub_key.to_bytes(), pub_bytes); + + let msg = b"roundtrip"; + let sig = prv.sign(msg); + assert!(pub_key.verify(msg, &sig).is_ok()); + } +} diff --git a/crates/rns-crypto/src/hkdf.rs b/crates/rns-crypto/src/hkdf.rs new file mode 100644 index 0000000..e3aea37 --- /dev/null +++ b/crates/rns-crypto/src/hkdf.rs @@ -0,0 +1,88 @@ +//! HKDF-SHA256 key derivation (RFC 5869). + +use alloc::vec; +use alloc::vec::Vec; +use hkdf::Hkdf; +use sha2::Sha256; +use thiserror::Error; + +/// Per RFC 5869, HKDF-SHA256 can emit at most 255 * HashLen = 8160 bytes. +const MAX_OUTPUT_LENGTH: usize = 255 * 32; + +/// Errors surfaced by [`hkdf_sha256`]. +#[derive(Debug, Error)] +pub enum HkdfError { + /// Requested output length exceeds the RFC 5869 cap (8160 bytes). + #[error("requested length {0} exceeds maximum HKDF output of {MAX_OUTPUT_LENGTH} bytes")] + OutputTooLong(usize), + /// Underlying HKDF expand call returned an error. + #[error("HKDF expansion failed")] + ExpansionFailed, +} + +/// HKDF-SHA256 key derivation (RFC 5869). +/// +/// `length` is capped at 8160 bytes. `salt = None` uses 32 zero bytes as +/// specified by the RFC; `info = None` uses an empty context string. +pub fn hkdf_sha256( + length: usize, + ikm: &[u8], + salt: Option<&[u8]>, + info: Option<&[u8]>, +) -> Result, HkdfError> { + if length > MAX_OUTPUT_LENGTH { + return Err(HkdfError::OutputTooLong(length)); + } + + let hk = Hkdf::::new(salt, ikm); + let mut okm = vec![0u8; length]; + hk.expand(info.unwrap_or(b""), &mut okm) + .map_err(|_| HkdfError::ExpansionFailed)?; + Ok(okm) +} + +/// Derive the 64-byte session key used for RNS link encryption: +/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=identity_hash, info=None)`. +pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<[u8; 64], HkdfError> { + let okm = hkdf_sha256(64, shared_secret, Some(salt), None)?; + let mut out = [0u8; 64]; + out.copy_from_slice(&okm); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hkdf_rfc5869_vector1() { + // RFC 5869 Test Case 1. + let ikm = hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(); + let salt = hex::decode("000102030405060708090a0b0c").unwrap(); + let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap(); + + let okm = hkdf_sha256(42, &ikm, Some(&salt), Some(&info)).unwrap(); + let expected = + "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"; + assert_eq!(hex::encode(&okm), expected); + } + + #[test] + fn test_hkdf_max_length_exceeded() { + let result = hkdf_sha256(MAX_OUTPUT_LENGTH + 1, b"test", None, None); + assert!(result.is_err()); + } + + #[test] + fn test_hkdf_no_salt() { + let result = hkdf_sha256(32, b"test_ikm", None, None); + assert!(result.is_ok()); + assert_eq!(result.unwrap().len(), 32); + } + + #[test] + fn test_derive_key_64() { + let key = derive_key_64(b"shared_secret", b"salt_value").unwrap(); + assert_eq!(key.len(), 64); + } +} diff --git a/crates/rns-crypto/src/hmac.rs b/crates/rns-crypto/src/hmac.rs new file mode 100644 index 0000000..e663b62 --- /dev/null +++ b/crates/rns-crypto/src/hmac.rs @@ -0,0 +1,60 @@ +//! HMAC-SHA256 tag computation and constant-time verification. + +use hmac::{Hmac, Mac}; +use sha2::Sha256; + +type HmacSha256 = Hmac; + +/// HMAC-SHA256 (RFC 2104), returning the 32-byte tag. +pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] { + let mut mac = HmacSha256::new_from_slice(key).expect("HMAC-SHA256 accepts any key length"); + mac.update(data); + mac.finalize().into_bytes().into() +} + +/// Verify an HMAC-SHA256 tag in constant time. +pub fn hmac_verify(key: &[u8], data: &[u8], expected: &[u8; 32]) -> bool { + use subtle::ConstantTimeEq; + let computed = hmac_sha256(key, data); + computed.ct_eq(expected).into() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hmac_sha256_rfc4231_vector1() { + // RFC 4231 Test Case 1. + let key = [0x0b; 20]; + let data = b"Hi There"; + let expected = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; + assert_eq!(hex::encode(hmac_sha256(&key, data)), expected); + } + + #[test] + fn test_hmac_sha256_rfc4231_vector2() { + // RFC 4231 Test Case 2. + let key = b"Jefe"; + let data = b"what do ya want for nothing?"; + let expected = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"; + assert_eq!(hex::encode(hmac_sha256(key, data)), expected); + } + + #[test] + fn test_hmac_verify_correct() { + let key = b"test_key"; + let data = b"test_data"; + let mac = hmac_sha256(key, data); + assert!(hmac_verify(key, data, &mac)); + } + + #[test] + fn test_hmac_verify_wrong() { + let key = b"test_key"; + let data = b"test_data"; + let mut mac = hmac_sha256(key, data); + mac[0] ^= 1; + assert!(!hmac_verify(key, data, &mac)); + } +} diff --git a/crates/rns-crypto/src/lib.rs b/crates/rns-crypto/src/lib.rs new file mode 100644 index 0000000..3a5b4f3 --- /dev/null +++ b/crates/rns-crypto/src/lib.rs @@ -0,0 +1,30 @@ +//! Cryptographic primitives for Reticulum. Constants, derivation inputs, and +//! wire-visible byte layouts match the Python reference (`RNS/Cryptography/`) +//! exactly — downstream interop depends on it. `no_std + alloc` when `std` is off. +#![cfg_attr(not(feature = "std"), no_std)] +#![warn(missing_docs)] +extern crate alloc; + +pub mod aes_cbc; +pub mod ed25519; +pub mod hkdf; +pub mod hmac; +pub mod pkcs7; +pub mod random; +pub mod sha; +pub mod token; +pub mod x25519; + +pub use token::TOKEN_OVERHEAD; + +use alloc::string::String; +use core::fmt::Write; + +/// Lower-case hex encoding of `bytes`. +pub fn hex_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + let _ = write!(&mut out, "{b:02x}"); + } + out +} diff --git a/crates/rns-crypto/src/pkcs7.rs b/crates/rns-crypto/src/pkcs7.rs new file mode 100644 index 0000000..4ca0998 --- /dev/null +++ b/crates/rns-crypto/src/pkcs7.rs @@ -0,0 +1,127 @@ +//! PKCS7 padding for 16-byte block ciphers (AES-CBC). + +use alloc::vec::Vec; +use thiserror::Error; + +const BLOCK_SIZE: usize = 16; + +/// Errors surfaced by [`unpad`]. +#[derive(Debug, Error)] +pub enum Pkcs7Error { + /// Trailing byte is zero or greater than the 16-byte block size. + #[error("invalid padding: padding byte value {0} exceeds block size {BLOCK_SIZE}")] + InvalidPaddingValue(u8), + /// The declared padding length doesn't match the trailing bytes. + #[error("invalid padding: inconsistent padding bytes")] + InconsistentPadding, + /// Input contained zero bytes. + #[error("invalid padding: empty input")] + EmptyInput, +} + +/// Apply PKCS7 padding for a 16-byte block size. +/// +/// Block-aligned inputs are still padded — a full 0x10 block is appended, +/// per the RFC 5652 construction. +pub fn pad(data: &[u8]) -> Vec { + let pad_len = BLOCK_SIZE - (data.len() % BLOCK_SIZE); + let mut out = Vec::with_capacity(data.len() + pad_len); + out.extend_from_slice(data); + out.extend(core::iter::repeat_n(pad_len as u8, pad_len)); + out +} + +/// Strip PKCS7 padding for a 16-byte block size. +/// +/// All padding bytes are validated; a mismatch returns an error. +pub fn unpad(data: &[u8]) -> Result<&[u8], Pkcs7Error> { + if data.is_empty() { + return Err(Pkcs7Error::EmptyInput); + } + let pad_byte = data[data.len() - 1]; + if pad_byte == 0 || pad_byte as usize > BLOCK_SIZE { + return Err(Pkcs7Error::InvalidPaddingValue(pad_byte)); + } + let pad_len = pad_byte as usize; + if pad_len > data.len() { + return Err(Pkcs7Error::InvalidPaddingValue(pad_byte)); + } + let start = data.len() - pad_len; + for &b in &data[start..] { + if b != pad_byte { + return Err(Pkcs7Error::InconsistentPadding); + } + } + Ok(&data[..start]) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + #[test] + fn test_pad_block_aligned() { + // Block-aligned input gets a full 0x10 padding block. + let input = [0u8; 16]; + let padded = pad(&input); + assert_eq!(padded.len(), 32); + assert!(padded[16..].iter().all(|&b| b == 16)); + } + + #[test] + fn test_pad_one_byte() { + let padded = pad(b"a"); + assert_eq!(padded.len(), 16); + assert_eq!(padded[0], b'a'); + assert!(padded[1..].iter().all(|&b| b == 15)); + } + + #[test] + fn test_pad_fifteen_bytes() { + let input = [0x41u8; 15]; + let padded = pad(&input); + assert_eq!(padded.len(), 16); + assert_eq!(padded[15], 1); + } + + #[test] + fn test_roundtrip() { + for len in 0..64 { + let data = vec![0xABu8; len]; + let padded = pad(&data); + let unpadded = unpad(&padded).unwrap(); + assert_eq!(unpadded, &data[..]); + } + } + + #[test] + fn test_unpad_empty() { + assert!(unpad(b"").is_err()); + } + + #[test] + fn test_unpad_invalid_zero() { + let mut data = [0u8; 16]; + data[15] = 0; + assert!(unpad(&data).is_err()); + } + + #[test] + fn test_unpad_invalid_too_large() { + let mut data = [0u8; 16]; + data[15] = 17; + assert!(unpad(&data).is_err()); + } + + #[test] + fn test_unpad_inconsistent_padding() { + // Last byte declares 4 pad bytes, but data[12] is not 4. + let mut data = vec![0x41u8; 16]; + data[15] = 4; + data[14] = 4; + data[13] = 4; + data[12] = 99; + assert!(matches!(unpad(&data), Err(Pkcs7Error::InconsistentPadding))); + } +} diff --git a/crates/rns-crypto/src/random.rs b/crates/rns-crypto/src/random.rs new file mode 100644 index 0000000..966f776 --- /dev/null +++ b/crates/rns-crypto/src/random.rs @@ -0,0 +1,52 @@ +//! OS-CSPRNG-backed random byte helpers. + +use alloc::vec; +use alloc::vec::Vec; +use rand::RngCore; +use rand_core::OsRng; + +/// Cryptographically secure random bytes from the OS CSPRNG. +pub fn random_bytes(len: usize) -> Vec { + let mut buf = vec![0u8; len]; + OsRng.fill_bytes(&mut buf); + buf +} + +/// 16 random bytes, sized for AES IVs and truncated hashes. +pub fn random_16() -> [u8; 16] { + let mut buf = [0u8; 16]; + OsRng.fill_bytes(&mut buf); + buf +} + +/// 32 random bytes. +pub fn random_32() -> [u8; 32] { + let mut buf = [0u8; 32]; + OsRng.fill_bytes(&mut buf); + buf +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_random_bytes_length() { + assert_eq!(random_bytes(0).len(), 0); + assert_eq!(random_bytes(16).len(), 16); + assert_eq!(random_bytes(64).len(), 64); + } + + #[test] + fn test_random_not_zero() { + let r = random_32(); + assert!(r.iter().any(|&b| b != 0)); + } + + #[test] + fn test_random_unique() { + let a = random_32(); + let b = random_32(); + assert_ne!(a, b); + } +} diff --git a/crates/rns-crypto/src/sha.rs b/crates/rns-crypto/src/sha.rs new file mode 100644 index 0000000..a38c005 --- /dev/null +++ b/crates/rns-crypto/src/sha.rs @@ -0,0 +1,80 @@ +//! SHA-256 / SHA-512 digests. + +use sha2::{Digest, Sha256, Sha512}; + +/// SHA-256 hash. +pub fn sha256(data: &[u8]) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(data); + hasher.finalize().into() +} + +/// SHA-512 hash. +pub fn sha512(data: &[u8]) -> [u8; 64] { + let mut hasher = Sha512::new(); + hasher.update(data); + hasher.finalize().into() +} + +/// SHA-256 truncated to 128 bits, used for destination and identity hashes. +pub fn truncated_hash(data: &[u8]) -> [u8; 16] { + let full = sha256(data); + let mut out = [0u8; 16]; + out.copy_from_slice(&full[..16]); + out +} + +/// Alias for [`sha256`]. +pub fn full_hash(data: &[u8]) -> [u8; 32] { + sha256(data) +} + +/// SHA-256 of an app-name string truncated to 80 bits. +pub fn name_hash(name: &str) -> [u8; 10] { + let full = sha256(name.as_bytes()); + let mut out = [0u8; 10]; + out.copy_from_slice(&full[..10]); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sha256_empty() { + let hash = sha256(b""); + let expected = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + assert_eq!(hex::encode(hash), expected); + } + + #[test] + fn test_sha256_hello() { + let hash = sha256(b"hello"); + let expected = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + assert_eq!(hex::encode(hash), expected); + } + + #[test] + fn test_sha512_empty() { + let hash = sha512(b""); + let expected = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; + assert_eq!(hex::encode(hash), expected); + } + + #[test] + fn test_truncated_hash() { + let hash = truncated_hash(b"test"); + assert_eq!(hash.len(), 16); + let full = sha256(b"test"); + assert_eq!(&hash[..], &full[..16]); + } + + #[test] + fn test_name_hash() { + let hash = name_hash("test.app"); + assert_eq!(hash.len(), 10); + let full = sha256(b"test.app"); + assert_eq!(&hash[..], &full[..10]); + } +} diff --git a/crates/rns-crypto/src/token.rs b/crates/rns-crypto/src/token.rs new file mode 100644 index 0000000..dd9a349 --- /dev/null +++ b/crates/rns-crypto/src/token.rs @@ -0,0 +1,253 @@ +//! RNS encryption token: AES-256-CBC + HMAC-SHA256 over an IV-prefixed ciphertext. + +use alloc::vec::Vec; +use thiserror::Error; + +use crate::aes_cbc; +use crate::hmac::{hmac_sha256, hmac_verify}; +use crate::pkcs7; +use crate::random::random_16; + +/// IV (16) + HMAC (32). A token is this plus the PKCS7-padded ciphertext. +pub const TOKEN_OVERHEAD: usize = 48; + +/// Errors surfaced by [`encrypt`] and [`decrypt`]. +#[derive(Debug, Error)] +pub enum TokenError { + /// Key must be 32 or 64 bytes. + #[error("invalid key length: expected 32 or 64, got {0}")] + InvalidKeyLength(usize), + /// Token is shorter than [`TOKEN_OVERHEAD`] so cannot contain IV + HMAC. + #[error("token too short for decryption")] + TooShort, + /// HMAC tag did not validate. + #[error("authentication failed")] + AuthenticationFailed, + /// Underlying AES-CBC decrypt returned an error. + #[error("decryption failed")] + DecryptionFailed, + /// Underlying AES-CBC encrypt returned an error. + #[error("encryption failed")] + EncryptionFailed, +} + +/// Split a token key into `(signing_key, encryption_key)`. +/// 64 → 32/32 (AES-256 + HMAC-SHA256); 32 → 16/16 (AES-128, legacy). +fn split_key(key: &[u8]) -> Result<(&[u8], &[u8]), TokenError> { + match key.len() { + 64 => Ok((&key[..32], &key[32..])), + 32 => Ok((&key[..16], &key[16..])), + n => Err(TokenError::InvalidKeyLength(n)), + } +} + +/// Token encrypt (Modified Fernet — no version byte, no timestamp). +/// Wire: `IV(16) || AES-CBC(PKCS7(plaintext)) || HMAC-SHA256(IV || ciphertext)(32)`. +pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result, TokenError> { + let (signing_key, encryption_key) = split_key(key)?; + + let iv = random_16(); + let padded = pkcs7::pad(plaintext); + + let ciphertext = + aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?; + + let mut signed_parts = Vec::with_capacity(16 + ciphertext.len()); + signed_parts.extend_from_slice(&iv); + signed_parts.extend_from_slice(&ciphertext); + + let mac = hmac_sha256(signing_key, &signed_parts); + + let mut token = signed_parts; + token.extend_from_slice(&mac); + + Ok(token) +} + +/// Token decrypt. All failure modes collapse to `AuthenticationFailed` +/// (padding-oracle defence). HMAC comparison is constant-time. +pub fn decrypt(token: &[u8], key: &[u8]) -> Result, TokenError> { + let (signing_key, encryption_key) = split_key(key)?; + + // Minimum well-formed token: IV(16) + one AES block(16) + HMAC(32). + if token.len() < 64 { + return Err(TokenError::AuthenticationFailed); + } + + let split_point = token.len() - 32; + let signed_parts = &token[..split_point]; + let received_hmac: &[u8; 32] = token[split_point..].try_into().unwrap(); + + if !hmac_verify(signing_key, signed_parts, received_hmac) { + return Err(TokenError::AuthenticationFailed); + } + + let iv = &signed_parts[..16]; + let ciphertext = &signed_parts[16..]; + + if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) { + return Err(TokenError::AuthenticationFailed); + } + + let padded = aes_cbc::decrypt(encryption_key, iv, ciphertext) + .map_err(|_| TokenError::AuthenticationFailed)?; + + let plaintext = pkcs7::unpad(&padded).map_err(|_| TokenError::AuthenticationFailed)?; + + Ok(plaintext.to_vec()) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + #[test] + fn test_encrypt_decrypt_roundtrip() { + let key = [0x42u8; 64]; + let plaintext = b"hello, reticulum!"; + + let token = encrypt(plaintext, &key).unwrap(); + let decrypted = decrypt(&token, &key).unwrap(); + assert_eq!(&decrypted, plaintext); + } + + #[test] + fn test_encrypt_produces_correct_structure() { + let key = [0x42u8; 64]; + let plaintext = b"test"; + + let token = encrypt(plaintext, &key).unwrap(); + // IV(16) + ciphertext(16) + HMAC(32) = 64. + assert_eq!(token.len(), 64); + } + + #[test] + fn test_encrypt_empty() { + let key = [0x42u8; 64]; + let token = encrypt(b"", &key).unwrap(); + assert_eq!(token.len(), 64); + let decrypted = decrypt(&token, &key).unwrap(); + assert!(decrypted.is_empty()); + } + + #[test] + fn test_encrypt_block_aligned() { + let key = [0x42u8; 64]; + // Block-aligned input forces a full extra padding block. + let plaintext = [0xABu8; 16]; + let token = encrypt(&plaintext, &key).unwrap(); + assert_eq!(token.len(), 80); + let decrypted = decrypt(&token, &key).unwrap(); + assert_eq!(&decrypted, &plaintext); + } + + #[test] + fn test_wrong_key_fails() { + let key1 = [0x42u8; 64]; + let key2 = [0x43u8; 64]; + let plaintext = b"secret"; + + let token = encrypt(plaintext, &key1).unwrap(); + assert!(decrypt(&token, &key2).is_err()); + } + + #[test] + fn test_tampered_ciphertext_fails() { + let key = [0x42u8; 64]; + let plaintext = b"secret"; + + let mut token = encrypt(plaintext, &key).unwrap(); + // Offset 20 lies inside the ciphertext, after the 16-byte IV. + token[20] ^= 0xFF; + assert!(decrypt(&token, &key).is_err()); + } + + #[test] + fn test_tampered_hmac_fails() { + let key = [0x42u8; 64]; + let plaintext = b"secret"; + + let mut token = encrypt(plaintext, &key).unwrap(); + let last = token.len() - 1; + token[last] ^= 0xFF; + assert!(decrypt(&token, &key).is_err()); + } + + #[test] + fn test_too_short_token() { + let key = [0x42u8; 64]; + assert!(decrypt(&[0u8; 63], &key).is_err()); + } + + #[test] + fn test_invalid_key_length() { + assert!(encrypt(b"test", &[0u8; 48]).is_err()); + assert!(decrypt(&[0u8; 64], &[0u8; 48]).is_err()); + } + + #[test] + fn test_various_lengths() { + let key = [0x42u8; 64]; + for len in 0..256 { + let plaintext = vec![0xABu8; len]; + let token = encrypt(&plaintext, &key).unwrap(); + let decrypted = decrypt(&token, &key).unwrap(); + assert_eq!(decrypted, plaintext, "failed for length {len}"); + } + } + + #[test] + fn test_unique_ciphertexts() { + // Random IV must produce distinct ciphertexts for the same input. + let key = [0x42u8; 64]; + let plaintext = b"same input"; + let t1 = encrypt(plaintext, &key).unwrap(); + let t2 = encrypt(plaintext, &key).unwrap(); + assert_ne!(t1, t2); + } + + /// Legacy AES-128 round-trip via 32-byte key (Python `Token.py:62-65`). + #[test] + fn test_encrypt_decrypt_roundtrip_aes128() { + let key = [0x42u8; 32]; + let plaintext = b"hello legacy reticulum"; + + let token = encrypt(plaintext, &key).unwrap(); + let decrypted = decrypt(&token, &key).unwrap(); + assert_eq!(&decrypted, plaintext); + } + + #[test] + fn test_encrypt_aes128_structure() { + let key = [0x42u8; 32]; + let plaintext = b"test"; + + let token = encrypt(plaintext, &key).unwrap(); + assert_eq!(token.len(), 64); + } + + #[test] + fn test_aes128_tampered_ciphertext_fails() { + let key = [0x42u8; 32]; + let plaintext = b"secret"; + + let mut token = encrypt(plaintext, &key).unwrap(); + token[20] ^= 0xFF; + assert!(decrypt(&token, &key).is_err()); + } + + /// A token under one key size must not decrypt with the other. + #[test] + fn test_token_key_size_isolation() { + let key128 = [0x42u8; 32]; + let key256 = [0x42u8; 64]; + let plaintext = b"isolated"; + + let t128 = encrypt(plaintext, &key128).unwrap(); + let t256 = encrypt(plaintext, &key256).unwrap(); + + assert!(decrypt(&t128, &key256).is_err()); + assert!(decrypt(&t256, &key128).is_err()); + } +} diff --git a/crates/rns-crypto/src/x25519.rs b/crates/rns-crypto/src/x25519.rs new file mode 100644 index 0000000..0d91d9d --- /dev/null +++ b/crates/rns-crypto/src/x25519.rs @@ -0,0 +1,121 @@ +//! X25519 Diffie-Hellman primitives. + +use rand_core::OsRng; +use x25519_dalek::{PublicKey, StaticSecret}; +use zeroize::Zeroize; + +/// X25519 private key (32 bytes, clamped scalar). +/// +/// Key material is zeroized on drop. +pub struct X25519PrivateKey { + secret: StaticSecret, +} + +impl Zeroize for X25519PrivateKey { + fn zeroize(&mut self) { + // Assignment drops the prior `StaticSecret` (ZeroizeOnDrop), leaving a zero scalar. + self.secret = StaticSecret::from([0u8; 32]); + } +} + +impl Drop for X25519PrivateKey { + fn drop(&mut self) { + self.zeroize(); + } +} + +/// X25519 public key (32 bytes, u-coordinate). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct X25519PublicKey { + key: PublicKey, +} + +impl X25519PrivateKey { + /// Generate a random key from the OS CSPRNG. + pub fn generate() -> Self { + Self { + secret: StaticSecret::random_from_rng(OsRng), + } + } + + /// Construct from a 32-byte scalar. + pub fn from_bytes(bytes: &[u8; 32]) -> Self { + Self { + secret: StaticSecret::from(*bytes), + } + } + + /// Return the 32-byte scalar. + pub fn to_bytes(&self) -> [u8; 32] { + self.secret.to_bytes() + } + + /// Derive the corresponding public key. + pub fn public_key(&self) -> X25519PublicKey { + X25519PublicKey { + key: PublicKey::from(&self.secret), + } + } + + /// Compute the shared secret with `peer` via X25519 Diffie-Hellman. + pub fn exchange(&self, peer: &X25519PublicKey) -> [u8; 32] { + self.secret.diffie_hellman(&peer.key).to_bytes() + } +} + +impl X25519PublicKey { + /// Parse a 32-byte u-coordinate. + pub fn from_bytes(bytes: &[u8; 32]) -> Self { + Self { + key: PublicKey::from(*bytes), + } + } + + /// Return the 32-byte u-coordinate. + pub fn to_bytes(&self) -> [u8; 32] { + self.key.to_bytes() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_key_generation() { + let prv = X25519PrivateKey::generate(); + let pub_key = prv.public_key(); + assert_ne!(pub_key.to_bytes(), [0u8; 32]); + } + + #[test] + fn test_key_roundtrip() { + let prv = X25519PrivateKey::generate(); + let bytes = prv.to_bytes(); + let prv2 = X25519PrivateKey::from_bytes(&bytes); + assert_eq!(prv.public_key().to_bytes(), prv2.public_key().to_bytes()); + } + + #[test] + fn test_ecdh_agreement() { + let alice_prv = X25519PrivateKey::generate(); + let alice_pub = alice_prv.public_key(); + + let bob_prv = X25519PrivateKey::generate(); + let bob_pub = bob_prv.public_key(); + + let alice_shared = alice_prv.exchange(&bob_pub); + let bob_shared = bob_prv.exchange(&alice_pub); + + assert_eq!(alice_shared, bob_shared); + } + + #[test] + fn test_from_known_bytes() { + let prv_bytes = [42u8; 32]; + let prv = X25519PrivateKey::from_bytes(&prv_bytes); + let pub_key = prv.public_key(); + let pub_key2 = X25519PrivateKey::from_bytes(&prv_bytes).public_key(); + assert_eq!(pub_key.to_bytes(), pub_key2.to_bytes()); + } +} diff --git a/crates/rns-identity/Cargo.toml b/crates/rns-identity/Cargo.toml new file mode 100644 index 0000000..95b3d10 --- /dev/null +++ b/crates/rns-identity/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "rns-identity" +description = "Identity, Destination, and Announce system for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +rns-crypto = { workspace = true, features = ["std"] } +rns-wire = { workspace = true, features = ["std"] } +zeroize = { workspace = true } +thiserror = { workspace = true } +rmp-serde = { workspace = true } +rmpv = { workspace = true } +serde = { workspace = true } +rand = { workspace = true } +tracing = { workspace = true } +hex = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/rns-identity/src/announce.rs b/crates/rns-identity/src/announce.rs new file mode 100644 index 0000000..ee96b95 --- /dev/null +++ b/crates/rns-identity/src/announce.rs @@ -0,0 +1,441 @@ +use rns_crypto::sha::truncated_hash; +use thiserror::Error; +use tracing::trace; + +use crate::identity::Identity; +use crate::name_hash::name_hash; + +// Announce field sizes, fixed by the wire format. +const PUBKEY_SIZE: usize = 64; +const NAME_HASH_SIZE: usize = 10; +const RANDOM_HASH_SIZE: usize = 10; +const SIGNATURE_SIZE: usize = 64; +const RATCHET_SIZE: usize = 32; + +const MIN_ANNOUNCE_SIZE: usize = PUBKEY_SIZE + NAME_HASH_SIZE + RANDOM_HASH_SIZE + SIGNATURE_SIZE; + +#[derive(Debug, Error)] +pub enum AnnounceError { + #[error("announce data too short: {0} bytes (minimum {MIN_ANNOUNCE_SIZE})")] + TooShort(usize), + #[error("signature verification failed")] + SignatureInvalid, + #[error("destination hash mismatch")] + HashMismatch, + #[error("identity has no private key for signing")] + NoPrivateKey, + #[error("invalid public key in announce")] + InvalidPublicKey, + #[error("hash collision detected for destination")] + HashCollision, +} + +/// Parsed announce data. +#[derive(Debug, Clone)] +pub struct AnnounceData { + pub public_key: [u8; 64], + pub name_hash: [u8; 10], + pub random_hash: [u8; 10], + pub ratchet: Option<[u8; 32]>, + pub signature: [u8; 64], + pub app_data: Option>, +} + +impl AnnounceData { + /// Create and sign an announce for a destination. + /// + /// The `random_hash` is `random(5) || timestamp_be(5)` so receivers can + /// detect replays without a shared clock. + pub fn create( + identity: &Identity, + app_name: &str, + app_data: Option<&[u8]>, + ratchet_pub: Option<&[u8; 32]>, + ) -> Result { + let public_key = identity.get_public_key(); + let nh = name_hash(app_name); + + let random_bytes = rns_crypto::random::random_bytes(5); + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let ts_bytes = ts.to_be_bytes(); + let mut random_hash = [0u8; 10]; + random_hash[..5].copy_from_slice(&random_bytes); + // Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years. + random_hash[5..].copy_from_slice(&ts_bytes[3..8]); + + let dest_hash = crate::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + + let mut signed_data = Vec::new(); + signed_data.extend_from_slice(&dest_hash); + signed_data.extend_from_slice(&public_key); + signed_data.extend_from_slice(&nh); + signed_data.extend_from_slice(&random_hash); + if let Some(r) = ratchet_pub { + signed_data.extend_from_slice(r); + } + if let Some(ad) = app_data { + signed_data.extend_from_slice(ad); + } + + let signature = identity + .sign(&signed_data) + .ok_or(AnnounceError::NoPrivateKey)?; + + Ok(Self { + public_key, + name_hash: nh, + random_hash, + ratchet: ratchet_pub.copied(), + signature, + app_data: app_data.map(|d| d.to_vec()), + }) + } + + /// Serialise the announce into its on-wire packet payload. + /// + /// Layout: `pub_key(64) || name_hash(10) || random_hash(10) || [ratchet(32)] || signature(64) || [app_data]`. + pub fn pack(&self) -> Vec { + let size = PUBKEY_SIZE + + NAME_HASH_SIZE + + RANDOM_HASH_SIZE + + if self.ratchet.is_some() { + RATCHET_SIZE + } else { + 0 + } + + SIGNATURE_SIZE + + self.app_data.as_ref().map_or(0, |d| d.len()); + + let mut out = Vec::with_capacity(size); + out.extend_from_slice(&self.public_key); + out.extend_from_slice(&self.name_hash); + out.extend_from_slice(&self.random_hash); + if let Some(ref r) = self.ratchet { + out.extend_from_slice(r); + } + out.extend_from_slice(&self.signature); + if let Some(ref ad) = self.app_data { + out.extend_from_slice(ad); + } + out + } + + /// Parse an announce from packet payload bytes. + /// + /// `has_ratchet` must match the packet header's context flag; the ratchet + /// field is not self-delimiting. + pub fn unpack(data: &[u8], has_ratchet: bool) -> Result { + let min_size = if has_ratchet { + MIN_ANNOUNCE_SIZE + RATCHET_SIZE + } else { + MIN_ANNOUNCE_SIZE + }; + + if data.len() < min_size { + return Err(AnnounceError::TooShort(data.len())); + } + + let mut pos = 0; + + let mut public_key = [0u8; 64]; + public_key.copy_from_slice(&data[pos..pos + 64]); + pos += 64; + + let mut nh = [0u8; 10]; + nh.copy_from_slice(&data[pos..pos + 10]); + pos += 10; + + let mut random_hash = [0u8; 10]; + random_hash.copy_from_slice(&data[pos..pos + 10]); + pos += 10; + + let ratchet = if has_ratchet { + let mut r = [0u8; 32]; + r.copy_from_slice(&data[pos..pos + 32]); + pos += 32; + Some(r) + } else { + None + }; + + let mut signature = [0u8; 64]; + signature.copy_from_slice(&data[pos..pos + 64]); + pos += 64; + + let app_data = if pos < data.len() { + Some(data[pos..].to_vec()) + } else { + None + }; + + Ok(Self { + public_key, + name_hash: nh, + random_hash, + ratchet, + signature, + app_data, + }) + } + + /// Validate an announce against the destination hash from the packet header. + pub fn validate(&self, packet_dest_hash: &[u8; 16]) -> Result { + self.validate_with_known_key(packet_dest_hash, None) + } + + /// Validate and optionally enforce first-seen key binding. + /// + /// If `known_public_key` is supplied and differs from the announced key, + /// the announce is rejected as a potential hash-collision hijack. + pub fn validate_with_known_key( + &self, + packet_dest_hash: &[u8; 16], + known_public_key: Option<&[u8; 64]>, + ) -> Result { + let identity = Identity::from_public_key(&self.public_key) + .map_err(|_| AnnounceError::InvalidPublicKey)?; + + let mut signed_data = Vec::new(); + signed_data.extend_from_slice(packet_dest_hash); + signed_data.extend_from_slice(&self.public_key); + signed_data.extend_from_slice(&self.name_hash); + signed_data.extend_from_slice(&self.random_hash); + if let Some(ref r) = self.ratchet { + signed_data.extend_from_slice(r); + } + if let Some(ref ad) = self.app_data { + signed_data.extend_from_slice(ad); + } + + trace!( + signed_data_len = signed_data.len(), + signed_data_head = hex::encode(&signed_data[..std::cmp::min(32, signed_data.len())]), + signed_data_tail = hex::encode(&signed_data[signed_data.len().saturating_sub(16)..]), + identity_hash = hex::encode(identity.hash), + "announce: verifying signature" + ); + if !identity.verify(&signed_data, &self.signature) { + return Err(AnnounceError::SignatureInvalid); + } + + // Destination hash = SHA-256(name_hash || identity_hash) truncated to 16 bytes. + let expected_hash = { + let mut material = Vec::with_capacity(26); + material.extend_from_slice(&self.name_hash); + material.extend_from_slice(&identity.hash); + truncated_hash(&material) + }; + + if &expected_hash != packet_dest_hash { + trace!( + expected = hex::encode(expected_hash), + actual = hex::encode(packet_dest_hash), + name_hash = hex::encode(self.name_hash), + identity_hash = hex::encode(identity.hash), + "announce: destination hash mismatch" + ); + return Err(AnnounceError::HashMismatch); + } + + // First-seen key binding: a valid signature on a different public key + // for an already-known destination hash implies a collision attack. + if let Some(known_key) = known_public_key + && known_key != &self.public_key + { + tracing::error!( + dest = hex::encode(packet_dest_hash), + "announce has valid signature and destination hash, but public key \ + differs from already known key — possible hash collision attack, rejecting" + ); + return Err(AnnounceError::HashCollision); + } + + Ok(identity) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_create_and_validate_announce() { + let id = Identity::new(); + let app_name = "test.announce"; + + let announce = AnnounceData::create(&id, app_name, Some(b"hello"), None).unwrap(); + + let dest_hash = + crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash)); + + let validated_id = announce.validate(&dest_hash).unwrap(); + assert_eq!(validated_id.hash, id.hash); + } + + #[test] + fn test_create_and_validate_with_ratchet() { + let id = Identity::new(); + let ratchet_pub = rns_crypto::random::random_32(); + + let announce = AnnounceData::create(&id, "test.ratchet", None, Some(&ratchet_pub)).unwrap(); + assert!(announce.ratchet.is_some()); + + let dest_hash = crate::destination::Destination::hash_from_name_and_identity( + "test.ratchet", + Some(&id.hash), + ); + announce.validate(&dest_hash).unwrap(); + } + + #[test] + fn test_pack_unpack_roundtrip() { + let id = Identity::new(); + let announce = AnnounceData::create(&id, "test.pack", Some(b"data"), None).unwrap(); + let packed = announce.pack(); + let unpacked = AnnounceData::unpack(&packed, false).unwrap(); + + assert_eq!(announce.public_key, unpacked.public_key); + assert_eq!(announce.name_hash, unpacked.name_hash); + assert_eq!(announce.random_hash, unpacked.random_hash); + assert_eq!(announce.signature, unpacked.signature); + assert_eq!(announce.app_data, unpacked.app_data); + } + + #[test] + fn test_pack_unpack_with_ratchet() { + let id = Identity::new(); + let ratchet = rns_crypto::random::random_32(); + let announce = AnnounceData::create(&id, "test.pack", None, Some(&ratchet)).unwrap(); + let packed = announce.pack(); + let unpacked = AnnounceData::unpack(&packed, true).unwrap(); + + assert_eq!(announce.ratchet, unpacked.ratchet); + assert_eq!(announce.signature, unpacked.signature); + } + + #[test] + fn test_tampered_signature_fails() { + let id = Identity::new(); + let mut announce = AnnounceData::create(&id, "test.tamper", None, None).unwrap(); + announce.signature[0] ^= 0xFF; + + let dest_hash = crate::destination::Destination::hash_from_name_and_identity( + "test.tamper", + Some(&id.hash), + ); + assert!(announce.validate(&dest_hash).is_err()); + } + + #[test] + fn test_wrong_dest_hash_fails() { + let id = Identity::new(); + let announce = AnnounceData::create(&id, "test.wrong", None, None).unwrap(); + + let wrong_hash = [0xFF; 16]; + assert!(announce.validate(&wrong_hash).is_err()); + } + + #[test] + fn test_announce_too_short() { + assert!(AnnounceData::unpack(&[0u8; 10], false).is_err()); + } + + #[test] + fn test_hash_collision_defense_same_key_accepted() { + let id = Identity::new(); + let app_name = "test.collision"; + let announce = AnnounceData::create(&id, app_name, None, None).unwrap(); + let dest_hash = + crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash)); + let known_key = id.get_public_key(); + assert!( + announce + .validate_with_known_key(&dest_hash, Some(&known_key)) + .is_ok() + ); + } + + #[test] + fn test_hash_collision_defense_different_key_rejected() { + let id = Identity::new(); + let app_name = "test.collision2"; + let announce = AnnounceData::create(&id, app_name, None, None).unwrap(); + let dest_hash = + crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash)); + let other_id = Identity::new(); + let other_key = other_id.get_public_key(); + let result = announce.validate_with_known_key(&dest_hash, Some(&other_key)); + assert!(matches!(result, Err(AnnounceError::HashCollision))); + } + + #[test] + fn test_hash_collision_defense_no_known_key_accepted() { + let id = Identity::new(); + let app_name = "test.collision3"; + let announce = AnnounceData::create(&id, app_name, None, None).unwrap(); + let dest_hash = + crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash)); + assert!(announce.validate_with_known_key(&dest_hash, None).is_ok()); + } + + use proptest::prelude::*; + + type AnnounceBytes = ( + [u8; 64], // public_key + [u8; 10], // name_hash + [u8; 10], // random_hash + [u8; 64], // signature + Option<[u8; 32]>, // ratchet + Option>, // app_data + ); + + fn any_announce_bytes() -> impl Strategy { + ( + any::<[u8; 64]>(), + any::<[u8; 10]>(), + any::<[u8; 10]>(), + any::<[u8; 64]>(), + proptest::option::of(any::<[u8; 32]>()), + // Empty app_data is omitted on the wire and parses back as None, + // so generate only None or Some(non-empty) for a clean roundtrip. + proptest::option::of(proptest::collection::vec(any::(), 1..=256)), + ) + } + + proptest! { + #[test] + fn proptest_announce_pack_unpack_roundtrip( + (public_key, name_hash, random_hash, signature, ratchet, app_data) + in any_announce_bytes(), + ) { + let has_ratchet = ratchet.is_some(); + let announce = AnnounceData { + public_key, + name_hash, + random_hash, + ratchet, + signature, + app_data: app_data.clone(), + }; + + let packed = announce.pack(); + let unpacked = AnnounceData::unpack(&packed, has_ratchet).unwrap(); + + prop_assert_eq!(unpacked.public_key, public_key); + prop_assert_eq!(unpacked.name_hash, name_hash); + prop_assert_eq!(unpacked.random_hash, random_hash); + prop_assert_eq!(unpacked.ratchet, ratchet); + prop_assert_eq!(unpacked.signature, signature); + prop_assert_eq!(&unpacked.app_data, &app_data); + + // Canonical form: re-pack must yield identical bytes. + prop_assert_eq!(unpacked.pack(), packed); + } + } +} diff --git a/crates/rns-identity/src/destination.rs b/crates/rns-identity/src/destination.rs new file mode 100644 index 0000000..e18e280 --- /dev/null +++ b/crates/rns-identity/src/destination.rs @@ -0,0 +1,859 @@ +use std::collections::HashMap; + +use rns_crypto::sha::truncated_hash; +use rns_crypto::token; +use thiserror::Error; + +use crate::identity::Identity; +use crate::name_hash::name_hash; + +/// Callback invoked on incoming data packets: `fn(plaintext, raw_packet)`. +pub type PacketCallback = Box; +/// Callback invoked when a new link is established: `fn(link_id)`. +pub type LinkEstablishedCallback = Box; +/// Callback deciding whether to emit a proof for a given packet. +pub type ProofRequestedCallback = Box bool + Send + Sync>; + +pub struct RequestHandler { + pub path: String, + pub allow: AllowPolicy, + /// Identity hashes permitted when `allow == AllowList`. + pub allowed_list: Vec<[u8; 16]>, + pub auto_compress: bool, +} + +/// Default app data for announces: static bytes or a dynamic generator. +pub enum DefaultAppData { + Static(Vec), + Dynamic(Box Option> + Send + Sync>), +} + +struct PathResponseCache { + timestamp: f64, + announce_data: Vec, +} + +// Path-response dedup window (seconds). Matches upstream default. +const PR_TAG_WINDOW: f64 = 30.0; + +/// Destination type (matches wire format `DestinationType`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum DestType { + /// Asymmetric encryption via identity (ECDH + AES-256). + Single = 0x00, + /// Symmetric encryption with pre-shared key. + Group = 0x01, + /// No encryption (plaintext). + Plain = 0x02, + /// Internal per-link ephemeral encryption. + Link = 0x03, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + In, + Out, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ProofStrategy { + ProveNone = 0x21, + ProveApp = 0x22, + ProveAll = 0x23, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum AllowPolicy { + AllowNone = 0x00, + AllowAll = 0x01, + AllowList = 0x02, +} + +#[derive(Debug, Error)] +pub enum DestinationError { + #[error("SINGLE destination requires an identity")] + MissingIdentity, + #[error("outbound SINGLE destination requires an identity")] + OutboundMissingIdentity, + #[error("PLAIN destination cannot have an identity")] + PlainWithIdentity, + #[error("encryption not available for this destination type")] + EncryptionUnavailable, + #[error("decryption failed")] + DecryptionFailed, + #[error("only SINGLE destinations can be proved")] + ProveNotSingle, + #[error("identity error: {0}")] + Identity(#[from] crate::identity::IdentityError), +} + +pub struct Destination { + pub dest_type: DestType, + pub direction: Direction, + pub hash: [u8; 16], + pub name_hash: [u8; 10], + pub app_name: String, + pub proof_strategy: ProofStrategy, + /// If set, incoming data is signature-checked but not decrypted. + pub only_validate_signature: bool, + group_key: Option>, + + // Identity auto-generated for an IN destination when none was supplied; + // callers retrieve it via [`auto_identity`] or [`take_auto_identity`]. + auto_identity: Option, + + packet_callback: Option, + link_established_callback: Option, + proof_requested_callback: Option, + + // Keyed by SHA-256(path)[:16]. + request_handlers: HashMap<[u8; 16], RequestHandler>, + + pub links: Vec<[u8; 16]>, + + pub accept_link_requests: bool, + + default_app_data: Option, + + pub ratchets_enabled: bool, + /// When set, non-ratchet ciphertexts are rejected. + pub ratchets_enforced: bool, + + /// OUT: remote peer's most recent ratchet public key, used for forward-secret encryption. + pub remote_ratchet_pub: Option<[u8; 32]>, + /// IN: our current ratchet public key, advertised in announces. + pub local_ratchet_pub: Option<[u8; 32]>, + + path_responses: HashMap, PathResponseCache>, +} + +impl Destination { + /// Create a new destination. + /// + /// For SINGLE/GROUP inbound destinations, a new identity is generated + /// automatically when `identity` is `None`; retrieve it via + /// [`Destination::auto_identity`]. + /// + /// See [`Destination::compute_hash`] for the hash derivation. + pub fn new( + identity: Option<&Identity>, + direction: Direction, + dest_type: DestType, + app_name: &str, + ) -> Result { + match dest_type { + DestType::Single | DestType::Group => { + let (id_ref, auto_id, hash_name) = match identity { + Some(id) => (id.hash, None, app_name.to_string()), + None => { + if direction == Direction::In { + let new_id = Identity::new(); + let hash = new_id.hash; + let hash_name = format!("{app_name}.{}", hex::encode(hash)); + (hash, Some(new_id), hash_name) + } else { + return Err(DestinationError::OutboundMissingIdentity); + } + } + }; + + let nh = name_hash(&hash_name); + let hash = Self::compute_hash(&nh, Some(&id_ref)); + + Ok(Self { + dest_type, + direction, + hash, + name_hash: nh, + app_name: app_name.to_string(), + proof_strategy: ProofStrategy::ProveNone, + only_validate_signature: false, + group_key: None, + auto_identity: auto_id, + packet_callback: None, + link_established_callback: None, + proof_requested_callback: None, + request_handlers: HashMap::new(), + links: Vec::new(), + accept_link_requests: true, + default_app_data: None, + ratchets_enabled: false, + ratchets_enforced: false, + remote_ratchet_pub: None, + local_ratchet_pub: None, + path_responses: HashMap::new(), + }) + } + DestType::Plain => { + if identity.is_some() { + return Err(DestinationError::PlainWithIdentity); + } + let nh = name_hash(app_name); + let hash = Self::compute_hash(&nh, None); + + Ok(Self { + dest_type, + direction, + hash, + name_hash: nh, + app_name: app_name.to_string(), + proof_strategy: ProofStrategy::ProveNone, + only_validate_signature: false, + group_key: None, + auto_identity: None, + packet_callback: None, + link_established_callback: None, + proof_requested_callback: None, + request_handlers: HashMap::new(), + links: Vec::new(), + accept_link_requests: true, + default_app_data: None, + ratchets_enabled: false, + ratchets_enforced: false, + remote_ratchet_pub: None, + local_ratchet_pub: None, + path_responses: HashMap::new(), + }) + } + DestType::Link => { + // LINK destinations are constructed by the link layer itself. + let nh = name_hash(app_name); + let hash = Self::compute_hash(&nh, identity.map(|i| &i.hash)); + + Ok(Self { + dest_type, + direction, + hash, + name_hash: nh, + app_name: app_name.to_string(), + proof_strategy: ProofStrategy::ProveNone, + only_validate_signature: false, + group_key: None, + auto_identity: None, + packet_callback: None, + link_established_callback: None, + proof_requested_callback: None, + request_handlers: HashMap::new(), + links: Vec::new(), + accept_link_requests: true, + default_app_data: None, + ratchets_enabled: false, + ratchets_enforced: false, + remote_ratchet_pub: None, + local_ratchet_pub: None, + path_responses: HashMap::new(), + }) + } + } + } + + /// Compute a destination hash. + /// + /// - SINGLE/GROUP: `SHA-256(name_hash || identity_hash)[:16]` + /// - PLAIN: `SHA-256(name_hash)[:16]` + pub fn compute_hash(nh: &[u8; 10], identity_hash: Option<&[u8; 16]>) -> [u8; 16] { + match identity_hash { + Some(ih) => { + let mut material = [0u8; 26]; + material[..10].copy_from_slice(nh); + material[10..].copy_from_slice(ih); + truncated_hash(&material) + } + None => truncated_hash(nh), + } + } + + pub fn hash_from_name_and_identity( + app_name: &str, + identity_hash: Option<&[u8; 16]>, + ) -> [u8; 16] { + let nh = name_hash(app_name); + Self::compute_hash(&nh, identity_hash) + } + + pub fn set_proof_strategy(&mut self, strategy: ProofStrategy) { + self.proof_strategy = strategy; + } + + /// Set the pre-shared key used for GROUP encryption. + pub fn set_group_key(&mut self, key: Vec) { + self.group_key = Some(key); + } + + /// Identity auto-generated at construction (IN + SINGLE/GROUP without a caller-provided identity). + pub fn auto_identity(&self) -> Option<&Identity> { + self.auto_identity.as_ref() + } + + pub fn take_auto_identity(&mut self) -> Option { + self.auto_identity.take() + } + + pub fn set_only_validate_signature(&mut self, only_validate: bool) { + self.only_validate_signature = only_validate; + } + + /// Produce a proof over `packet_hash` for this (SINGLE) destination. + /// + /// `implicit_proof = true` emits the 64-byte signature alone; otherwise + /// the output is `packet_hash || signature`. + pub fn prove( + &self, + packet_hash: &[u8], + identity: &Identity, + implicit_proof: bool, + ) -> Result, DestinationError> { + if self.dest_type != DestType::Single { + return Err(DestinationError::ProveNotSingle); + } + identity + .prove(packet_hash, implicit_proof) + .map_err(DestinationError::Identity) + } + + /// Encrypt data for this destination. + /// + /// For SINGLE destinations a `remote_ratchet_pub` replaces the identity's + /// X25519 key in the ECDH exchange, giving forward secrecy. + pub fn encrypt( + &self, + plaintext: &[u8], + identity: &Identity, + remote_ratchet_pub: Option<&[u8; 32]>, + ) -> Result, DestinationError> { + match self.dest_type { + DestType::Plain => Ok(plaintext.to_vec()), + DestType::Single => identity + .encrypt(plaintext, remote_ratchet_pub) + .map_err(DestinationError::Identity), + DestType::Group => { + let key = self + .group_key + .as_ref() + .ok_or(DestinationError::EncryptionUnavailable)?; + token::encrypt(plaintext, key).map_err(|_| DestinationError::DecryptionFailed) + } + DestType::Link => Err(DestinationError::EncryptionUnavailable), + } + } + + pub fn decrypt( + &self, + ciphertext: &[u8], + identity: &Identity, + ) -> Result, DestinationError> { + self.decrypt_with_ratchets(ciphertext, identity, None) + } + + /// Decrypt data, trying each ratchet private key before the identity key. + pub fn decrypt_with_ratchets( + &self, + ciphertext: &[u8], + identity: &Identity, + ratchet_keys: Option<&[[u8; 32]]>, + ) -> Result, DestinationError> { + match self.dest_type { + DestType::Plain => Ok(ciphertext.to_vec()), + DestType::Single => { + let ratchet_refs: Option> = if self.ratchets_enabled { + ratchet_keys.map(|keys| keys.iter().collect()) + } else { + None + }; + let enforce = self.ratchets_enforced; + identity + .decrypt(ciphertext, ratchet_refs.as_deref(), enforce) + .map_err(DestinationError::Identity) + } + DestType::Group => { + let key = self + .group_key + .as_ref() + .ok_or(DestinationError::EncryptionUnavailable)?; + token::decrypt(ciphertext, key).map_err(|_| DestinationError::DecryptionFailed) + } + DestType::Link => Err(DestinationError::EncryptionUnavailable), + } + } + + /// Record the remote peer's ratchet public key, learnt from an announce. + pub fn set_remote_ratchet(&mut self, pub_key: [u8; 32]) { + self.remote_ratchet_pub = Some(pub_key); + } + + /// Set our outbound ratchet public key from the ratchet ring. + pub fn set_local_ratchet(&mut self, pub_key: [u8; 32]) { + self.local_ratchet_pub = Some(pub_key); + } + + /// Return the local ratchet public key if ratchets are enabled here. + pub fn get_ratchet_for_announce(&self) -> Option<[u8; 32]> { + if self.ratchets_enabled { + self.local_ratchet_pub + } else { + None + } + } + + pub fn set_packet_callback(&mut self, callback: PacketCallback) { + self.packet_callback = Some(callback); + } + + pub fn set_link_established_callback(&mut self, callback: LinkEstablishedCallback) { + self.link_established_callback = Some(callback); + } + + /// Callback invoked under `ProveApp` strategy; returning `true` emits a proof. + pub fn set_proof_requested_callback(&mut self, callback: ProofRequestedCallback) { + self.proof_requested_callback = Some(callback); + } + + pub fn on_link_established(&self, link_id: [u8; 16]) { + if let Some(ref cb) = self.link_established_callback { + cb(link_id); + } + } + + /// Register a request handler. Returns `false` if `path` is empty. + pub fn register_request_handler( + &mut self, + path: &str, + allow: AllowPolicy, + allowed_list: Option>, + auto_compress: bool, + ) -> bool { + if path.is_empty() { + return false; + } + + let path_hash = truncated_hash(path.as_bytes()); + + self.request_handlers.insert( + path_hash, + RequestHandler { + path: path.to_string(), + allow, + allowed_list: allowed_list.unwrap_or_default(), + auto_compress, + }, + ); + + true + } + + pub fn deregister_request_handler(&mut self, path: &str) -> bool { + let path_hash = truncated_hash(path.as_bytes()); + self.request_handlers.remove(&path_hash).is_some() + } + + pub fn get_request_handler(&self, path_hash: &[u8; 16]) -> Option<&RequestHandler> { + self.request_handlers.get(path_hash) + } + + pub fn check_request_allowed( + &self, + path_hash: &[u8; 16], + remote_identity_hash: Option<&[u8; 16]>, + ) -> bool { + match self.request_handlers.get(path_hash) { + None => false, + Some(handler) => match handler.allow { + AllowPolicy::AllowNone => false, + AllowPolicy::AllowAll => true, + AllowPolicy::AllowList => { + if let Some(id_hash) = remote_identity_hash { + handler.allowed_list.iter().any(|h| h == id_hash) + } else { + false + } + } + }, + } + } + + /// Decrypt and dispatch an incoming packet. + /// + /// LINKREQUEST (`0x02`) bypasses decryption and is handled by + /// [`Destination::incoming_link_request`]; DATA (`0x00`) packets + /// additionally fire the packet callback. + pub fn receive( + &self, + packet_type: u8, + data: &[u8], + identity: &Identity, + ) -> Result>, DestinationError> { + if packet_type == 0x02 { + return Ok(Some(data.to_vec())); + } + + let plaintext = self.decrypt(data, identity)?; + + if packet_type == 0x00 + && let Some(ref cb) = self.packet_callback + { + cb(&plaintext, data); + } + + Ok(Some(plaintext)) + } + + pub fn should_prove(&self, packet_data: &[u8]) -> bool { + match self.proof_strategy { + ProofStrategy::ProveNone => false, + ProofStrategy::ProveAll => true, + ProofStrategy::ProveApp => { + if let Some(ref cb) = self.proof_requested_callback { + cb(packet_data) + } else { + false + } + } + } + } + + pub fn incoming_link_request(&mut self, link_id: [u8; 16]) -> bool { + if !self.accept_link_requests { + return false; + } + self.links.push(link_id); + true + } + + pub fn set_accepts_links(&mut self, accept: bool) { + self.accept_link_requests = accept; + } + + /// Enable ratchet forward secrecy. If `enforce`, non-ratchet inbound ciphertext is rejected. + pub fn enable_ratchets(&mut self, enforce: bool) { + self.ratchets_enabled = true; + self.ratchets_enforced = enforce; + } + + pub fn disable_ratchets(&mut self) { + self.ratchets_enabled = false; + self.ratchets_enforced = false; + } + + pub fn ratchets_active(&self) -> bool { + self.ratchets_enabled + } + + pub fn set_default_app_data(&mut self, app_data: DefaultAppData) { + self.default_app_data = Some(app_data); + } + + pub fn clear_default_app_data(&mut self) { + self.default_app_data = None; + } + + /// Return the current default app data, evaluating a dynamic generator if present. + pub fn resolve_app_data(&self) -> Option> { + match &self.default_app_data { + None => None, + Some(DefaultAppData::Static(data)) => Some(data.clone()), + Some(DefaultAppData::Dynamic(generator)) => generator(), + } + } + + /// Build signed announce data for this destination and return `(announce_bytes, has_ratchet)`. + /// + /// Wire layout: + /// - `announce_data = public_key(64) || name_hash(10) || random_hash(10) || [ratchet(32)] || signature(64) || [app_data]` + /// - `signed_data = dest_hash(16) || public_key(64) || name_hash(10) || random_hash(10) || [ratchet(32)] || [app_data]` + pub fn create_announce( + &mut self, + identity: &Identity, + app_data: Option<&[u8]>, + ratchet: Option<&[u8; 32]>, + tag: Option<&[u8]>, + now: f64, + ) -> Result<(Vec, bool), DestinationError> { + if self.dest_type != DestType::Single { + return Err(DestinationError::EncryptionUnavailable); + } + if self.direction != Direction::In { + return Err(DestinationError::EncryptionUnavailable); + } + + self.path_responses + .retain(|_, v| now <= v.timestamp + PR_TAG_WINDOW); + + if let Some(tag_bytes) = tag + && let Some(cached) = self.path_responses.get(tag_bytes) + { + return Ok((cached.announce_data.clone(), ratchet.is_some())); + } + + let effective_app_data = app_data + .map(|d| d.to_vec()) + .or_else(|| self.resolve_app_data()); + + let public_key = identity.get_public_key(); + + let random_bytes: [u8; 5] = rns_crypto::random::random_bytes(5).try_into().unwrap(); + let ts_int = now as u64; + // Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years. + let ts_bytes = &ts_int.to_be_bytes()[3..8]; + let mut random_hash = [0u8; 10]; + random_hash[..5].copy_from_slice(&random_bytes); + random_hash[5..].copy_from_slice(ts_bytes); + + let has_ratchet = ratchet.is_some(); + + let mut signed_data = Vec::with_capacity(16 + 64 + 10 + 10 + 32 + 256); + signed_data.extend_from_slice(&self.hash); + signed_data.extend_from_slice(&public_key); + signed_data.extend_from_slice(&self.name_hash); + signed_data.extend_from_slice(&random_hash); + if let Some(r) = ratchet { + signed_data.extend_from_slice(r); + } + if let Some(ref ad) = effective_app_data { + signed_data.extend_from_slice(ad); + } + + let signature = identity + .sign(&signed_data) + .ok_or(DestinationError::EncryptionUnavailable)?; + + // `dest_hash` lives in the packet header, not the announce body. + let mut announce_data = Vec::with_capacity(64 + 10 + 10 + 32 + 64 + 256); + announce_data.extend_from_slice(&public_key); + announce_data.extend_from_slice(&self.name_hash); + announce_data.extend_from_slice(&random_hash); + if let Some(r) = ratchet { + announce_data.extend_from_slice(r); + } + announce_data.extend_from_slice(&signature); + if let Some(ref ad) = effective_app_data { + announce_data.extend_from_slice(ad); + } + + if let Some(tag_bytes) = tag { + self.path_responses.insert( + tag_bytes.to_vec(), + PathResponseCache { + timestamp: now, + announce_data: announce_data.clone(), + }, + ); + } + + Ok((announce_data, has_ratchet)) + } + + pub fn announce_packet( + &mut self, + identity: &Identity, + app_data: Option<&[u8]>, + ratchet: Option<&[u8; 32]>, + path_response: bool, + tag: Option<&[u8]>, + now: f64, + ) -> Result, DestinationError> { + let (announce_data, has_ratchet) = + self.create_announce(identity, app_data, ratchet, tag, now)?; + + let context = if path_response { + rns_wire::context::PacketContext::PathResponse + } else { + rns_wire::context::PacketContext::None + }; + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: has_ratchet, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: self.hash, + context, + }; + + let mut raw = header.pack(); + raw.extend_from_slice(&announce_data); + Ok(raw) + } + + pub fn remove_link(&mut self, link_id: &[u8; 16]) { + self.links.retain(|id| id != link_id); + } + + pub fn link_count(&self) -> usize { + self.links.len() + } + + /// Hex-encoded destination hash for logging. + pub fn hex_hash(&self) -> String { + hex::encode(self.hash) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_single_destination() { + let id = Identity::new(); + let dest = + Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap(); + assert_eq!(dest.dest_type, DestType::Single); + assert_ne!(dest.hash, [0u8; 16]); + } + + #[test] + fn test_plain_destination() { + let dest = Destination::new(None, Direction::In, DestType::Plain, "test.app").unwrap(); + assert_eq!(dest.dest_type, DestType::Plain); + } + + #[test] + fn test_plain_with_identity_fails() { + let id = Identity::new(); + assert!(Destination::new(Some(&id), Direction::In, DestType::Plain, "test.app").is_err()); + } + + #[test] + fn test_single_in_without_identity_auto_creates() { + let dest = Destination::new(None, Direction::In, DestType::Single, "test.app").unwrap(); + assert!(dest.auto_identity().is_some()); + assert!(dest.auto_identity().unwrap().has_private_key()); + assert_ne!(dest.hash, [0u8; 16]); + + let auto_hash = dest.auto_identity().unwrap().hash; + let python_hash_name = format!("test.app.{}", hex::encode(auto_hash)); + let expected_name_hash = name_hash(&python_hash_name); + assert_eq!(dest.name_hash, expected_name_hash); + assert_eq!( + dest.hash, + Destination::compute_hash(&expected_name_hash, Some(&auto_hash)) + ); + assert_ne!( + dest.name_hash, + name_hash("test.app"), + "Python includes the generated identity hash in the name aspects before hashing" + ); + } + + #[test] + fn test_single_out_without_identity_fails() { + assert!(Destination::new(None, Direction::Out, DestType::Single, "test.app").is_err()); + } + + #[test] + fn test_dest_hash_deterministic() { + let id = Identity::new(); + let dest1 = + Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap(); + let dest2 = + Destination::new(Some(&id), Direction::Out, DestType::Single, "test.app").unwrap(); + assert_eq!(dest1.hash, dest2.hash); + } + + #[test] + fn test_dest_hash_computation() { + let id = Identity::new(); + let nh = name_hash("test.app"); + let expected = Destination::compute_hash(&nh, Some(&id.hash)); + let dest = + Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap(); + assert_eq!(dest.hash, expected); + } + + #[test] + fn test_plain_dest_hash() { + let nh = name_hash("test.plain"); + let expected = rns_crypto::sha::sha256(&nh); + let dest = Destination::new(None, Direction::In, DestType::Plain, "test.plain").unwrap(); + assert_eq!(&dest.hash[..], &expected[..16]); + } + + #[test] + fn test_different_apps_different_hashes() { + let id = Identity::new(); + let d1 = Destination::new(Some(&id), Direction::In, DestType::Single, "app.one").unwrap(); + let d2 = Destination::new(Some(&id), Direction::In, DestType::Single, "app.two").unwrap(); + assert_ne!(d1.hash, d2.hash); + } + + #[test] + fn test_hash_from_name_and_identity() { + let id = Identity::new(); + let dest = + Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap(); + let computed = Destination::hash_from_name_and_identity("test.app", Some(&id.hash)); + assert_eq!(dest.hash, computed); + } + + #[test] + fn test_only_validate_signature_flag() { + let id = Identity::new(); + let mut dest = + Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap(); + assert!(!dest.only_validate_signature); + + dest.set_only_validate_signature(true); + assert!(dest.only_validate_signature); + } + + #[test] + fn test_prove() { + let id = Identity::new(); + let dest = + Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap(); + let packet_hash = rns_crypto::sha::sha256(b"test packet"); + + let proof = dest.prove(&packet_hash, &id, true).unwrap(); + assert_eq!(proof.len(), 64); + + let proof = dest.prove(&packet_hash, &id, false).unwrap(); + assert_eq!(proof.len(), 32 + 64); + } + + #[test] + fn test_prove_plain_fails() { + let dest = Destination::new(None, Direction::In, DestType::Plain, "test.app").unwrap(); + let id = Identity::new(); + assert!(dest.prove(b"test", &id, true).is_err()); + } + + #[test] + fn test_encrypt_with_ratchet() { + let id = Identity::new(); + let dest = + Destination::new(Some(&id), Direction::Out, DestType::Single, "test.app").unwrap(); + + let ratchet_prv = rns_crypto::x25519::X25519PrivateKey::generate(); + let ratchet_pub = ratchet_prv.public_key().to_bytes(); + + let plaintext = b"ratcheted message"; + let ct = dest.encrypt(plaintext, &id, Some(&ratchet_pub)).unwrap(); + + assert!(id.decrypt(&ct, None, false).is_err()); + + let ratchet_prv_bytes = ratchet_prv.to_bytes(); + let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes]; + let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap(); + assert_eq!(&pt[..], plaintext); + } + + #[test] + fn test_take_auto_identity() { + let mut dest = Destination::new(None, Direction::In, DestType::Single, "test.app").unwrap(); + assert!(dest.auto_identity().is_some()); + + let taken = dest.take_auto_identity(); + assert!(taken.is_some()); + assert!(taken.unwrap().has_private_key()); + assert!(dest.auto_identity().is_none()); + } +} diff --git a/crates/rns-identity/src/identity.rs b/crates/rns-identity/src/identity.rs new file mode 100644 index 0000000..9403af4 --- /dev/null +++ b/crates/rns-identity/src/identity.rs @@ -0,0 +1,461 @@ +use rns_crypto::ed25519::{Ed25519Error, Ed25519PrivateKey, Ed25519PublicKey}; +use rns_crypto::hkdf::derive_key_64; +use rns_crypto::sha::truncated_hash; +use rns_crypto::token; +use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use zeroize::{Zeroize, Zeroizing}; + +use crate::persistence; +use std::path::Path; + +/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key. +pub const DERIVED_KEY_LENGTH: usize = 64; + +/// Per-message overhead of `Identity::encrypt` before PKCS7 padding: +/// ephemeral X25519 public (32) + Token framing (48). +pub const IDENTITY_OVERHEAD: usize = 32 + rns_crypto::TOKEN_OVERHEAD; + +#[derive(Debug, Error)] +pub enum IdentityError { + #[error("invalid private key length: expected 64, got {0}")] + InvalidPrivateKeyLength(usize), + #[error("invalid public key length: expected 64, got {0}")] + InvalidPublicKeyLength(usize), + #[error("signature verification failed")] + VerificationFailed, + #[error("decryption failed")] + DecryptionFailed, + #[error("ed25519 error: {0}")] + Ed25519(#[from] Ed25519Error), + #[error("io error: {0}")] + Io(#[from] std::io::Error), +} + +/// A Reticulum identity: X25519 keypair for encryption + Ed25519 keypair for signing. +/// +/// Wire representation: +/// - Private (64 B): `X25519_prv(32) || Ed25519_seed(32)` +/// - Public (64 B): `X25519_pub(32) || Ed25519_pub(32)` +/// - Hash (16 B): `SHA-256(public_64)[:16]` +pub struct Identity { + prv: Option, + sig_prv: Option, + pub_key: X25519PublicKey, + sig_pub: Ed25519PublicKey, + pub hash: [u8; 16], +} + +impl Default for Identity { + fn default() -> Self { + Self::new() + } +} + +impl Identity { + pub fn new() -> Self { + let prv = X25519PrivateKey::generate(); + let sig_prv = Ed25519PrivateKey::generate(); + let pub_key = prv.public_key(); + let sig_pub = sig_prv.public_key(); + let hash = Self::compute_hash(&pub_key, &sig_pub); + + Self { + prv: Some(prv), + sig_prv: Some(sig_prv), + pub_key, + sig_pub, + hash, + } + } + + pub fn from_private_key(key: &[u8]) -> Result { + if key.len() != 64 { + return Err(IdentityError::InvalidPrivateKeyLength(key.len())); + } + let mut x_bytes = Zeroizing::new([0u8; 32]); + x_bytes.copy_from_slice(&key[..32]); + let mut ed_bytes = Zeroizing::new([0u8; 32]); + ed_bytes.copy_from_slice(&key[32..]); + + let prv = X25519PrivateKey::from_bytes(&x_bytes); + let sig_prv = Ed25519PrivateKey::from_bytes(&ed_bytes); + let pub_key = prv.public_key(); + let sig_pub = sig_prv.public_key(); + let hash = Self::compute_hash(&pub_key, &sig_pub); + + Ok(Self { + prv: Some(prv), + sig_prv: Some(sig_prv), + pub_key, + sig_pub, + hash, + }) + } + + /// Construct a verify/encrypt-only identity from its 64-byte public key. + pub fn from_public_key(key: &[u8]) -> Result { + if key.len() != 64 { + return Err(IdentityError::InvalidPublicKeyLength(key.len())); + } + let mut x_bytes = [0u8; 32]; + x_bytes.copy_from_slice(&key[..32]); + let mut ed_bytes = [0u8; 32]; + ed_bytes.copy_from_slice(&key[32..]); + + let pub_key = X25519PublicKey::from_bytes(&x_bytes); + let sig_pub = Ed25519PublicKey::from_bytes(&ed_bytes)?; + let hash = Self::compute_hash(&pub_key, &sig_pub); + + Ok(Self { + prv: None, + sig_prv: None, + pub_key, + sig_pub, + hash, + }) + } + + /// Load an identity from file, accepting either the current msgpack envelope + /// or a legacy raw 64-byte private key. + pub fn from_file(path: &Path) -> Result { + let data = std::fs::read(path)?; + + if let Ok(persisted) = rmp_serde::from_slice::(&data) { + return Self::from_private_key(&persisted.private_key); + } + + Self::from_private_key(&data) + } + + /// Persist the identity as the raw 64-byte private key used by the Python + /// reference implementation, so identity files are interchangeable. + pub fn to_file(&self, path: &Path) -> Result<(), IdentityError> { + let key = self + .get_private_key() + .ok_or(IdentityError::DecryptionFailed)?; + persistence::atomic_write(path, &*key)?; + Ok(()) + } + + /// Return the 64-byte private key (`X25519_prv || Ed25519_seed`), zeroised on drop. + pub fn get_private_key(&self) -> Option> { + let prv = self.prv.as_ref()?; + let sig_prv = self.sig_prv.as_ref()?; + let mut key = Zeroizing::new([0u8; 64]); + key[..32].copy_from_slice(&prv.to_bytes()); + key[32..].copy_from_slice(&sig_prv.to_bytes()); + Some(key) + } + + /// Return the 64-byte public key (`X25519_pub || Ed25519_pub`). + pub fn get_public_key(&self) -> [u8; 64] { + let mut key = [0u8; 64]; + key[..32].copy_from_slice(&self.pub_key.to_bytes()); + key[32..].copy_from_slice(&self.sig_pub.to_bytes()); + key + } + + pub fn has_private_key(&self) -> bool { + self.prv.is_some() && self.sig_prv.is_some() + } + + pub fn get_signing_key(&self) -> Option { + self.sig_prv + .as_ref() + .map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes())) + } + + /// Sign `message` with the Ed25519 key; `None` if this is a public-only identity. + pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> { + self.sig_prv.as_ref().map(|key| key.sign(message)) + } + + pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool { + self.sig_pub.verify(message, signature).is_ok() + } + + /// Encrypt `plaintext` for this identity using ECIES. + /// + /// Output layout: `ephemeral_X25519_pub(32) || IV(16) || AES-256-CBC(PKCS7(pt)) || HMAC(32)`. + /// + /// Passing a `ratchet` public key substitutes it for the identity's X25519 + /// public key in the ECDH, giving forward secrecy against later key + /// compromise. + pub fn encrypt( + &self, + plaintext: &[u8], + ratchet: Option<&[u8; 32]>, + ) -> Result, IdentityError> { + let ephemeral = X25519PrivateKey::generate(); + let ephemeral_pub = ephemeral.public_key(); + + let target = match ratchet { + Some(r) => X25519PublicKey::from_bytes(r), + None => self.pub_key.clone(), + }; + + let mut shared = ephemeral.exchange(&target); + let derived = + derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed); + shared.zeroize(); + let derived = derived?; + let ciphertext = + token::encrypt(plaintext, &derived).map_err(|_| IdentityError::DecryptionFailed)?; + + let mut result = Vec::with_capacity(32 + ciphertext.len()); + result.extend_from_slice(&ephemeral_pub.to_bytes()); + result.extend_from_slice(&ciphertext); + Ok(result) + } + + /// Decrypt ciphertext addressed to this identity, trying each ratchet key + /// before falling back to the identity key (unless `enforce_ratchets`). + pub fn decrypt( + &self, + ciphertext: &[u8], + ratchets: Option<&[&[u8; 32]]>, + enforce_ratchets: bool, + ) -> Result, IdentityError> { + if ciphertext.len() < 32 { + return Err(IdentityError::DecryptionFailed); + } + + let mut peer_pub_bytes = [0u8; 32]; + peer_pub_bytes.copy_from_slice(&ciphertext[..32]); + let peer_pub = X25519PublicKey::from_bytes(&peer_pub_bytes); + let ct = &ciphertext[32..]; + + if let Some(ratchets) = ratchets { + for ratchet in ratchets { + let ratchet_prv = X25519PrivateKey::from_bytes(ratchet); + let mut shared = ratchet_prv.exchange(&peer_pub); + let derived_result = derive_key_64(&shared, &self.hash); + shared.zeroize(); + if let Ok(derived) = derived_result + && let Ok(plaintext) = token::decrypt(ct, &derived) + { + return Ok(plaintext); + } + } + } + + if enforce_ratchets { + return Err(IdentityError::DecryptionFailed); + } + + let prv = self.prv.as_ref().ok_or(IdentityError::DecryptionFailed)?; + let mut shared = prv.exchange(&peer_pub); + let derived_result = + derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed); + shared.zeroize(); + let derived = derived_result?; + let plaintext = + token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?; + Ok(plaintext) + } + + /// Sign `packet_hash` and return proof bytes. + /// + /// `implicit_proof = true` returns the 64-byte signature alone; `false` + /// returns `packet_hash(32) || signature(64)` (96 bytes). + pub fn prove( + &self, + packet_hash: &[u8], + implicit_proof: bool, + ) -> Result, IdentityError> { + let signature = self + .sign(packet_hash) + .ok_or(IdentityError::DecryptionFailed)?; + + if implicit_proof { + Ok(signature.to_vec()) + } else { + let mut proof_data = Vec::with_capacity(packet_hash.len() + 64); + proof_data.extend_from_slice(packet_hash); + proof_data.extend_from_slice(&signature); + Ok(proof_data) + } + } + + fn compute_hash(pub_key: &X25519PublicKey, sig_pub: &Ed25519PublicKey) -> [u8; 16] { + let mut combined = [0u8; 64]; + combined[..32].copy_from_slice(&pub_key.to_bytes()); + combined[32..].copy_from_slice(&sig_pub.to_bytes()); + truncated_hash(&combined) + } +} + +// Msgpack envelope wrapping the raw 64-byte private key on disk. +#[derive(Serialize, Deserialize)] +struct IdentityPersisted { + private_key: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_generate_identity() { + let id = Identity::new(); + assert!(id.has_private_key()); + assert_ne!(id.hash, [0u8; 16]); + } + + #[test] + fn test_private_key_roundtrip() { + let id1 = Identity::new(); + let prv = id1.get_private_key().unwrap(); + let id2 = Identity::from_private_key(&*prv).unwrap(); + assert_eq!(id1.hash, id2.hash); + assert_eq!(id1.get_public_key(), id2.get_public_key()); + } + + #[test] + fn test_public_key_roundtrip() { + let id1 = Identity::new(); + let pub_key = id1.get_public_key(); + let id2 = Identity::from_public_key(&pub_key).unwrap(); + assert_eq!(id1.hash, id2.hash); + assert!(!id2.has_private_key()); + } + + #[test] + fn test_sign_verify() { + let id = Identity::new(); + let msg = b"hello reticulum"; + let sig = id.sign(msg).unwrap(); + assert!(id.verify(msg, &sig)); + } + + #[test] + fn test_sign_verify_wrong_message() { + let id = Identity::new(); + let sig = id.sign(b"correct").unwrap(); + assert!(!id.verify(b"wrong", &sig)); + } + + #[test] + fn test_encrypt_decrypt() { + let id = Identity::new(); + let plaintext = b"secret message"; + let ct = id.encrypt(plaintext, None).unwrap(); + let pt = id.decrypt(&ct, None, false).unwrap(); + assert_eq!(&pt, plaintext); + } + + #[test] + fn test_encrypt_decrypt_with_ratchet() { + let id = Identity::new(); + let ratchet_prv = rns_crypto::x25519::X25519PrivateKey::generate(); + let ratchet_pub = ratchet_prv.public_key().to_bytes(); + let ratchet_prv_bytes = ratchet_prv.to_bytes(); + + let plaintext = b"ratcheted message"; + let ct = id.encrypt(plaintext, Some(&ratchet_pub)).unwrap(); + + assert!(id.decrypt(&ct, None, false).is_err()); + + let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes]; + let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap(); + assert_eq!(&pt, plaintext); + } + + #[test] + fn test_cross_identity_encrypt_decrypt() { + let sender = Identity::new(); + let receiver = Identity::new(); + + let plaintext = b"from sender to receiver"; + let ct = receiver.encrypt(plaintext, None).unwrap(); + let pt = receiver.decrypt(&ct, None, false).unwrap(); + assert_eq!(&pt, plaintext); + + assert!(sender.decrypt(&ct, None, false).is_err()); + } + + #[test] + fn test_public_key_only_cannot_sign() { + let id = Identity::new(); + let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap(); + assert!(pub_id.sign(b"test").is_none()); + } + + #[test] + fn test_hash_is_truncated_sha256() { + let id = Identity::new(); + let full = rns_crypto::sha::sha256(&id.get_public_key()); + assert_eq!(&id.hash[..], &full[..16]); + } + + #[test] + fn test_file_roundtrip() { + let dir = std::env::temp_dir().join("reticulum_identity_test_msgpack"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("test_identity"); + + let id1 = Identity::new(); + id1.to_file(&path).unwrap(); + let id2 = Identity::from_file(&path).unwrap(); + + assert_eq!(id1.hash, id2.hash); + assert_eq!(id1.get_public_key(), id2.get_public_key()); + assert_eq!(id1.get_private_key(), id2.get_private_key()); + + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir(&dir); + } + + #[test] + fn test_file_backward_compat_raw() { + let dir = std::env::temp_dir().join("reticulum_identity_test_compat"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("raw_identity"); + + let id1 = Identity::new(); + let key = id1.get_private_key().unwrap(); + // Legacy format: raw 64-byte private key, no msgpack envelope. + std::fs::write(&path, &key).unwrap(); + + let id2 = Identity::from_file(&path).unwrap(); + assert_eq!(id1.hash, id2.hash); + assert_eq!(id1.get_public_key(), id2.get_public_key()); + + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir(&dir); + } + + #[test] + fn test_prove_implicit() { + let id = Identity::new(); + let packet_hash = rns_crypto::sha::sha256(b"test packet"); + + let proof = id.prove(&packet_hash, true).unwrap(); + assert_eq!(proof.len(), 64); + let mut sig = [0u8; 64]; + sig.copy_from_slice(&proof); + assert!(id.verify(&packet_hash, &sig)); + } + + #[test] + fn test_prove_explicit() { + let id = Identity::new(); + let packet_hash = rns_crypto::sha::sha256(b"test packet"); + + let proof = id.prove(&packet_hash, false).unwrap(); + assert_eq!(proof.len(), 32 + 64); + assert_eq!(&proof[..32], &packet_hash); + let mut sig = [0u8; 64]; + sig.copy_from_slice(&proof[32..]); + assert!(id.verify(&packet_hash, &sig)); + } + + #[test] + fn test_prove_no_private_key_fails() { + let id = Identity::new(); + let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap(); + assert!(pub_id.prove(b"test", true).is_err()); + } +} diff --git a/crates/rns-identity/src/ifac.rs b/crates/rns-identity/src/ifac.rs new file mode 100644 index 0000000..3e33862 --- /dev/null +++ b/crates/rns-identity/src/ifac.rs @@ -0,0 +1,139 @@ +use rns_crypto::hkdf::hkdf_sha256; +use rns_crypto::sha::sha256; +use thiserror::Error; + +// Fixed IFAC HKDF salt. Shared with the Python reference; changing it breaks interop. +const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8"; + +#[derive(Debug, Error)] +pub enum IfacError { + #[error("HKDF derivation failed: {0}")] + HkdfFailed(#[from] rns_crypto::hkdf::HkdfError), + #[error("invalid IFAC salt hex")] + InvalidSalt, +} + +/// Derive the 64-byte IFAC (Interface Access Control) key. +/// +/// `ifac_origin` concatenates `SHA-256(network_name)` and `SHA-256(passphrase)` +/// for whichever fields are `Some(_)` (a `None` field is omitted, so `None` +/// and `Some("")` differ), then HKDF-SHA256 expands it under the fixed salt. +/// First 32 bytes → X25519 private; second 32 → Ed25519 seed. +pub fn derive_ifac_key( + network_name: Option<&str>, + passphrase: Option<&str>, +) -> Result<[u8; 64], IfacError> { + let mut ifac_origin = Vec::new(); + + if let Some(name) = network_name { + ifac_origin.extend_from_slice(&sha256(name.as_bytes())); + } + if let Some(key) = passphrase { + ifac_origin.extend_from_slice(&sha256(key.as_bytes())); + } + + let ifac_origin_hash = sha256(&ifac_origin); + + let salt = hex_decode(IFAC_SALT).ok_or(IfacError::InvalidSalt)?; + + let derived = hkdf_sha256(64, &ifac_origin_hash, Some(&salt), None)?; + let mut key = [0u8; 64]; + key.copy_from_slice(&derived); + Ok(key) +} + +/// Build the IFAC identity plus a self-signature over `SHA-256(ifac_key)`. +/// +/// Returns `(identity, ifac_key, signature)`. +pub fn derive_ifac_identity( + network_name: Option<&str>, + passphrase: Option<&str>, +) -> Result<(crate::identity::Identity, [u8; 64], [u8; 64]), IfacError> { + let ifac_key = derive_ifac_key(network_name, passphrase)?; + + let identity = crate::identity::Identity::from_private_key(&ifac_key) + .map_err(|_| IfacError::InvalidSalt)?; + + let key_hash = sha256(&ifac_key); + let signature = identity.sign(&key_hash).ok_or(IfacError::InvalidSalt)?; + + Ok((identity, ifac_key, signature)) +} + +/// Split IFAC key into `(signing_key, masking_key)`, each 32 bytes. +pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) { + (&key[..32], &key[32..]) +} + +fn hex_decode(s: &str) -> Option> { + if !s.len().is_multiple_of(2) { + return None; + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ifac_derivation_deterministic() { + let key1 = derive_ifac_key(Some("testnet"), Some("password")).unwrap(); + let key2 = derive_ifac_key(Some("testnet"), Some("password")).unwrap(); + assert_eq!(key1, key2); + } + + #[test] + fn test_ifac_different_inputs_different_keys() { + let key1 = derive_ifac_key(Some("net1"), Some("pass1")).unwrap(); + let key2 = derive_ifac_key(Some("net2"), Some("pass2")).unwrap(); + assert_ne!(key1, key2); + } + + #[test] + fn test_ifac_none_inputs() { + let key = derive_ifac_key(None, None).unwrap(); + assert_eq!(key.len(), 64); + } + + #[test] + fn test_ifac_key_split() { + let key = derive_ifac_key(Some("test"), Some("test")).unwrap(); + let (signing, masking) = split_ifac_key(&key); + assert_eq!(signing.len(), 32); + assert_eq!(masking.len(), 32); + } + + #[test] + fn test_ifac_partial_inputs() { + let key_name_only = derive_ifac_key(Some("testnet"), None).unwrap(); + let key_both = derive_ifac_key(Some("testnet"), Some("password")).unwrap(); + assert_ne!(key_name_only, key_both); + + let key_pass_only = derive_ifac_key(None, Some("password")).unwrap(); + assert_ne!(key_pass_only, key_both); + } + + #[test] + fn test_ifac_none_vs_empty() { + // `None` omits the field from the origin; `Some("")` includes SHA-256(""). + let key_none = derive_ifac_key(None, None).unwrap(); + let key_empty = derive_ifac_key(Some(""), Some("")).unwrap(); + assert_ne!(key_none, key_empty); + } + + #[test] + fn test_derive_ifac_identity() { + let (identity, ifac_key, signature) = + derive_ifac_identity(Some("testnet"), Some("password")).unwrap(); + + assert!(identity.has_private_key()); + assert_eq!(ifac_key.len(), 64); + + let key_hash = sha256(&ifac_key); + assert!(identity.verify(&key_hash, &signature)); + } +} diff --git a/crates/rns-identity/src/known_destinations.rs b/crates/rns-identity/src/known_destinations.rs new file mode 100644 index 0000000..0d0b712 --- /dev/null +++ b/crates/rns-identity/src/known_destinations.rs @@ -0,0 +1,664 @@ +use std::collections::HashMap; +use std::io::Cursor; +use std::path::Path; + +use crate::persistence; +use rmpv::Value; + +/// Record of a destination learnt from a validated announce. +#[derive(Debug, Clone)] +pub struct KnownDestination { + /// Learn time as a Unix timestamp (seconds). + pub timestamp: f64, + /// Packet hash of the announce that introduced the destination. + pub packet_hash: [u8; 32], + /// Concatenated `X25519_pub || Ed25519_pub`. + pub public_key: [u8; 64], + pub app_data: Option>, + /// Pinned via `retain()` — `cleanup()` skips this entry regardless of age. + pub retained: bool, +} + +/// Table of known destinations, keyed by 16-byte destination hash. +pub struct KnownDestinations { + entries: HashMap<[u8; 16], KnownDestination>, +} + +impl KnownDestinations { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + } + } + + /// Insert or refresh the entry for `dest_hash`. The `retained` flag is + /// preserved on update so a fresh announce never un-pins an entry. + pub fn remember( + &mut self, + dest_hash: [u8; 16], + timestamp: f64, + packet_hash: [u8; 32], + public_key: [u8; 64], + app_data: Option>, + ) { + match self.entries.get_mut(&dest_hash) { + Some(existing) => { + existing.timestamp = timestamp; + existing.packet_hash = packet_hash; + existing.public_key = public_key; + existing.app_data = app_data; + // `retained` preserved across refresh. + } + None => { + self.entries.insert( + dest_hash, + KnownDestination { + timestamp, + packet_hash, + public_key, + app_data, + retained: false, + }, + ); + } + } + } + + pub fn get(&self, dest_hash: &[u8; 16]) -> Option<&KnownDestination> { + self.entries.get(dest_hash) + } + + pub fn contains(&self, dest_hash: &[u8; 16]) -> bool { + self.entries.contains_key(dest_hash) + } + + pub fn recall_app_data(&self, dest_hash: &[u8; 16]) -> Option> { + self.entries.get(dest_hash).and_then(|e| e.app_data.clone()) + } + + /// Linear scan for an entry whose `SHA-256(public_key)[:16]` matches `identity_hash`. + pub fn recall_by_identity( + &self, + identity_hash: &[u8; 16], + ) -> Option<(&[u8; 16], &KnownDestination)> { + for (dest_hash, entry) in &self.entries { + let computed_id_hash = rns_crypto::sha::truncated_hash(&entry.public_key); + if &computed_id_hash == identity_hash { + return Some((dest_hash, entry)); + } + } + None + } + + /// Check membership across this table plus a set of locally-registered + /// destination hashes (the fallback used by transport path resolution). + pub fn is_known_or_registered( + &self, + dest_hash: &[u8; 16], + registered: &std::collections::HashSet<[u8; 16]>, + ) -> bool { + self.entries.contains_key(dest_hash) || registered.contains(dest_hash) + } + + pub fn remove(&mut self, dest_hash: &[u8; 16]) -> Option { + self.entries.remove(dest_hash) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.entries.iter() + } + + /// Pin `dest_hash` so `cleanup()` will never consider it stale. + pub fn retain(&mut self, dest_hash: &[u8; 16]) { + if let Some(entry) = self.entries.get_mut(dest_hash) { + entry.retained = true; + } + } + + /// Release a pin set by `retain()`. The entry's `timestamp` (last-seen + /// announce wall-clock) drives `cleanup()` from now on. + pub fn unretain(&mut self, dest_hash: &[u8; 16]) { + if let Some(entry) = self.entries.get_mut(dest_hash) { + entry.retained = false; + } + } + + /// Drop stale entries past `destination_timeout_secs`. `has_path` is a + /// caller-supplied path-table lookup (this crate doesn't depend on + /// rns-transport). Returns the hashes that were dropped. + pub fn cleanup( + &mut self, + now: f64, + destination_timeout_secs: f64, + has_path: impl Fn(&[u8; 16]) -> bool, + ) -> Vec<[u8; 16]> { + let mut to_remove = Vec::new(); + + for (dest_hash, entry) in &self.entries { + // Keep: pinned, or currently routable. + if entry.retained || has_path(dest_hash) { + continue; + } + + let age = now - entry.timestamp; + if age > destination_timeout_secs { + to_remove.push(*dest_hash); + } + } + + for hash in &to_remove { + self.entries.remove(hash); + } + + to_remove + } + + /// Atomically write the table to `path` in Python Reticulum's canonical + /// msgpack format. The loader still accepts older Rust `RNS\x03` files. + pub fn save(&self, path: &Path) -> std::io::Result<()> { + let serialized = self.serialize(); + persistence::atomic_write(path, &serialized) + } + + /// Load the table from `path`; returns an empty table on missing or + /// unparseable input. + pub fn load(path: &Path) -> std::io::Result { + match persistence::read_file(path)? { + Some(data) => Ok(Self::deserialize(&data).unwrap_or_else(|_| Self::new())), + None => Ok(Self::new()), + } + } + + /// Merge `other` into self; existing entries win on key conflict. + pub fn merge(&mut self, other: &KnownDestinations) { + for (hash, entry) in &other.entries { + self.entries.entry(*hash).or_insert_with(|| entry.clone()); + } + } + + const MAGIC: &'static [u8] = b"RNS\x03"; + + // Legacy Rust sidecar/on-disk format (little-endian): + // magic: b"RNS\x03" + // count: u32 + // count × (dest_hash[16], timestamp: f64, packet_hash[32], public_key[64], + // has_app_data: u8, app_data_len: u32, app_data[app_data_len], + // retained: u8 (0|1)) + fn serialize(&self) -> Vec { + let mut entries = Vec::with_capacity(self.entries.len()); + for (hash, entry) in &self.entries { + let app_data = entry + .app_data + .as_ref() + .map(|data| Value::Binary(data.clone())) + .unwrap_or(Value::Nil); + let last_use = if entry.retained { -1i64 } else { 0i64 }; + entries.push(( + Value::Binary(hash.to_vec()), + Value::Array(vec![ + Value::F64(entry.timestamp), + Value::Binary(entry.packet_hash.to_vec()), + Value::Binary(entry.public_key.to_vec()), + app_data, + Value::Integer(last_use.into()), + ]), + )); + } + + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &Value::Map(entries)) + .expect("writing msgpack to Vec cannot fail"); + buf + } + + // Kept as a regression fixture for loading the legacy Rust sidecar format. + #[allow(dead_code)] + fn serialize_legacy_rust(&self) -> Vec { + let mut buf = Vec::new(); + buf.extend_from_slice(Self::MAGIC); + buf.extend_from_slice(&(self.entries.len() as u32).to_le_bytes()); + + for (hash, entry) in &self.entries { + buf.extend_from_slice(hash); + buf.extend_from_slice(&entry.timestamp.to_le_bytes()); + buf.extend_from_slice(&entry.packet_hash); + buf.extend_from_slice(&entry.public_key); + match &entry.app_data { + Some(ad) => { + buf.push(1); + buf.extend_from_slice(&(ad.len() as u32).to_le_bytes()); + buf.extend_from_slice(ad); + } + None => { + buf.push(0); + buf.extend_from_slice(&0u32.to_le_bytes()); + } + } + buf.push(if entry.retained { 1 } else { 0 }); + } + + buf + } + + fn deserialize(data: &[u8]) -> Result { + if !data.starts_with(Self::MAGIC) { + return Self::deserialize_python_msgpack(data); + } + let data = &data[Self::MAGIC.len()..]; + if data.len() < 4 { + return Err("too short"); + } + let count = + u32::from_le_bytes(data[..4].try_into().map_err(|_| "corrupt header")?) as usize; + let mut pos = 4; + let mut entries = HashMap::new(); + + for _ in 0..count { + if pos + 16 + 8 + 32 + 64 + 1 + 4 > data.len() { + return Err("truncated entry"); + } + let mut dest_hash = [0u8; 16]; + dest_hash.copy_from_slice(&data[pos..pos + 16]); + pos += 16; + + let timestamp = f64::from_le_bytes( + data[pos..pos + 8] + .try_into() + .map_err(|_| "corrupt timestamp")?, + ); + pos += 8; + + let mut packet_hash = [0u8; 32]; + packet_hash.copy_from_slice(&data[pos..pos + 32]); + pos += 32; + + let mut public_key = [0u8; 64]; + public_key.copy_from_slice(&data[pos..pos + 64]); + pos += 64; + + let has_app_data = data[pos]; + pos += 1; + + let ad_len = u32::from_le_bytes( + data[pos..pos + 4] + .try_into() + .map_err(|_| "corrupt app_data length")?, + ) as usize; + pos += 4; + + let app_data = if has_app_data == 1 { + if pos + ad_len > data.len() { + return Err("truncated app_data"); + } + let ad = data[pos..pos + ad_len].to_vec(); + pos += ad_len; + Some(ad) + } else { + None + }; + + if pos + 1 > data.len() { + return Err("truncated retained flag"); + } + let retained = data[pos] != 0; + pos += 1; + + entries.insert( + dest_hash, + KnownDestination { + timestamp, + packet_hash, + public_key, + app_data, + retained, + }, + ); + } + + Ok(Self { entries }) + } + + /// Parse Python Reticulum's canonical `storage/known_destinations` file. + /// + /// Python writes msgpack as `{dest_hash: [timestamp, packet_hash, + /// public_key, app_data, last_use]}` and transparently upgrades older + /// four-field entries by treating `last_use` as `0`. + fn deserialize_python_msgpack(data: &[u8]) -> Result { + let value = rmpv::decode::read_value(&mut Cursor::new(data)) + .map_err(|_| "invalid python known_destinations msgpack")?; + let Value::Map(map) = value else { + return Err("python known_destinations root is not a map"); + }; + + let mut entries = HashMap::new(); + for (dest_value, entry_value) in map { + let dest_bytes = Self::msgpack_bytes(&dest_value)?; + if dest_bytes.len() != 16 { + // Python ignores entries whose key is not a truncated hash. + continue; + } + let mut dest_hash = [0u8; 16]; + dest_hash.copy_from_slice(&dest_bytes); + + let Value::Array(fields) = entry_value else { + return Err("python known_destinations entry is not an array"); + }; + if fields.len() < 4 { + return Err("python known_destinations entry is too short"); + } + + let timestamp = Self::msgpack_number(&fields[0])?; + let packet_hash_bytes = Self::msgpack_bytes(&fields[1])?; + let public_key_bytes = Self::msgpack_bytes(&fields[2])?; + let app_data = match &fields[3] { + Value::Nil => None, + value => Some(Self::msgpack_bytes(value)?), + }; + let last_use = fields + .get(4) + .map(Self::msgpack_number) + .transpose()? + .unwrap_or(0.0); + + if packet_hash_bytes.len() != 32 { + return Err("python known_destinations packet hash has invalid length"); + } + if public_key_bytes.len() != 64 { + return Err("python known_destinations public key has invalid length"); + } + + let mut packet_hash = [0u8; 32]; + packet_hash.copy_from_slice(&packet_hash_bytes); + let mut public_key = [0u8; 64]; + public_key.copy_from_slice(&public_key_bytes); + + entries.insert( + dest_hash, + KnownDestination { + timestamp, + packet_hash, + public_key, + app_data, + retained: last_use < 0.0, + }, + ); + } + + Ok(Self { entries }) + } + + fn msgpack_bytes(value: &Value) -> Result, &'static str> { + match value { + Value::Binary(bytes) => Ok(bytes.clone()), + Value::String(s) => s + .as_str() + .map(|s| s.as_bytes().to_vec()) + .ok_or("msgpack string is not valid utf-8"), + _ => Err("msgpack value is not bytes"), + } + } + + fn msgpack_number(value: &Value) -> Result { + match value { + Value::F64(value) => Ok(*value), + Value::F32(value) => Ok((*value).into()), + Value::Integer(value) => value + .as_i64() + .map(|value| value as f64) + .or_else(|| value.as_u64().map(|value| value as f64)) + .ok_or("msgpack integer does not fit in f64"), + _ => Err("msgpack value is not numeric"), + } + } +} + +impl Default for KnownDestinations { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_remember_and_get() { + let mut kd = KnownDestinations::new(); + let hash = [0xAA; 16]; + kd.remember(hash, 1234.5, [0xBB; 32], [0xCC; 64], Some(b"data".to_vec())); + let entry = kd.get(&hash).unwrap(); + assert_eq!(entry.timestamp, 1234.5); + assert_eq!(entry.app_data.as_deref(), Some(b"data".as_slice())); + assert!(!entry.retained); + } + + #[test] + fn test_remember_preserves_retained_on_refresh() { + let mut kd = KnownDestinations::new(); + let hash = [0xAA; 16]; + kd.remember(hash, 100.0, [0; 32], [0; 64], None); + kd.retain(&hash); + assert!(kd.get(&hash).unwrap().retained); + + kd.remember(hash, 200.0, [1; 32], [1; 64], Some(b"new".to_vec())); + let entry = kd.get(&hash).unwrap(); + assert_eq!(entry.timestamp, 200.0); + assert_eq!(entry.app_data.as_deref(), Some(b"new".as_slice())); + assert!(entry.retained); + } + + #[test] + fn test_serialize_deserialize_round_trip() { + let mut kd = KnownDestinations::new(); + kd.remember( + [0x01; 16], + 100.0, + [0x02; 32], + [0x03; 64], + Some(b"hello".to_vec()), + ); + kd.remember([0x04; 16], 200.0, [0x05; 32], [0x06; 64], None); + kd.retain(&[0x04; 16]); + + let serialized = kd.serialize(); + assert!( + !serialized.starts_with(KnownDestinations::MAGIC), + "public save format must remain Python-compatible msgpack" + ); + let kd2 = KnownDestinations::deserialize(&serialized).unwrap(); + assert_eq!(kd2.len(), 2); + + let e1 = kd2.get(&[0x01; 16]).unwrap(); + assert_eq!(e1.timestamp, 100.0); + assert_eq!(e1.app_data.as_deref(), Some(b"hello".as_slice())); + assert!(!e1.retained); + + let e2 = kd2.get(&[0x04; 16]).unwrap(); + assert!(e2.app_data.is_none()); + assert!(e2.retained); + } + + #[test] + fn test_deserialize_rejects_unknown_magic() { + let mut buf = b"OLD\x02".to_vec(); + buf.extend_from_slice(&0u32.to_le_bytes()); + assert!(KnownDestinations::deserialize(&buf).is_err()); + } + + #[test] + fn test_deserialize_legacy_rust_format() { + let mut kd = KnownDestinations::new(); + kd.remember( + [0xAA; 16], + 42.0, + [0xBB; 32], + [0xCC; 64], + Some(b"legacy".to_vec()), + ); + kd.retain(&[0xAA; 16]); + + let serialized = kd.serialize_legacy_rust(); + assert!(serialized.starts_with(KnownDestinations::MAGIC)); + let loaded = KnownDestinations::deserialize(&serialized).unwrap(); + let entry = loaded.get(&[0xAA; 16]).unwrap(); + assert_eq!(entry.timestamp, 42.0); + assert_eq!(entry.packet_hash, [0xBB; 32]); + assert_eq!(entry.public_key, [0xCC; 64]); + assert_eq!(entry.app_data.as_deref(), Some(b"legacy".as_slice())); + assert!(entry.retained); + } + + #[test] + fn test_file_persistence() { + let dir = std::env::temp_dir().join("reticulum_kd_test"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("known_destinations"); + + let mut kd = KnownDestinations::new(); + kd.remember( + [0xAA; 16], + 42.0, + [0xBB; 32], + [0xCC; 64], + Some(b"test".to_vec()), + ); + kd.save(&path).unwrap(); + assert!( + !std::fs::read(&path) + .unwrap() + .starts_with(KnownDestinations::MAGIC) + ); + + let kd2 = KnownDestinations::load(&path).unwrap(); + assert_eq!(kd2.len(), 1); + let entry = kd2.get(&[0xAA; 16]).unwrap(); + assert_eq!(entry.timestamp, 42.0); + + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir(&dir); + } + + #[test] + fn test_merge() { + let mut kd1 = KnownDestinations::new(); + kd1.remember([0x01; 16], 100.0, [0; 32], [0; 64], None); + kd1.remember([0x02; 16], 200.0, [0; 32], [0; 64], None); + + let mut kd2 = KnownDestinations::new(); + // Same key as kd1, different payload, to probe conflict resolution. + kd2.remember([0x02; 16], 300.0, [1; 32], [1; 64], None); + kd2.remember([0x03; 16], 400.0, [0; 32], [0; 64], None); + + kd1.merge(&kd2); + assert_eq!(kd1.len(), 3); + let e2 = kd1.get(&[0x02; 16]).unwrap(); + assert_eq!(e2.timestamp, 200.0); + } + + #[test] + fn test_recall_app_data() { + let mut kd = KnownDestinations::new(); + let hash1 = [0xAA; 16]; + let hash2 = [0xBB; 16]; + + kd.remember( + hash1, + 100.0, + [0; 32], + [0; 64], + Some(b"my app data".to_vec()), + ); + kd.remember(hash2, 200.0, [0; 32], [0; 64], None); + + assert_eq!(kd.recall_app_data(&hash1), Some(b"my app data".to_vec())); + assert_eq!(kd.recall_app_data(&hash2), None); + assert_eq!(kd.recall_app_data(&[0xCC; 16]), None); + } + + #[test] + fn test_retain_unretain_round_trip() { + let mut kd = KnownDestinations::new(); + let hash = [0xAA; 16]; + kd.remember(hash, 100.0, [0; 32], [0; 64], None); + assert!(!kd.get(&hash).unwrap().retained); + + kd.retain(&hash); + assert!(kd.get(&hash).unwrap().retained); + + kd.unretain(&hash); + assert!(!kd.get(&hash).unwrap().retained); + } + + #[test] + fn test_cleanup_retains_pinned() { + let mut kd = KnownDestinations::new(); + let hash = [0xAA; 16]; + // Timestamp far in the past, no path, but pinned. + kd.remember(hash, 0.0, [0; 32], [0; 64], None); + kd.retain(&hash); + + let removed = kd.cleanup(1_000_000.0, 7.0 * 24.0 * 3600.0, |_| false); + assert!(removed.is_empty()); + assert!(kd.contains(&hash)); + } + + #[test] + fn test_cleanup_keeps_pathed_entries() { + let mut kd = KnownDestinations::new(); + let hash = [0xAA; 16]; + // Never used, but has a live path — must keep. + kd.remember(hash, 0.0, [0; 32], [0; 64], None); + + let removed = kd.cleanup(1_000_000.0, 7.0 * 24.0 * 3600.0, |h| h == &hash); + assert!(removed.is_empty()); + assert!(kd.contains(&hash)); + } + + #[test] + fn test_cleanup_drops_pathless_past_destination_timeout() { + let mut kd = KnownDestinations::new(); + let stale_never_used = [0xAA; 16]; + let stale_used = [0xBB; 16]; + let fresh = [0xCC; 16]; + let dest_timeout = 7.0 * 24.0 * 3600.0; + + kd.remember(stale_never_used, 0.0, [0; 32], [0; 64], None); + kd.remember(stale_used, 0.0, [0; 32], [0; 64], None); + kd.remember(fresh, dest_timeout - 60.0, [0; 32], [0; 64], None); + + // `now` sits one second past the timeout for the stale pair. + let now = dest_timeout + 1.0; + let removed = kd.cleanup(now, dest_timeout, |_| false); + + // Both stale arms are reaped under the uniform policy; the fresh + // entry (only ~60 s old at `now`) survives. + assert_eq!(removed.len(), 2); + assert!(removed.contains(&stale_never_used)); + assert!(removed.contains(&stale_used)); + assert!(kd.contains(&fresh)); + } + + #[test] + fn test_cleanup_keeps_pathless_well_below_destination_timeout() { + let mut kd = KnownDestinations::new(); + let never_used = [0xAA; 16]; + let used = [0xBB; 16]; + + kd.remember(never_used, 0.0, [0; 32], [0; 64], None); + kd.remember(used, 0.0, [0; 32], [0; 64], None); + + let removed = kd.cleanup(10.0 * 60.0, 7.0 * 24.0 * 3600.0, |_| false); + assert!(removed.is_empty()); + assert!(kd.contains(&never_used)); + assert!(kd.contains(&used)); + } +} diff --git a/crates/rns-identity/src/lib.rs b/crates/rns-identity/src/lib.rs new file mode 100644 index 0000000..f5975ab --- /dev/null +++ b/crates/rns-identity/src/lib.rs @@ -0,0 +1,12 @@ +//! Reticulum identities, destinations, announces, ratchets, IFAC. +//! +//! Python reference: `RNS/Identity.py`, `RNS/Destination.py`. + +pub mod announce; +pub mod destination; +pub mod identity; +pub mod ifac; +pub mod known_destinations; +pub mod name_hash; +pub mod persistence; +pub mod ratchet; diff --git a/crates/rns-identity/src/name_hash.rs b/crates/rns-identity/src/name_hash.rs new file mode 100644 index 0000000..48985dd --- /dev/null +++ b/crates/rns-identity/src/name_hash.rs @@ -0,0 +1,32 @@ +use rns_crypto::sha::sha256; + +/// 80-bit name hash (`SHA-256(app_name)[:10]`). +/// +/// `app_name` is the full dotted app/aspect path, e.g. `"lxmf.delivery"`. +pub fn name_hash(app_name: &str) -> [u8; 10] { + let full = sha256(app_name.as_bytes()); + let mut out = [0u8; 10]; + out.copy_from_slice(&full[..10]); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_name_hash_basic() { + let h = name_hash("test.app"); + assert_eq!(h.len(), 10); + } + + #[test] + fn test_name_hash_deterministic() { + assert_eq!(name_hash("lxmf.delivery"), name_hash("lxmf.delivery")); + } + + #[test] + fn test_name_hash_different_names() { + assert_ne!(name_hash("app.one"), name_hash("app.two")); + } +} diff --git a/crates/rns-identity/src/persistence.rs b/crates/rns-identity/src/persistence.rs new file mode 100644 index 0000000..b9497a0 --- /dev/null +++ b/crates/rns-identity/src/persistence.rs @@ -0,0 +1,68 @@ +use std::fs; +use std::io::Write; +use std::path::Path; + +/// Write `data` to `path` via `.tmp` + `rename`, fsyncing first. +/// +/// On Unix the temp file is created with mode `0600` so that key material is +/// not world-readable even during the write. +pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> { + let tmp_path = path.with_extension("tmp"); + + { + #[cfg(unix)] + let mut f = { + use std::os::unix::fs::OpenOptionsExt; + std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(&tmp_path)? + }; + #[cfg(not(unix))] + let mut f = fs::File::create(&tmp_path)?; + + f.write_all(data)?; + f.sync_all()?; + } + + fs::rename(&tmp_path, path)?; + Ok(()) +} + +/// Read `path` in full, returning `None` if the file does not exist. +pub fn read_file(path: &Path) -> std::io::Result>> { + match fs::read(path) { + Ok(data) => Ok(Some(data)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + #[test] + fn test_atomic_write_and_read() { + let dir = std::env::temp_dir().join("reticulum_test_persistence"); + let _ = fs::create_dir_all(&dir); + let path = dir.join("test_atomic"); + + atomic_write(&path, b"hello world").unwrap(); + let data = read_file(&path).unwrap().unwrap(); + assert_eq!(data, b"hello world"); + + let _ = fs::remove_file(&path); + let _ = fs::remove_dir(&dir); + } + + #[test] + fn test_read_nonexistent() { + let path = PathBuf::from("/tmp/reticulum_nonexistent_file_xyz"); + let result = read_file(&path).unwrap(); + assert!(result.is_none()); + } +} diff --git a/crates/rns-identity/src/ratchet.rs b/crates/rns-identity/src/ratchet.rs new file mode 100644 index 0000000..6a3b7a4 --- /dev/null +++ b/crates/rns-identity/src/ratchet.rs @@ -0,0 +1,658 @@ +use rns_crypto::sha::full_hash; +use rns_crypto::x25519::X25519PrivateKey; +use rns_wire::constants::{NAME_HASH_LENGTH, RATCHET_COUNT, RATCHET_EXPIRY, RATCHET_INTERVAL}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; +use zeroize::Zeroize; + +use crate::persistence; + +/// A bounded history of X25519 private ratchet keys for forward secrecy. +/// +/// Index 0 is the most recent key; older keys are retained so decryption can +/// still succeed for in-flight ciphertexts. All key material is zeroised on +/// drop and on truncation. +pub struct RatchetRing { + keys: Vec<[u8; 32]>, + last_rotation: f64, + retained_count: usize, + rotation_interval: u64, +} + +impl RatchetRing { + pub fn new() -> Self { + Self { + keys: Vec::new(), + last_rotation: 0.0, + retained_count: RATCHET_COUNT, + rotation_interval: RATCHET_INTERVAL, + } + } + + /// Generate a fresh ratchet key, push it to the front, and return its public key. + /// + /// Any keys evicted past `retained_count` are zeroised before drop. + pub fn rotate(&mut self) -> [u8; 32] { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let prv = X25519PrivateKey::generate(); + let pub_key = prv.public_key().to_bytes(); + + self.keys.insert(0, prv.to_bytes()); + if self.keys.len() > self.retained_count { + for key in &mut self.keys[self.retained_count..] { + key.zeroize(); + } + self.keys.truncate(self.retained_count); + } + self.last_rotation = now; + + pub_key + } + + /// True when at least `rotation_interval` seconds have elapsed since the last rotate. + pub fn needs_rotation(&self) -> bool { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + now - self.last_rotation >= self.rotation_interval as f64 + } + + /// Public key of the most recent ratchet, if the ring has been rotated at least once. + pub fn current_public_key(&self) -> Option<[u8; 32]> { + self.keys.first().map(|prv_bytes| { + let prv = X25519PrivateKey::from_bytes(prv_bytes); + prv.public_key().to_bytes() + }) + } + + /// All retained private keys, newest first, for decryption attempts. + pub fn private_keys(&self) -> &[[u8; 32]] { + &self.keys + } + + pub fn len(&self) -> usize { + self.keys.len() + } + + pub fn is_empty(&self) -> bool { + self.keys.is_empty() + } + + /// Set `retained_count`; returns `false` if `count == 0`. + pub fn set_retained_ratchets(&mut self, count: usize) -> bool { + if count > 0 { + self.retained_count = count; + self.clean(); + true + } else { + false + } + } + + pub fn retained_ratchets(&self) -> usize { + self.retained_count + } + + /// Set `rotation_interval` (seconds); returns `false` if `interval == 0`. + pub fn set_ratchet_interval(&mut self, interval: u64) -> bool { + if interval > 0 { + self.rotation_interval = interval; + true + } else { + false + } + } + + pub fn ratchet_interval(&self) -> u64 { + self.rotation_interval + } + + fn clean(&mut self) { + if self.keys.len() > self.retained_count { + self.keys.truncate(self.retained_count); + } + } + + /// Persist to `path` as a Python-compatible msgpack envelope. + /// + /// Python writes `{signature, ratchets}`. Rust also includes + /// `last_rotation`, which Python ignores and Rust defaults when loading a + /// Python-written file. `ratchets` is itself the msgpack-encoded key list + /// signed by the owning identity. + pub fn save(&self, path: &Path, signature: &[u8; 64]) -> std::io::Result<()> { + let ratchets_packed = + rmp_serde::to_vec(&self.keys).map_err(|e| std::io::Error::other(e.to_string()))?; + + let persisted = RatchetRingPersisted { + signature: signature.to_vec(), + ratchets: ratchets_packed, + last_rotation: self.last_rotation, + }; + let buf = + rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?; + persistence::atomic_write(path, &buf) + } + + /// Load the ring, retrying with 1s/2s/4s backoff to ride out transient + /// read errors while another process is rewriting the file. + pub fn load(path: &Path) -> std::io::Result<(Self, [u8; 64])> { + let mut last_err = None; + let delays_ms = [0, 1000, 2000, 4000]; + + for (attempt, delay) in delays_ms.iter().enumerate() { + if *delay > 0 { + std::thread::sleep(std::time::Duration::from_millis(*delay)); + } + + match Self::try_load(path) { + Ok(result) => return Ok(result), + Err(e) => { + if attempt < delays_ms.len() - 1 { + tracing::warn!( + attempt = attempt + 1, + path = %path.display(), + error = %e, + "ratchet load attempt failed, retrying" + ); + } + last_err = Some(e); + } + } + } + + Err(last_err.unwrap()) + } + + fn try_load(path: &Path) -> std::io::Result<(Self, [u8; 64])> { + let data = std::fs::read(path)?; + + let persisted: RatchetRingPersisted = + rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?; + + if persisted.signature.len() != 64 { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "invalid signature length in ratchet file", + )); + } + + let mut signature = [0u8; 64]; + signature.copy_from_slice(&persisted.signature); + + let keys: Vec<[u8; 32]> = rmp_serde::from_slice(&persisted.ratchets) + .map_err(|e| std::io::Error::other(e.to_string()))?; + + Ok(( + Self { + keys, + last_rotation: persisted.last_rotation, + retained_count: RATCHET_COUNT, + rotation_interval: RATCHET_INTERVAL, + }, + signature, + )) + } +} + +#[derive(Serialize, Deserialize)] +struct RatchetRingPersisted { + signature: Vec, + ratchets: Vec, + #[serde(default)] + last_rotation: f64, +} + +impl Zeroize for RatchetRing { + fn zeroize(&mut self) { + for key in &mut self.keys { + key.zeroize(); + } + self.keys.clear(); + self.last_rotation = 0.0; + } +} + +impl Drop for RatchetRing { + fn drop(&mut self) { + self.zeroize(); + } +} + +impl Default for RatchetRing { + fn default() -> Self { + Self::new() + } +} + +/// Ratchet public key learned from a remote destination's announce, with +/// the local receive time used for expiry. +pub struct ReceivedRatchet { + pub ratchet_pub: [u8; 32], + pub received_at: f64, +} + +// On-disk shape shared with the Python reference: `{"ratchet": bytes, "received": float}`. +#[derive(Serialize, Deserialize)] +struct ReceivedRatchetPersisted { + ratchet: Vec, + received: f64, +} + +impl ReceivedRatchet { + pub fn new(ratchet_pub: [u8; 32]) -> Self { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + Self { + ratchet_pub, + received_at: now, + } + } + + pub fn is_expired(&self) -> bool { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + now - self.received_at > RATCHET_EXPIRY as f64 + } + + pub fn ratchet_id(&self) -> Vec { + get_ratchet_id(&self.ratchet_pub) + } + + /// Persist to `{ratchetdir}/{hex(dest_hash)}` in the shared msgpack format. + pub fn save(&self, path: &Path) -> std::io::Result<()> { + let persisted = ReceivedRatchetPersisted { + ratchet: self.ratchet_pub.to_vec(), + received: self.received_at, + }; + let buf = + rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?; + + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + + persistence::atomic_write(path, &buf) + } + + pub fn load(path: &Path) -> std::io::Result { + let data = std::fs::read(path)?; + let persisted: ReceivedRatchetPersisted = + rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?; + + if persisted.ratchet.len() != 32 { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "invalid ratchet public key length", + )); + } + let mut ratchet_pub = [0u8; 32]; + ratchet_pub.copy_from_slice(&persisted.ratchet); + + Ok(Self { + ratchet_pub, + received_at: persisted.received, + }) + } +} + +/// Compute the ratchet identifier: `full_hash(ratchet_pub)[..NAME_HASH_LENGTH]`. +pub fn get_ratchet_id(ratchet_pub: &[u8; 32]) -> Vec { + let hash = full_hash(ratchet_pub); + hash[..NAME_HASH_LENGTH].to_vec() +} + +/// Derive the ratchet public key from its 32-byte private key. +pub fn ratchet_public_bytes(ratchet_prv: &[u8; 32]) -> [u8; 32] { + let prv = X25519PrivateKey::from_bytes(ratchet_prv); + prv.public_key().to_bytes() +} + +/// Sweep `dir`, deleting expired and unparseable ratchet files. Returns the +/// number of files removed. +/// +/// Only touches disk; pair with [`purge_expired_ratchets_in_memory`] when an +/// in-memory cache is also kept. +pub fn clean_received_ratchets_dir(dir: &Path) -> usize { + let mut removed = 0usize; + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_file() { + continue; + } + let drop_it = match ReceivedRatchet::load(&path) { + Ok(r) => r.is_expired(), + Err(_) => true, + }; + if drop_it { + match std::fs::remove_file(&path) { + Ok(()) => removed += 1, + Err(e) => tracing::error!( + path = %path.display(), + error = %e, + "failed to remove expired/corrupt ratchet file" + ), + } + } + } + removed +} + +/// Drop expired entries from an in-memory received-ratchet map; returns the count removed. +pub fn purge_expired_ratchets_in_memory( + map: &mut HashMap, +) -> usize { + let before = map.len(); + map.retain(|_, r| !r.is_expired()); + before - map.len() +} + +/// Per-destination cache of remote ratchet public keys, with optional disk backing. +pub struct ReceivedRatchetStore { + entries: HashMap<[u8; 16], ReceivedRatchet>, + storage_dir: Option, +} + +impl ReceivedRatchetStore { + /// In-memory only; no persistence. + pub fn new() -> Self { + Self { + entries: HashMap::new(), + storage_dir: None, + } + } + + /// Store backed by `dir` (one file per destination hash). + pub fn with_storage(dir: PathBuf) -> Self { + Self { + entries: HashMap::new(), + storage_dir: Some(dir), + } + } + + /// Record `ratchet_pub` for `dest_hash`. Re-inserting the identical key is a no-op; + /// any other value replaces the entry and is written to disk when backed. + pub fn remember(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32]) { + if let Some(existing) = self.entries.get(&dest_hash) + && existing.ratchet_pub == ratchet_pub + { + return; + } + + let received = ReceivedRatchet::new(ratchet_pub); + + if let Some(ref dir) = self.storage_dir { + let hexhash = hex::encode(dest_hash); + let path = dir.join(&hexhash); + if let Err(e) = received.save(&path) { + tracing::error!( + dest = hexhash, + error = %e, + "failed to persist received ratchet" + ); + } + } + + self.entries.insert(dest_hash, received); + } + + /// Return the current ratchet public key for `dest_hash`, loading from + /// disk on miss. Yields `None` if the entry is expired or absent. + pub fn get(&mut self, dest_hash: &[u8; 16]) -> Option<[u8; 32]> { + if !self.entries.contains_key(dest_hash) + && let Some(ref dir) = self.storage_dir + { + let hexhash = hex::encode(dest_hash); + let path = dir.join(&hexhash); + if path.exists() { + match ReceivedRatchet::load(&path) { + Ok(ratchet) => { + if !ratchet.is_expired() && ratchet.ratchet_pub.len() == 32 { + self.entries.insert(*dest_hash, ratchet); + } else { + return None; + } + } + Err(e) => { + tracing::error!( + dest = hexhash, + error = %e, + "failed to load ratchet from disk" + ); + return None; + } + } + } + } + + self.entries + .get(dest_hash) + .filter(|r| !r.is_expired()) + .map(|r| r.ratchet_pub) + } + + /// Return the current ratchet ID for `dest_hash`, loading from disk on miss. + pub fn current_ratchet_id(&mut self, dest_hash: &[u8; 16]) -> Option> { + self.get(dest_hash) + .map(|pub_bytes| get_ratchet_id(&pub_bytes)) + } + + pub fn clean_expired(&mut self) { + self.entries.retain(|_, ratchet| !ratchet.is_expired()); + if let Some(ref dir) = self.storage_dir { + clean_received_ratchets_dir(dir); + } + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +impl Default for ReceivedRatchetStore { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ratchet_ring_rotate() { + let mut ring = RatchetRing::new(); + assert!(ring.is_empty()); + + let pub1 = ring.rotate(); + assert_eq!(ring.len(), 1); + assert!(ring.current_public_key().is_some()); + + let pub2 = ring.rotate(); + assert_eq!(ring.len(), 2); + assert_ne!(pub1, pub2); + } + + #[test] + fn test_ratchet_ring_max_keys() { + let mut ring = RatchetRing::new(); + for _ in 0..RATCHET_COUNT + 10 { + ring.rotate(); + } + assert_eq!(ring.len(), RATCHET_COUNT); + } + + #[test] + fn test_ratchet_ring_file_roundtrip() { + let dir = std::env::temp_dir().join("reticulum_ratchet_test_msgpack"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("ratchets"); + + let mut ring = RatchetRing::new(); + ring.rotate(); + ring.rotate(); + ring.rotate(); + let sig = [0xAA; 64]; + ring.save(&path, &sig).unwrap(); + + let (ring2, sig2) = RatchetRing::load(&path).unwrap(); + assert_eq!(ring2.len(), 3); + assert_eq!(sig2, sig); + assert_eq!(ring.private_keys(), ring2.private_keys()); + + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir(&dir); + } + + #[test] + fn test_ratchet_ring_loads_python_shape_without_last_rotation() { + #[derive(Serialize)] + struct PythonRatchets { + signature: Vec, + ratchets: Vec, + } + + let dir = std::env::temp_dir().join("reticulum_python_ratchet_test_msgpack"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("ratchets"); + + let keys = vec![[0x11; 32], [0x22; 32]]; + let signature = vec![0xAA; 64]; + let ratchets = rmp_serde::to_vec(&keys).unwrap(); + let persisted = PythonRatchets { + signature: signature.clone(), + ratchets, + }; + let buf = rmp_serde::to_vec(&persisted).unwrap(); + std::fs::write(&path, buf).unwrap(); + + let (ring, loaded_signature) = RatchetRing::load(&path).unwrap(); + assert_eq!(ring.len(), 2); + assert_eq!(ring.private_keys(), keys.as_slice()); + assert_eq!(loaded_signature.as_slice(), signature.as_slice()); + + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir(&dir); + } + + #[test] + fn test_set_retained_ratchets() { + let mut ring = RatchetRing::new(); + for _ in 0..20 { + ring.rotate(); + } + assert_eq!(ring.len(), 20); + + assert!(ring.set_retained_ratchets(5)); + assert_eq!(ring.len(), 5); + assert_eq!(ring.retained_ratchets(), 5); + + assert!(!ring.set_retained_ratchets(0)); + assert_eq!(ring.retained_ratchets(), 5); + } + + #[test] + fn test_set_ratchet_interval() { + let mut ring = RatchetRing::new(); + assert_eq!(ring.ratchet_interval(), RATCHET_INTERVAL); + + assert!(ring.set_ratchet_interval(60)); + assert_eq!(ring.ratchet_interval(), 60); + + assert!(!ring.set_ratchet_interval(0)); + assert_eq!(ring.ratchet_interval(), 60); + } + + #[test] + fn test_received_ratchet_msgpack_roundtrip() { + let dir = std::env::temp_dir().join("reticulum_recv_ratchet_test"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("test_ratchet"); + + let ratchet_pub = rns_crypto::random::random_32(); + let received = ReceivedRatchet::new(ratchet_pub); + + received.save(&path).unwrap(); + let loaded = ReceivedRatchet::load(&path).unwrap(); + + assert_eq!(loaded.ratchet_pub, ratchet_pub); + assert!((loaded.received_at - received.received_at).abs() < 0.001); + assert!(!loaded.is_expired()); + + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir(&dir); + } + + #[test] + fn test_received_ratchet_store() { + let dir = std::env::temp_dir().join("reticulum_ratchet_store_test"); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::create_dir_all(&dir); + + let mut store = ReceivedRatchetStore::with_storage(dir.clone()); + let dest_hash = [0xAA; 16]; + let ratchet_pub = rns_crypto::random::random_32(); + + store.remember(dest_hash, ratchet_pub); + assert_eq!(store.len(), 1); + + assert_eq!(store.get(&dest_hash), Some(ratchet_pub)); + + let rid = store.current_ratchet_id(&dest_hash); + assert!(rid.is_some()); + + // Fresh store re-reads the entry from disk. + let mut store2 = ReceivedRatchetStore::with_storage(dir.clone()); + assert_eq!(store2.get(&dest_hash), Some(ratchet_pub)); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_received_ratchet_store_dedup() { + let mut store = ReceivedRatchetStore::new(); + let dest_hash = [0xBB; 16]; + let ratchet_pub = rns_crypto::random::random_32(); + + store.remember(dest_hash, ratchet_pub); + store.remember(dest_hash, ratchet_pub); + assert_eq!(store.len(), 1); + + let ratchet_pub2 = rns_crypto::random::random_32(); + store.remember(dest_hash, ratchet_pub2); + assert_eq!(store.len(), 1); + assert_eq!(store.get(&dest_hash), Some(ratchet_pub2)); + } + + #[test] + fn test_get_ratchet_id() { + let pub_bytes = rns_crypto::random::random_32(); + let rid = get_ratchet_id(&pub_bytes); + assert_eq!(rid.len(), NAME_HASH_LENGTH); + } + + #[test] + fn test_ratchet_public_bytes() { + let prv = X25519PrivateKey::generate(); + let prv_bytes = prv.to_bytes(); + let pub_bytes = ratchet_public_bytes(&prv_bytes); + assert_eq!(pub_bytes, prv.public_key().to_bytes()); + } +} diff --git a/crates/rns-interface/Cargo.toml b/crates/rns-interface/Cargo.toml new file mode 100644 index 0000000..c53914e --- /dev/null +++ b/crates/rns-interface/Cargo.toml @@ -0,0 +1,77 @@ +[package] +name = "rns-interface" +description = "Network interface trait and implementations for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[features] +default = [] +serial = ["dep:serialport"] +ble = ["dep:btleplug", "dep:futures", "dep:uuid"] +ble_peer = ["ble"] +# See rns-transport's mobile-throttle. When enabled, auto-interface beacons +# and reverse-peering probes slow down in the background; BLE peer scan +# cadence adjusts to `is_foreground`. Disabled on desktop builds. +mobile-throttle = ["rns-transport/mobile-throttle"] + +[dependencies] +rns-crypto = { workspace = true, features = ["std"] } +rns-wire = { workspace = true, features = ["std"] } +rns-transport = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +bytes = { workspace = true } +tracing = { workspace = true } +socket2 = { workspace = true } +if-addrs = { workspace = true } +serialport = { workspace = true, optional = true } +btleplug = { workspace = true, optional = true } +futures = { version = "0.3", optional = true } +uuid = { version = "1", optional = true } +rand = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +hex = { workspace = true } + +# Apple BLE Peripheral (CoreBluetooth GATT server, iOS + macOS). +# Version pinned to match btleplug's internal objc2 version so the shared +# runtime types stay binary-compatible. objc2-core-bluetooth gives us +# linked-symbol access to NSString constants (CBCentralManagerScanOption*, +# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal +# values, which Apple is free to change. +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] +objc2 = "0.5" +objc2-foundation = "0.2" +objc2-core-bluetooth = "0.2" + +[target.'cfg(target_os = "macos")'.dependencies] +libc = "0.2" + +# Android JNI (BLE Peripheral, USB Serial) +[target.'cfg(target_os = "android")'.dependencies] +jni = "0.19" + +# Linux BLE Peripheral via BlueZ D-Bus (real GATT server, B7). +# Linux-only target dep so non-Linux builds don't pull in BlueZ. The +# linux_peripheral module is gated by both `ble` feature and target_os. +[target.'cfg(target_os = "linux")'.dependencies] +bluer = { version = "0.17", features = ["bluetoothd"] } + +# Windows BLE Peripheral via WinRT GattServiceProvider (MSIX-packaged apps). +# Windows-only target dep so cross-platform builds don't pull in WinRT +# shims. The windows_peripheral module is gated by `ble` feature and +# target_os. GattServiceProvider.CreateAsync returns AccessDenied for +# unpackaged Win32 binaries; we surface that as a clear peripheral- +# unavailable event so embedding UIs can direct users to an MSIX build for +# discoverability. +[target.'cfg(target_os = "windows")'.dependencies] +windows = { version = "0.58", features = [ + "Devices_Bluetooth", + "Devices_Bluetooth_Advertisement", + "Devices_Bluetooth_GenericAttributeProfile", + "Devices_Radios", + "Foundation", + "Foundation_Collections", + "Storage_Streams", +] } diff --git a/crates/rns-interface/src/android_usb.rs b/crates/rns-interface/src/android_usb.rs new file mode 100644 index 0000000..405bd23 --- /dev/null +++ b/crates/rns-interface/src/android_usb.rs @@ -0,0 +1,658 @@ +//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use bytes::Bytes; +use tokio::sync::mpsc; + +use crate::kiss; +use crate::rnode; +use crate::traits::{ + InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode, +}; +use rns_transport::messages::TransportMessage; + +pub const BAUD_RATE: u32 = 115_200; + +/// USB VIDs of serial chipsets commonly used by RNode hardware. +pub const KNOWN_VIDS: &[(u16, &str)] = &[ + (0x0403, "FTDI"), + (0x10C4, "Silicon Labs CP210x"), + (0x1A86, "WCH CH340/CH341"), + (0x0525, "CDC-ACM (Netchip)"), + (0x2E8A, "Raspberry Pi Pico / RP2040"), + (0x303A, "Espressif ESP32-S3"), + (0x239A, "Adafruit"), + (0x1915, "Nordic Semiconductor NRF52840"), +]; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct UsbSerialDevice { + pub device_name: String, + pub vid: u16, + pub pid: u16, + pub chipset: String, + pub manufacturer: String, + pub product: String, +} + +#[derive(Debug, Clone)] +pub struct AndroidUsbConfig { + pub name: String, + pub device_name: String, + pub baud_rate: u32, + pub frequency: u32, + pub bandwidth: u32, + pub spreading_factor: u8, + pub coding_rate: u8, + pub tx_power: u8, + pub mode: InterfaceMode, +} + +impl AndroidUsbConfig { + pub fn new(name: &str, device_name: &str) -> Self { + Self { + name: name.to_string(), + device_name: device_name.to_string(), + baud_rate: BAUD_RATE, + frequency: 915_000_000, + bandwidth: 125_000, + spreading_factor: 8, + coding_rate: 6, + tx_power: 17, + mode: InterfaceMode::Full, + } + } +} + +use jni::JavaVM; +use jni::objects::{GlobalRef, JObject, JValue}; +use std::sync::OnceLock; + +static JAVA_VM: OnceLock = OnceLock::new(); +static APP_CONTEXT: OnceLock = OnceLock::new(); + +/// Stash JavaVM (wired from `JNI_OnLoad`); Application context fetched lazily +/// via `ActivityThread.currentApplication()` so callers don't thread it through. +pub fn init_vm(vm: JavaVM) { + let _ = JAVA_VM.set(vm); +} + +/// Shared JavaVM accessor (e.g. `auto.rs::get_link_local_addrs_android`). +/// `None` until `init_vm` has run. +pub fn java_vm() -> Option<&'static JavaVM> { + JAVA_VM.get() +} + +fn with_env(f: F) -> Result +where + F: FnOnce(&jni::JNIEnv) -> Result, +{ + let vm = JAVA_VM.get().ok_or("JavaVM not initialized for USB")?; + let env = vm + .attach_current_thread() + .map_err(|e| format!("JNI: {e}"))?; + f(&env) +} + +/// Lazily resolve the Application context; cached after first resolution. +fn ensure_app_context(env: &jni::JNIEnv) -> Result<&'static GlobalRef, String> { + if let Some(ctx) = APP_CONTEXT.get() { + return Ok(ctx); + } + let activity_thread = env + .find_class("android/app/ActivityThread") + .map_err(|e| format!("ActivityThread class: {e}"))?; + let app = env + .call_static_method( + activity_thread, + "currentApplication", + "()Landroid/app/Application;", + &[], + ) + .map_err(|e| format!("currentApplication: {e}"))? + .l() + .map_err(|e| format!("currentApplication object: {e}"))?; + if app.is_null() { + return Err("ActivityThread.currentApplication() returned null".into()); + } + let global = env + .new_global_ref(app) + .map_err(|e| format!("new_global_ref(application): {e}"))?; + let _ = APP_CONTEXT.set(global); + APP_CONTEXT + .get() + .ok_or_else(|| "APP_CONTEXT race".to_string()) +} + +pub async fn enumerate_usb_devices() -> Result, String> { + tokio::task::spawn_blocking(|| { + with_env(|env| { + let ctx = ensure_app_context(env)?; + let usb_str = env.new_string("usb").map_err(|e| format!("{e}"))?; + let usb_mgr = env + .call_method( + ctx.as_obj(), + "getSystemService", + "(Ljava/lang/String;)Ljava/lang/Object;", + &[JValue::Object(usb_str.into())], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + + let device_map = env + .call_method(usb_mgr, "getDeviceList", "()Ljava/util/HashMap;", &[]) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let values = env + .call_method(device_map, "values", "()Ljava/util/Collection;", &[]) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let iter = env + .call_method(values, "iterator", "()Ljava/util/Iterator;", &[]) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + + let mut devices = Vec::new(); + loop { + let has_next = env + .call_method(iter, "hasNext", "()Z", &[]) + .map_err(|e| format!("{e}"))? + .z() + .map_err(|e| format!("{e}"))?; + if !has_next { + break; + } + + let device = env + .call_method(iter, "next", "()Ljava/lang/Object;", &[]) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let vid = env + .call_method(device, "getVendorId", "()I", &[]) + .map_err(|e| format!("{e}"))? + .i() + .map_err(|e| format!("{e}"))? as u16; + let pid = env + .call_method(device, "getProductId", "()I", &[]) + .map_err(|e| format!("{e}"))? + .i() + .map_err(|e| format!("{e}"))? as u16; + let name_js = env + .call_method(device, "getDeviceName", "()Ljava/lang/String;", &[]) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let name: String = env + .get_string(name_js.into()) + .map(|s| s.into()) + .unwrap_or_default(); + + let chipset = KNOWN_VIDS + .iter() + .find(|(v, _)| *v == vid) + .map(|(_, n)| n.to_string()) + .unwrap_or_default(); + + if !chipset.is_empty() { + devices.push(UsbSerialDevice { + device_name: name, + vid, + pid, + chipset, + manufacturer: String::new(), + product: String::new(), + }); + } + } + Ok(devices) + }) + }) + .await + .map_err(|e| format!("{e}"))? +} + +pub async fn request_usb_permission(device_name: &str) -> Result { + let dev_name = device_name.to_string(); + tokio::task::spawn_blocking(move || { + with_env(|env| { + let ctx = ensure_app_context(env)?; + let usb_str = env.new_string("usb").map_err(|e| format!("{e}"))?; + let usb_mgr = env + .call_method( + ctx.as_obj(), + "getSystemService", + "(Ljava/lang/String;)Ljava/lang/Object;", + &[JValue::Object(usb_str.into())], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + + let device_map = env + .call_method(usb_mgr, "getDeviceList", "()Ljava/util/HashMap;", &[]) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let key = env.new_string(&dev_name).map_err(|e| format!("{e}"))?; + let device = env + .call_method( + device_map, + "get", + "(Ljava/lang/Object;)Ljava/lang/Object;", + &[JValue::Object(key.into())], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + + if device.is_null() { + return Err(format!("USB device not found: {dev_name}")); + } + + env.call_method( + usb_mgr, + "hasPermission", + "(Landroid/hardware/usb/UsbDevice;)Z", + &[JValue::Object(device)], + ) + .map_err(|e| format!("{e}"))? + .z() + .map_err(|e| format!("{e}")) + }) + }) + .await + .map_err(|e| format!("{e}"))? +} + +/// Open device, claim CDC data interface, set line coding. +/// Returns `(tx, rx, connected_flag)` — drop flag to false to stop loops. +async fn open_usb_serial( + device_name: &str, + baud_rate: u32, +) -> Result< + ( + mpsc::Sender>, + mpsc::Receiver>, + Arc, + ), + InterfaceError, +> { + let dev_name = device_name.to_string(); + + tokio::task::spawn_blocking(move || -> Result<_, String> { + with_env(|env| { + let ctx = ensure_app_context(env)?; + let usb_str = env.new_string("usb").map_err(|e| format!("{e}"))?; + let usb_mgr = env + .call_method( + ctx.as_obj(), + "getSystemService", + "(Ljava/lang/String;)Ljava/lang/Object;", + &[JValue::Object(usb_str.into())], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + + let device_map = env + .call_method(usb_mgr, "getDeviceList", "()Ljava/util/HashMap;", &[]) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let key = env.new_string(&dev_name).map_err(|e| format!("{e}"))?; + let device = env + .call_method( + device_map, + "get", + "(Ljava/lang/Object;)Ljava/lang/Object;", + &[JValue::Object(key.into())], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + + let connection = env + .call_method( + usb_mgr, + "openDevice", + "(Landroid/hardware/usb/UsbDevice;)Landroid/hardware/usb/UsbDeviceConnection;", + &[JValue::Object(device)], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + if connection.is_null() { + return Err("Failed to open USB device (permission denied?)".into()); + } + + // CDC-Data (0x0A) or vendor-specific (0xFF) with bulk IN+OUT. + let iface_count = env + .call_method(device, "getInterfaceCount", "()I", &[]) + .map_err(|e| format!("{e}"))? + .i() + .map_err(|e| format!("{e}"))?; + + let mut data_iface = JObject::null(); + let mut ep_in = JObject::null(); + let mut ep_out = JObject::null(); + + for i in 0..iface_count { + let iface = env + .call_method( + device, + "getInterface", + "(I)Landroid/hardware/usb/UsbInterface;", + &[JValue::Int(i)], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let cls = env + .call_method(iface, "getInterfaceClass", "()I", &[]) + .map_err(|e| format!("{e}"))? + .i() + .map_err(|e| format!("{e}"))?; + + if cls == 0x0A || cls == 0xFF { + let epc = env + .call_method(iface, "getEndpointCount", "()I", &[]) + .map_err(|e| format!("{e}"))? + .i() + .map_err(|e| format!("{e}"))?; + for j in 0..epc { + let ep = env + .call_method( + iface, + "getEndpoint", + "(I)Landroid/hardware/usb/UsbEndpoint;", + &[JValue::Int(j)], + ) + .map_err(|e| format!("{e}"))? + .l() + .map_err(|e| format!("{e}"))?; + let dir = env + .call_method(ep, "getDirection", "()I", &[]) + .map_err(|e| format!("{e}"))? + .i() + .map_err(|e| format!("{e}"))?; + if dir == 0x80 { + ep_in = ep; + } else { + ep_out = ep; + } + } + if !ep_in.is_null() && !ep_out.is_null() { + data_iface = iface; + break; + } + } + } + if data_iface.is_null() { + return Err("No CDC-ACM interface found".into()); + } + + env.call_method( + connection, + "claimInterface", + "(Landroid/hardware/usb/UsbInterface;Z)Z", + &[JValue::Object(data_iface), JValue::Bool(1)], + ) + .map_err(|e| format!("{e}"))?; + + // CDC SET_LINE_CODING (bmRequestType=0x21, bRequest=0x20): + // [baud_rate u32 LE][stop_bits u8][parity u8][data_bits u8]. + // + // The Android signature is `controlTransfer(int, int, int, int, + // byte[], int, int)` — seven parameters including the trailing + // timeout. Calling with the six-parameter signature throws + // NoSuchMethodError into a pending JNI exception, which the next + // JNI op (new_global_ref) detects as a CheckJNI violation and + // aborts the process. CP2102 / CH340 / FTDI ignore CDC class + // requests anyway (they use vendor-specific control transfers), + // so we send this best-effort and explicitly clear any pending + // exception before continuing. + let mut lc = [0u8; 7]; + lc[0..4].copy_from_slice(&baud_rate.to_le_bytes()); + lc[6] = 8; + let lc_arr = env.byte_array_from_slice(&lc).map_err(|e| format!("{e}"))?; + let _ = env.call_method( + connection, + "controlTransfer", + "(IIII[BII)I", + &[ + JValue::Int(0x21), + JValue::Int(0x20), + JValue::Int(0), + JValue::Int(0), + JValue::Object(lc_arr.into()), + JValue::Int(7), + JValue::Int(1000), + ], + ); + // Defensive: ensure any Java exception from the optional CDC call + // is cleared so the subsequent global-ref allocations don't trip + // CheckJNI's "pending exception" abort. + if env.exception_check().unwrap_or(false) { + let _ = env.exception_clear(); + } + + let conn_ref = env.new_global_ref(connection).map_err(|e| format!("{e}"))?; + let ep_in_ref = env.new_global_ref(ep_in).map_err(|e| format!("{e}"))?; + let ep_out_ref = env.new_global_ref(ep_out).map_err(|e| format!("{e}"))?; + + let connected = Arc::new(AtomicBool::new(true)); + let (write_tx, mut write_rx) = mpsc::channel::>(64); + let (read_tx, read_rx) = mpsc::channel::>(64); + + let cw = connected.clone(); + let vm = match JAVA_VM.get() { + Some(v) => v.clone(), + None => return Err("JavaVM not initialized for USB write loop".into()), + }; + let cr_w = conn_ref.clone(); + let ep_w = ep_out_ref.clone(); + tokio::task::spawn_blocking(move || { + let rt = tokio::runtime::Handle::current(); + while cw.load(Ordering::Relaxed) { + match rt.block_on(write_rx.recv()) { + Some(data) => { + if let Ok(env2) = vm.attach_current_thread() { + let buf = env2 + .byte_array_from_slice(&data) + .expect("JNI byte_array_from_slice failed (OOM in JVM heap)"); + let _ = env2.call_method( + cr_w.as_obj(), + "bulkTransfer", + "(Landroid/hardware/usb/UsbEndpoint;[BII)I", + &[ + JValue::Object(ep_w.as_obj()), + JValue::Object(buf.into()), + JValue::Int(data.len() as i32), + JValue::Int(1000), + ], + ); + } + } + None => break, + } + } + }); + + let cr = connected.clone(); + let vm2 = match JAVA_VM.get() { + Some(v) => v.clone(), + None => return Err("JavaVM not initialized for USB read loop".into()), + }; + tokio::task::spawn_blocking(move || { + loop { + if !cr.load(Ordering::Relaxed) { + break; + } + if let Ok(env2) = vm2.attach_current_thread() { + let buf = env2 + .new_byte_array(1024) + .expect("JNI new_byte_array failed (OOM in JVM heap)"); + match env2.call_method( + conn_ref.as_obj(), + "bulkTransfer", + "(Landroid/hardware/usb/UsbEndpoint;[BII)I", + &[ + JValue::Object(ep_in_ref.as_obj()), + JValue::Object(buf.into()), + JValue::Int(1024), + JValue::Int(100), + ], + ) { + Ok(val) => { + let n = val.i().unwrap_or(-1); + if n > 0 { + if let Ok(bytes) = env2.convert_byte_array(buf) { + if read_tx + .blocking_send(bytes[..n as usize].to_vec()) + .is_err() + { + break; + } + } + } + } + Err(_) => { + cr.store(false, Ordering::Relaxed); + break; + } + } + } + } + }); + + Ok((write_tx, read_rx, connected)) + }) + }) + .await + .map_err(|e| InterfaceError::SendFailed(format!("{e}")))? + .map_err(|e| InterfaceError::SendFailed(e)) +} + +/// Same shape as the serial/BLE RNode interfaces, but over Android USB. +pub async fn spawn_android_usb_rnode_interface( + config: AndroidUsbConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let (raw_write_tx, mut raw_read_rx, connected) = + open_usb_serial(&config.device_name, config.baud_rate).await?; + + let name = config.name.clone(); + + // Radio stays disabled until we push an init sequence, so do it before + // handing the write channel to the transport-facing task. + let mut rnode_cfg = rnode::RNodeConfig::new(&config.name, &config.device_name); + rnode_cfg.baud_rate = config.baud_rate; + rnode_cfg.frequency = config.frequency; + rnode_cfg.bandwidth = config.bandwidth; + rnode_cfg.spreading_factor = config.spreading_factor; + rnode_cfg.coding_rate = config.coding_rate; + rnode_cfg.tx_power = config.tx_power; + rnode_cfg.mode = config.mode; + let init_bytes = rnode::build_init_sequence(&rnode_cfg); + if raw_write_tx.send(init_bytes).await.is_err() { + return Err(InterfaceError::SendFailed( + "Android USB writer closed before RNode init could be sent".into(), + )); + } + + let shared_txb = Arc::new(AtomicU64::new(0)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + + let (tx, mut app_rx) = mpsc::channel::(64); + + let txb = shared_txb.clone(); + let wtx = raw_write_tx.clone(); + let write_name = name.clone(); + tokio::spawn(async move { + while let Some(payload) = app_rx.recv().await { + let frame = kiss::frame(&payload); + txb.fetch_add(frame.len() as u64, Ordering::Relaxed); + if wtx.send(frame).await.is_err() { + tracing::warn!(name = %write_name, "USB write channel closed"); + break; + } + } + }); + + // Any RSSI/SNR from a preceding CMD_STAT_* frame attaches to the next + // inbound data packet; both reset after use. + let read_name = name.clone(); + let rxb = shared_rxb.clone(); + let online = connected.clone(); + let read_task = tokio::spawn(async move { + let mut deframer = kiss::KissDeframer::new(); + let mut last_rssi: Option = None; + let mut last_snr: Option = None; + while let Some(bytes) = raw_read_rx.recv().await { + if bytes.is_empty() { + continue; + } + // Count only real LoRa data payloads, not KISS framing or + // control responses (DETECT_RESP, CMD_STAT_*, CMD_FW_VERSION, + // etc.). Mirrors ble_rnode.rs so UI RX counters don't tick up + // while the radio is idle. + for (cmd, frame) in deframer.feed(&bytes) { + match rnode::process_rnode_response(cmd, &frame, id, &mut last_rssi, &mut last_snr) + { + rnode::RNodeResponse::Packet(msg) => { + rxb.fetch_add(frame.len() as u64, Ordering::Relaxed); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(name = %read_name, "transport channel closed"); + online.store(false, Ordering::SeqCst); + return; + } + } + rnode::RNodeResponse::Ready(_) | rnode::RNodeResponse::None => {} + } + } + } + tracing::info!(name = %read_name, "Android USB read task exiting (channel closed)"); + online.store(false, Ordering::SeqCst); + }); + + Ok(InterfaceHandle { + id, + name, + mode: config.mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: true, + repeat: false, + }, + bitrate: BAUD_RATE as u64, + mtu: 500, + online: connected, + txb: Some(shared_txb), + rxb: Some(shared_rxb), + tx, + read_task, + }) +} + +/// Push an already-KISS-framed control frame through the raw USB writer, +/// bypassing the transport CMD_DATA wrapper. The canonical caller is the +/// BLE→serial handoff, which sends `[FEND, CMD_BT_CTRL, 0x00, FEND]` to turn +/// off the RNode's BT radio before the USB link takes over. +pub async fn send_raw_frame( + writer: &mpsc::Sender>, + frame: Vec, +) -> Result<(), InterfaceError> { + writer + .send(frame) + .await + .map_err(|_| InterfaceError::SendFailed("USB raw writer closed".into())) +} diff --git a/crates/rns-interface/src/auto.rs b/crates/rns-interface/src/auto.rs new file mode 100644 index 0000000..dd541dd --- /dev/null +++ b/crates/rns-interface/src/auto.rs @@ -0,0 +1,1601 @@ +//! Automatic peer discovery over IPv6 link-local multicast. +//! +//! 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::net::{Ipv6Addr, SocketAddr, SocketAddrV6}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::time::Instant; + +use bytes::Bytes; +use tokio::net::UdpSocket; +use tokio::sync::{Mutex, broadcast, mpsc}; + +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const DISCOVERY_PORT: u16 = 29716; +pub const DATA_PORT: u16 = 42671; +pub const BEACON_INTERVAL: f64 = 1.6; +/// Background beacon — slow enough to save battery, still inside expiry window. +pub const BEACON_INTERVAL_BG: f64 = 8.0; +pub const PEER_EXPIRY: f64 = 22.0; +pub const HW_MTU: u32 = 1196; +pub const FIXED_MTU: bool = true; +pub const DEFAULT_GROUP_ID: &str = "reticulum"; +pub const UNICAST_DISCOVERY_PORT: u16 = DISCOVERY_PORT + 1; +pub const REVERSE_PEERING_INTERVAL: f64 = BEACON_INTERVAL * 3.25; +pub const PEER_JOB_INTERVAL: f64 = 4.0; +pub const MCAST_ECHO_TIMEOUT: f64 = 6.5; +pub const MULTI_IF_DEQUE_LEN: usize = 48; +pub const MULTI_IF_DEQUE_TTL: f64 = 0.75; + +// Per-platform ignores: loopback, Apple AWDL, cellular RIL, VPN tunnels. + +#[cfg(target_os = "macos")] +const IGNORED_IFACES: &[&str] = &["awdl0", "llw0", "lo0", "en5"]; + +#[cfg(target_os = "linux")] +const IGNORED_IFACES: &[&str] = &["lo"]; + +#[cfg(target_os = "android")] +const IGNORED_IFACES: &[&str] = &[ + "lo", + "dummy0", + "rmnet_data0", + "rmnet_data1", + "rmnet_data2", + "rmnet_data3", + "rmnet_data4", + "rmnet_data5", + "rmnet_data6", + "rmnet_data7", + "rmnet_ipa0", + "r_rmnet_data0", + "v4-rmnet_data0", +]; + +#[cfg(target_os = "ios")] +const IGNORED_IFACES: &[&str] = &[ + "lo0", "awdl0", "llw0", "ap1", "ipsec0", "utun0", "utun1", "utun2", "utun3", "pdp_ip0", + "pdp_ip1", "pdp_ip2", "pdp_ip3", +]; + +#[cfg(not(any( + target_os = "macos", + target_os = "linux", + target_os = "android", + target_os = "ios" +)))] +const IGNORED_IFACES: &[&str] = &["lo", "lo0"]; + +/// IPv6 multicast scope (RFC 4291 §2.7) — lower nibble of `ff_S:` byte. +/// `Link` stays on the LAN; `Site`+ require routed multicast configuration. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DiscoveryScope { + Link, + Admin, + Site, + Organisation, + Global, +} + +impl DiscoveryScope { + pub const fn as_hex_nibble(self) -> u8 { + match self { + Self::Link => 0x2, + Self::Admin => 0x4, + Self::Site => 0x5, + Self::Organisation => 0x8, + Self::Global => 0xe, + } + } +} + +impl std::str::FromStr for DiscoveryScope { + type Err = String; + fn from_str(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "link" => Ok(Self::Link), + "admin" => Ok(Self::Admin), + "site" => Ok(Self::Site), + "organisation" | "organization" => Ok(Self::Organisation), + "global" => Ok(Self::Global), + other => Err(format!("unknown discovery scope: {other}")), + } + } +} + +impl std::fmt::Display for DiscoveryScope { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Link => "link", + Self::Admin => "admin", + Self::Site => "site", + Self::Organisation => "organisation", + Self::Global => "global", + }) + } +} + +/// IPv6 multicast transient/permanent flag (RFC 4291 §2.7) — upper nibble +/// of `ff_T_:`. Default is `Temporary`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum McastAddrType { + Temporary, + Permanent, +} + +impl McastAddrType { + pub const fn as_hex_nibble(self) -> u8 { + match self { + Self::Temporary => 0x1, + Self::Permanent => 0x0, + } + } +} + +impl std::str::FromStr for McastAddrType { + type Err = String; + fn from_str(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "temporary" | "temp" => Ok(Self::Temporary), + "permanent" | "perm" => Ok(Self::Permanent), + other => Err(format!("unknown multicast address type: {other}")), + } + } +} + +impl std::fmt::Display for McastAddrType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Temporary => "temporary", + Self::Permanent => "permanent", + }) + } +} + +/// Async events from `spawn_auto_interface`; forwarded to Tauri broadcasts. +#[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. + JoinFailed { + interface_name: String, + ifname: String, + reason: String, + }, + /// Carrier state changed — multicast echoes started or stopped arriving + /// on `ifname` within `MCAST_ECHO_TIMEOUT`. `ok=false` is the trip-wire + /// for Windows Public-profile firewall block, bridged-AP reboot, or + /// general IPv6 multicast suppression. `reason` is human-readable. + CarrierState { + interface_name: String, + ifname: String, + ok: bool, + reason: String, + }, +} + +static AUTO_EVENT_TX: OnceLock> = OnceLock::new(); + +/// Subscribe to `AutoInterfaceEvent`s emitted by any AutoInterface in this +/// process. Channel is lazy-created; lagged subscribers see `RecvError::Lagged`. +pub fn subscribe_auto_events() -> broadcast::Receiver { + AUTO_EVENT_TX + .get_or_init(|| { + let (tx, _rx) = broadcast::channel(64); + tx + }) + .subscribe() +} + +fn dispatch_auto_event(event: AutoInterfaceEvent) { + if let Some(tx) = AUTO_EVENT_TX.get() { + // Ignore "no subscribers" errors; events are best-effort and callers + // may not have started their relay task yet. + let _ = tx.send(event); + } +} + +#[derive(Debug, Clone)] +pub struct AutoInterfaceConfig { + pub name: String, + pub group_id: String, + pub discovery_scope: DiscoveryScope, + pub discovery_port: u16, + pub data_port: u16, + pub multicast_address_type: McastAddrType, + /// Whitelist of NIC names. `None` = all (minus IGNORED_IFACES + ignored_devices). + pub devices: Option>, + /// Additional NIC names to skip on top of the platform default IGNORED_IFACES. + pub ignored_devices: Vec, + /// Bitrate override in bits per second. `None` = default 10 Mbps guess. + pub configured_bitrate: Option, + pub mode: InterfaceMode, +} + +impl Default for AutoInterfaceConfig { + fn default() -> Self { + Self { + name: "AutoInterface".to_string(), + group_id: DEFAULT_GROUP_ID.to_string(), + discovery_scope: DiscoveryScope::Link, + discovery_port: DISCOVERY_PORT, + data_port: DATA_PORT, + multicast_address_type: McastAddrType::Temporary, + devices: None, + ignored_devices: Vec::new(), + configured_bitrate: None, + mode: InterfaceMode::Full, + } + } +} + +#[derive(Debug, Clone)] +struct Peer { + addr: SocketAddrV6, + last_seen: Instant, + last_reverse: Instant, +} + +type PeerTable = Arc>>; + +#[derive(Debug, Clone)] +struct DeduplicateEntry { + hash: [u8; 32], + timestamp: Instant, +} + +/// Dedupes packets seen on multiple NICs at once (e.g. WLAN + wired). +#[derive(Debug, Clone)] +pub struct MultiIfDedup { + deque: VecDeque, + max_len: usize, + ttl_secs: f64, +} + +impl MultiIfDedup { + pub fn new() -> Self { + Self { + deque: VecDeque::with_capacity(MULTI_IF_DEQUE_LEN), + max_len: MULTI_IF_DEQUE_LEN, + ttl_secs: MULTI_IF_DEQUE_TTL, + } + } + + /// Record the packet and return whether it was already seen within TTL. + pub fn is_duplicate(&mut self, data: &[u8]) -> bool { + let hash = rns_crypto::sha::sha256(data); + let now = Instant::now(); + + while let Some(front) = self.deque.front() { + if now.duration_since(front.timestamp).as_secs_f64() > self.ttl_secs { + self.deque.pop_front(); + } else { + break; + } + } + + for entry in &self.deque { + if entry.hash == hash { + return true; + } + } + + if self.deque.len() >= self.max_len { + self.deque.pop_front(); + } + self.deque.push_back(DeduplicateEntry { + hash, + timestamp: now, + }); + + false + } +} + +impl Default for MultiIfDedup { + fn default() -> Self { + Self::new() + } +} + +/// Verify a beacon against `SHA-256(group_id + peer_addr_string)`. +pub fn verify_beacon(beacon: &[u8], group_id: &str, peer_addr: &Ipv6Addr) -> bool { + if beacon.len() < 32 { + return false; + } + let expected = make_beacon(group_id, peer_addr); + beacon[..32] == expected[..] +} + +#[cfg(any(target_os = "macos", test))] +fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr { + if (addr.segments()[0] & 0xffc0) != 0xfe80 { + return addr; + } + let mut segments = addr.segments(); + segments[1] = 0; + Ipv6Addr::new( + segments[0], + segments[1], + segments[2], + segments[3], + segments[4], + segments[5], + segments[6], + segments[7], + ) +} + +/// Derive `ff_T_S_:0:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX` from address-type nibble, +/// scope nibble, and bytes 2..14 of `SHA-256(group_id)`. +pub fn derive_multicast_address( + group_id: &str, + scope: DiscoveryScope, + addr_type: McastAddrType, +) -> Ipv6Addr { + let hash = rns_crypto::sha::sha256(group_id.as_bytes()); + let high = + 0xff00u16 | ((addr_type.as_hex_nibble() as u16) << 4) | (scope.as_hex_nibble() as u16); + Ipv6Addr::new( + high, + 0, + u16::from_be_bytes([hash[2], hash[3]]), + u16::from_be_bytes([hash[4], hash[5]]), + u16::from_be_bytes([hash[6], hash[7]]), + u16::from_be_bytes([hash[8], hash[9]]), + u16::from_be_bytes([hash[10], hash[11]]), + u16::from_be_bytes([hash[12], hash[13]]), + ) +} + +/// `Link` scope + `Temporary` address type (Python's defaults). +pub fn multicast_group_for(group_id: &str) -> Ipv6Addr { + derive_multicast_address(group_id, DiscoveryScope::Link, McastAddrType::Temporary) +} + +/// `SHA-256(group_id || link_local_addr_string)`, the beacon payload. +fn make_beacon(group_id: &str, link_local: &Ipv6Addr) -> [u8; 32] { + let mut input = group_id.as_bytes().to_vec(); + input.extend_from_slice(link_local.to_string().as_bytes()); + rns_crypto::sha::sha256(&input) +} + +/// One enumerated host NIC, returned by [`list_network_interfaces`]. +#[derive(Debug, Clone, serde::Serialize)] +pub struct NetworkInterfaceInfo { + pub name: String, + pub addr_v4: Option, + pub addr_v6_link_local: Option, + pub is_up: bool, + pub is_loopback: bool, +} + +/// Enumerate all host NICs (including loopback / ignored). Callers filter on top. +pub fn list_network_interfaces() -> Result, String> { + use std::collections::BTreeMap; + + let mut by_name: BTreeMap = BTreeMap::new(); + let ifaces = + if_addrs::get_if_addrs().map_err(|e| format!("if_addrs::get_if_addrs() failed: {e}"))?; + for iface in ifaces { + let entry = by_name + .entry(iface.name.clone()) + .or_insert_with(|| NetworkInterfaceInfo { + name: iface.name.clone(), + addr_v4: None, + addr_v6_link_local: None, + is_up: false, + is_loopback: iface.is_loopback(), + }); + entry.is_loopback = entry.is_loopback || iface.is_loopback(); + match iface.addr.ip() { + std::net::IpAddr::V4(v4) => { + if entry.addr_v4.is_none() { + entry.addr_v4 = Some(v4.to_string()); + } + entry.is_up = true; + } + std::net::IpAddr::V6(v6) => { + // fe80::/10 — link-local prefix used by AutoInterface discovery. + if (v6.segments()[0] & 0xffc0) == 0xfe80 && entry.addr_v6_link_local.is_none() { + entry.addr_v6_link_local = Some(v6.to_string()); + } + entry.is_up = true; + } + } + } + + #[cfg(target_os = "macos")] + { + match darwin_link_local_addrs(None, &[], false) { + Ok(addrs) => { + for (name, addr, _) in addrs { + let entry = + by_name + .entry(name.clone()) + .or_insert_with(|| NetworkInterfaceInfo { + name, + addr_v4: None, + addr_v6_link_local: None, + is_up: true, + is_loopback: false, + }); + entry.addr_v6_link_local = Some(addr.to_string()); + entry.is_up = true; + } + } + Err(e) => tracing::debug!(error = %e, "Darwin getifaddrs link-local list failed"), + } + } + + Ok(by_name.into_values().collect()) +} + +fn iface_passes_filters( + iface_name: &str, + devices: Option<&[String]>, + ignored_devices: &[String], +) -> bool { + if IGNORED_IFACES.contains(&iface_name) { + return false; + } + if ignored_devices.iter().any(|n| n == iface_name) { + return false; + } + if let Some(allowed) = devices + && !allowed.iter().any(|n| n == iface_name) + { + return false; + } + true +} + +/// Enumerate link-local IPv6 addresses, applying device/ignore filters. +/// Drops addresses with unresolvable scope id — `scope_id = 0` silently +/// routes via the default NIC, which is wrong on multi-homed hosts. +fn get_link_local_addrs( + devices: Option<&[String]>, + ignored_devices: &[String], +) -> Vec<(String, Ipv6Addr, u32)> { + // Android's libc getifaddrs() hides IPv6 link-local from app context; + // must use Java NetworkInterface.getNetworkInterfaces() via JNI. + #[cfg(target_os = "android")] + { + match get_link_local_addrs_android(devices, ignored_devices) { + Ok(v) if !v.is_empty() => { + tracing::info!(count = v.len(), "Android JNI link-local enumerate"); + return v; + } + Ok(_) => { + tracing::warn!( + "Android JNI link-local enumerate returned 0 — falling back to if_addrs" + ); + } + Err(e) => { + tracing::warn!(error = %e, "Android JNI link-local enumerate failed"); + } + } + } + + let mut result = Vec::new(); + match if_addrs::get_if_addrs() { + Ok(ifaces) => { + tracing::debug!(count = ifaces.len(), "if_addrs enumerated interfaces"); + for iface in ifaces { + tracing::debug!(name = %iface.name, addr = ?iface.addr.ip(), "if_addrs entry"); + if !iface_passes_filters(&iface.name, devices, ignored_devices) { + continue; + } + if let std::net::IpAddr::V6(addr) = iface.addr.ip() + && (addr.segments()[0] & 0xffc0) == 0xfe80 + { + let scope_id = iface_name_to_scope_id(&iface.name); + if scope_id == 0 { + tracing::warn!( + iface = %iface.name, + addr = %addr, + "skipping link-local: could not resolve scope id (would send on wrong NIC)" + ); + continue; + } + result.push((iface.name.clone(), addr, scope_id)); + } + } + } + Err(e) => { + tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed"); + } + } + + #[cfg(target_os = "macos")] + if result.is_empty() { + match darwin_link_local_addrs(devices, ignored_devices, true) { + Ok(addrs) if !addrs.is_empty() => { + tracing::debug!( + count = addrs.len(), + "Darwin getifaddrs link-local enumerate" + ); + return addrs; + } + Ok(_) => {} + Err(e) => tracing::warn!(error = %e, "Darwin getifaddrs link-local enumerate failed"), + } + } + + result +} + +#[cfg(target_os = "macos")] +fn darwin_link_local_addrs( + devices: Option<&[String]>, + ignored_devices: &[String], + apply_filters: bool, +) -> Result, String> { + use std::ffi::CStr; + use std::ptr; + + let mut ifap: *mut libc::ifaddrs = ptr::null_mut(); + // SAFETY: getifaddrs initialises `ifap` on success; the linked list is + // released with freeifaddrs before return. + if unsafe { libc::getifaddrs(&mut ifap) } != 0 { + return Err(std::io::Error::last_os_error().to_string()); + } + + struct IfAddrsGuard(*mut libc::ifaddrs); + impl Drop for IfAddrsGuard { + fn drop(&mut self) { + // SAFETY: pointer came from successful getifaddrs and is released once. + unsafe { libc::freeifaddrs(self.0) }; + } + } + let _guard = IfAddrsGuard(ifap); + + let mut result = Vec::new(); + let mut cursor = ifap; + while !cursor.is_null() { + // SAFETY: cursor walks the null-terminated getifaddrs list. + let ifa = unsafe { &*cursor }; + cursor = ifa.ifa_next; + + if ifa.ifa_addr.is_null() || ifa.ifa_name.is_null() { + continue; + } + // SAFETY: getifaddrs provides a nul-terminated interface name. + let name = unsafe { CStr::from_ptr(ifa.ifa_name) } + .to_string_lossy() + .into_owned(); + if apply_filters && !iface_passes_filters(&name, devices, ignored_devices) { + continue; + } + if ifa.ifa_flags & libc::IFF_UP as u32 == 0 { + continue; + } + let explicitly_allowed = devices.is_some_and(|allowed| allowed.iter().any(|n| n == &name)); + if apply_filters && !explicitly_allowed && ifa.ifa_flags & libc::IFF_POINTOPOINT as u32 != 0 + { + tracing::debug!(iface = %name, "skipping Darwin point-to-point link-local"); + continue; + } + // SAFETY: ifa_addr is non-null and points to a sockaddr for this entry. + let family = unsafe { (*ifa.ifa_addr).sa_family as i32 }; + if family != libc::AF_INET6 { + continue; + } + + // SAFETY: family is AF_INET6, so sockaddr_in6 layout is valid. + let sin6 = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in6) }; + let addr = normalize_link_local_addr(Ipv6Addr::from(sin6.sin6_addr.s6_addr)); + if (addr.segments()[0] & 0xffc0) != 0xfe80 { + continue; + } + + let scope_id = if sin6.sin6_scope_id != 0 { + sin6.sin6_scope_id + } else { + iface_name_to_scope_id(&name) + }; + if scope_id == 0 { + tracing::warn!( + iface = %name, + addr = %addr, + "skipping Darwin link-local: could not resolve scope id" + ); + continue; + } + if result.iter().any(|(existing, _, _)| existing == &name) { + continue; + } + tracing::debug!(iface = %name, addr = %addr, scope_id, "Darwin link-local found"); + result.push((name, addr, scope_id)); + } + + Ok(result) +} + +#[cfg(target_os = "android")] +fn get_link_local_addrs_android( + devices: Option<&[String]>, + ignored_devices: &[String], +) -> Result, String> { + use jni::objects::JObject; + + let vm = crate::android_usb::java_vm().ok_or("JavaVM not initialized")?; + let env = vm + .attach_current_thread() + .map_err(|e| format!("attach_current_thread: {e}"))?; + + let ni_class = env + .find_class("java/net/NetworkInterface") + .map_err(|e| format!("NetworkInterface class: {e}"))?; + let inet6_class = env + .find_class("java/net/Inet6Address") + .map_err(|e| format!("Inet6Address class: {e}"))?; + + let ifaces_enum = env + .call_static_method( + ni_class, + "getNetworkInterfaces", + "()Ljava/util/Enumeration;", + &[], + ) + .map_err(|e| format!("getNetworkInterfaces: {e}"))? + .l() + .map_err(|e| format!("getNetworkInterfaces obj: {e}"))?; + if ifaces_enum.is_null() { + return Err("getNetworkInterfaces returned null".into()); + } + + let mut result: Vec<(String, Ipv6Addr, u32)> = Vec::new(); + + while env + .call_method(ifaces_enum, "hasMoreElements", "()Z", &[]) + .map_err(|e| format!("hasMoreElements: {e}"))? + .z() + .map_err(|e| format!("hasMoreElements bool: {e}"))? + { + let iface_obj: JObject = env + .call_method(ifaces_enum, "nextElement", "()Ljava/lang/Object;", &[]) + .map_err(|e| format!("nextElement (iface): {e}"))? + .l() + .map_err(|e| format!("nextElement iface obj: {e}"))?; + if iface_obj.is_null() { + continue; + } + + let is_up = env + .call_method(iface_obj, "isUp", "()Z", &[]) + .map_err(|e| format!("isUp: {e}"))? + .z() + .map_err(|e| format!("isUp bool: {e}"))?; + if !is_up { + continue; + } + + let name_obj: JObject = env + .call_method(iface_obj, "getName", "()Ljava/lang/String;", &[]) + .map_err(|e| format!("getName: {e}"))? + .l() + .map_err(|e| format!("getName obj: {e}"))?; + let name: String = if name_obj.is_null() { + String::new() + } else { + env.get_string(name_obj.into()) + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_default() + }; + if !iface_passes_filters(&name, devices, ignored_devices) { + continue; + } + + let scope_id = env + .call_method(iface_obj, "getIndex", "()I", &[]) + .map_err(|e| format!("getIndex: {e}"))? + .i() + .map_err(|e| format!("getIndex int: {e}"))? as u32; + if scope_id == 0 { + tracing::warn!( + iface = %name, + "skipping JNI link-local: getIndex returned 0 (interface may have just gone down)" + ); + continue; + } + + let addrs_enum: JObject = env + .call_method( + iface_obj, + "getInetAddresses", + "()Ljava/util/Enumeration;", + &[], + ) + .map_err(|e| format!("getInetAddresses: {e}"))? + .l() + .map_err(|e| format!("getInetAddresses obj: {e}"))?; + if addrs_enum.is_null() { + continue; + } + + while env + .call_method(addrs_enum, "hasMoreElements", "()Z", &[]) + .map_err(|e| format!("addr hasMoreElements: {e}"))? + .z() + .map_err(|e| format!("addr hasMoreElements bool: {e}"))? + { + let addr_obj: JObject = env + .call_method(addrs_enum, "nextElement", "()Ljava/lang/Object;", &[]) + .map_err(|e| format!("nextElement (addr): {e}"))? + .l() + .map_err(|e| format!("nextElement addr obj: {e}"))?; + if addr_obj.is_null() { + continue; + } + + let is_v6 = env + .is_instance_of(addr_obj, inet6_class) + .map_err(|e| format!("is_instance_of Inet6Address: {e}"))?; + if !is_v6 { + continue; + } + + let is_ll = env + .call_method(addr_obj, "isLinkLocalAddress", "()Z", &[]) + .map_err(|e| format!("isLinkLocalAddress: {e}"))? + .z() + .map_err(|e| format!("isLinkLocalAddress bool: {e}"))?; + if !is_ll { + continue; + } + + let raw_obj: JObject = env + .call_method(addr_obj, "getAddress", "()[B", &[]) + .map_err(|e| format!("getAddress: {e}"))? + .l() + .map_err(|e| format!("getAddress obj: {e}"))?; + if raw_obj.is_null() { + continue; + } + let raw: Vec = env + .convert_byte_array(raw_obj.into_inner()) + .unwrap_or_default(); + if raw.len() != 16 { + continue; + } + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&raw); + let v6 = Ipv6Addr::from(bytes); + tracing::info!(iface = %name, addr = %v6, scope_id, "JNI link-local found"); + result.push((name.clone(), v6, scope_id)); + } + } + + Ok(result) +} + +/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`. +/// Returns 0 if the lookup fails; callers fall back to OS auto-selection. +#[cfg(any(unix, windows))] +fn iface_name_to_scope_id(name: &str) -> u32 { + use std::ffi::CString; + if let Ok(cname) = CString::new(name) { + // SAFETY: if_nametoindex takes a NUL-terminated C string and returns + // an index or 0 on error, with no ownership implications. + unsafe { libc_if_nametoindex(cname.as_ptr()) } + } else { + 0 + } +} + +#[cfg(unix)] +unsafe extern "C" { + #[link_name = "if_nametoindex"] + fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32; +} + +#[cfg(windows)] +#[link(name = "iphlpapi")] +unsafe extern "C" { + #[link_name = "if_nametoindex"] + fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32; +} + +#[cfg(not(any(unix, windows)))] +fn iface_name_to_scope_id(_name: &str) -> u32 { + 0 +} + +/// Bind UDP/IPv6 with REUSEADDR/REUSEPORT so multicast peers can share the port. +fn bind_reusable_udp_v6(port: u16) -> std::io::Result { + bind_one(port) +} + +fn bind_one(port: u16) -> std::io::Result { + use socket2::{Domain, Protocol, Socket, Type}; + let sock = Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP))?; + if let Err(e) = sock.set_reuse_address(true) { + tracing::warn!(port, error = %e, "SO_REUSEADDR failed"); + } + #[cfg(unix)] + if let Err(e) = sock.set_reuse_port(true) { + tracing::warn!(port, error = %e, "SO_REUSEPORT failed"); + } + // IPv6-only — link-local + scope_ids assume v6 semantics. + if let Err(e) = sock.set_only_v6(true) { + tracing::warn!(port, error = %e, "IPV6_V6ONLY failed"); + } + sock.set_nonblocking(true)?; + let addr: SocketAddr = SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, port, 0, 0).into(); + sock.bind(&addr.into())?; + UdpSocket::from_std(sock.into()) +} + +/// Diagnostic: probe alternate ports to localize bind failures. +#[cfg(target_os = "android")] +fn probe_alternate_ports(base: u16) { + let candidates: [u16; 4] = [base.saturating_add(1), base.saturating_add(2), 50000, 0]; + for p in candidates { + match bind_one(p) { + Ok(s) => { + let local = s.local_addr(); + tracing::info!(probe_port = p, ?local, "probe bind succeeded"); + drop(s); + } + Err(e) => { + tracing::warn!(probe_port = p, error = %e, "probe bind failed"); + } + } + } +} + +fn hex32(bytes: &[u8]) -> String { + let take = bytes.len().min(32); + let mut s = String::with_capacity(take * 2); + for b in &bytes[..take] { + s.push_str(&format!("{:02x}", b)); + } + s +} + +fn hex_prefix(bytes: &[u8], n: usize) -> String { + let take = bytes.len().min(n); + let mut s = String::with_capacity(take * 2); + for b in &bytes[..take] { + s.push_str(&format!("{:02x}", b)); + } + s +} + +/// Spawn the auto-discovery interface. +pub async fn spawn_auto_interface( + config: AutoInterfaceConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, + is_foreground: Arc, +) -> Result { + let mcast_group = derive_multicast_address( + &config.group_id, + config.discovery_scope, + config.multicast_address_type, + ); + let initial_link_locals = + get_link_local_addrs(config.devices.as_deref(), &config.ignored_devices); + + if initial_link_locals.is_empty() { + tracing::warn!(name = %config.name, "no link-local IPv6 addresses found"); + } + + // Adopted NIC set; jobs task refreshes on link flap. Each iteration snapshots. + let link_locals: Arc>> = + Arc::new(Mutex::new(initial_link_locals.clone())); + + // Per-NIC last-echo timestamp — updated by discovery RX when it sees our + // own beacon (multicast carrier confirmed). Read by jobs for carrier check. + let multicast_echoes: Arc>> = + Arc::new(Mutex::new(HashMap::new())); + + let data_sock = Arc::new(bind_reusable_udp_v6(config.data_port).map_err(|e| { + #[cfg(target_os = "android")] + if e.kind() == std::io::ErrorKind::AddrInUse { + probe_alternate_ports(config.data_port); + } + std::io::Error::new( + e.kind(), + format!("data socket bind ({}): {e}", config.data_port), + ) + })?); + let data_local = data_sock.local_addr()?; + tracing::info!(name = %config.name, addr = %data_local, "auto data socket bound"); + + let disc_sock = Arc::new(bind_reusable_udp_v6(config.discovery_port).map_err(|e| { + std::io::Error::new( + e.kind(), + format!("discovery socket bind ({}): {e}", config.discovery_port), + ) + })?); + tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound"); + + for (iface_name, _ll_addr, scope_id) in &initial_link_locals { + if let Err(e) = 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" + ); + } + } + } + + let online = Arc::new(AtomicBool::new(true)); + let (tx, mut rx) = mpsc::channel::(256); + let name = config.name.clone(); + let mode = config.mode; + + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + + let peers: PeerTable = Arc::new(Mutex::new(HashMap::new())); + + let online_b = online.clone(); + let group_id = config.group_id.clone(); + let disc_sock_send = disc_sock.clone(); + let beacon_link_locals = link_locals.clone(); + let disc_port = config.discovery_port; + let is_fg_beacon = is_foreground.clone(); + tokio::spawn(async move { + let mut interval = + tokio::time::interval(std::time::Duration::from_secs_f64(BEACON_INTERVAL)); + #[cfg(feature = "mobile-throttle")] + let mut was_foreground = true; + #[cfg(not(feature = "mobile-throttle"))] + let _ = &is_fg_beacon; + loop { + interval.tick().await; + if !online_b.load(Ordering::SeqCst) { + break; + } + // Slow beacons in background to save battery. + #[cfg(feature = "mobile-throttle")] + { + let is_fg = is_fg_beacon.load(Ordering::Relaxed); + if is_fg != was_foreground { + let secs = if is_fg { + BEACON_INTERVAL + } else { + BEACON_INTERVAL_BG + }; + interval = tokio::time::interval(std::time::Duration::from_secs_f64(secs)); + interval.tick().await; + was_foreground = is_fg; + } + } + // Snapshot adopted set; jobs task may have replaced it on link flap. + let snapshot = { beacon_link_locals.lock().await.clone() }; + for (_name, ll_addr, scope_id) in &snapshot { + let beacon = make_beacon(&group_id, ll_addr); + let dest = SocketAddrV6::new(mcast_group, disc_port, 0, *scope_id); + let res = disc_sock_send.send_to(&beacon, dest).await; + tracing::debug!( + iface = %_name, + ll = %ll_addr, + scope_id, + dst = %dest, + hash = %hex32(&beacon), + sent = res.is_ok(), + "auto-instr beacon TX" + ); + } + } + }); + + let peers_disc = peers.clone(); + let online_d = online.clone(); + let data_port = config.data_port; + let auth_group_id = config.group_id.clone(); + let disc_link_locals = link_locals.clone(); + let disc_echoes = multicast_echoes.clone(); + let disc_sock_recv = disc_sock.clone(); + tokio::spawn(async move { + let mut buf = [0u8; 256]; + loop { + if !online_d.load(Ordering::SeqCst) { + break; + } + match disc_sock_recv.recv_from(&mut buf).await { + Ok((n, src)) => { + if n < 32 { + tracing::debug!(src = %src, n, "auto-instr mcast RX too short"); + continue; + } + if let SocketAddr::V6(src_v6) = src { + let peer_ip = *src_v6.ip(); + // Match source LL against ours — non-empty means self-echo. + let self_iface = { + let snapshot = disc_link_locals.lock().await; + snapshot + .iter() + .find(|(_, ll, _)| *ll == peer_ip) + .map(|(name, _, _)| name.clone()) + }; + let is_self = self_iface.is_some(); + let received_hash = hex32(&buf[..32]); + let expected = make_beacon(&auth_group_id, &peer_ip); + let expected_hex = hex32(&expected); + let match_ok = expected[..] == buf[..32]; + tracing::debug!( + src = %src_v6, + scope_id = src_v6.scope_id(), + n, + is_self, + recv_hash = %received_hash, + expected_hash = %expected_hex, + match_ok, + "auto-instr mcast RX" + ); + if let Some(ifname) = self_iface { + // Self-echo: carrier confirmed; record for jobs task. + let mut echoes = disc_echoes.lock().await; + echoes.insert(ifname, Instant::now()); + continue; + } + if !match_ok { + continue; + } + let scope = src_v6.scope_id(); + let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope); + let now = Instant::now(); + let mut table = peers_disc.lock().await; + table + .entry(peer_ip) + .and_modify(|p| p.last_seen = now) + .or_insert(Peer { + addr: data_addr, + last_seen: now, + last_reverse: now, + }); + tracing::debug!(peer = %peer_ip, "auto: peer discovered/refreshed"); + } else { + tracing::debug!(src = %src, "auto-instr mcast RX non-v6 source"); + } + } + Err(e) => { + tracing::warn!(error = %e, "auto discovery recv error"); + break; + } + } + } + }); + + // Unicast + reverse-peering keeps peers reachable on one-way multicast paths. + let peers_unicast = peers.clone(); + let online_u = online.clone(); + let unicast_group_id = config.group_id.clone(); + let unicast_link_locals = link_locals.clone(); + let unicast_disc_port = config.discovery_port + 1; + if let Ok(unicast_sock) = UdpSocket::bind(SocketAddrV6::new( + Ipv6Addr::UNSPECIFIED, + unicast_disc_port, + 0, + 0, + )) + .await + { + let unicast_sock = Arc::new(unicast_sock); + + let urecv_sock = unicast_sock.clone(); + let urecv_peers = peers_unicast.clone(); + let urecv_online = online_u.clone(); + let urecv_group_id = unicast_group_id.clone(); + let urecv_link_locals = unicast_link_locals.clone(); + tokio::spawn(async move { + let mut buf = [0u8; 256]; + loop { + if !urecv_online.load(Ordering::SeqCst) { + break; + } + match urecv_sock.recv_from(&mut buf).await { + Ok((n, src)) => { + if n < 32 { + continue; + } + if let SocketAddr::V6(src_v6) = src { + let peer_ip = *src_v6.ip(); + let is_self = { + let snapshot = urecv_link_locals.lock().await; + snapshot.iter().any(|(_, ll, _)| *ll == peer_ip) + }; + if is_self { + continue; + } + if !verify_beacon(&buf[..n], &urecv_group_id, &peer_ip) { + continue; + } + let scope = src_v6.scope_id(); + let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope); + let now = Instant::now(); + let mut table = urecv_peers.lock().await; + table + .entry(peer_ip) + .and_modify(|p| p.last_seen = now) + .or_insert(Peer { + addr: data_addr, + last_seen: now, + last_reverse: now, + }); + tracing::debug!(peer = %peer_ip, "auto: unicast peer discovered"); + } + } + Err(e) => { + tracing::debug!(error = %e, "auto unicast discovery recv error"); + break; + } + } + } + }); + + let rev_peers = peers_unicast; + let rev_online = online_u; + let rev_group_id = unicast_group_id; + let rev_link_locals = unicast_link_locals; + let is_fg_rev = is_foreground.clone(); + tokio::spawn(async move { + let mut interval = + tokio::time::interval(std::time::Duration::from_secs_f64(REVERSE_PEERING_INTERVAL)); + #[cfg(feature = "mobile-throttle")] + let mut was_foreground = true; + #[cfg(not(feature = "mobile-throttle"))] + let _ = &is_fg_rev; + loop { + interval.tick().await; + if !rev_online.load(Ordering::SeqCst) { + break; + } + #[cfg(feature = "mobile-throttle")] + { + let is_fg = is_fg_rev.load(Ordering::Relaxed); + if is_fg != was_foreground { + let secs = if is_fg { + REVERSE_PEERING_INTERVAL + } else { + BEACON_INTERVAL_BG * 3.25 + }; + interval = tokio::time::interval(std::time::Duration::from_secs_f64(secs)); + interval.tick().await; + was_foreground = is_fg; + } + } + let snapshot = { rev_link_locals.lock().await.clone() }; + let now = Instant::now(); + let mut table = rev_peers.lock().await; + for (_ip, peer) in table.iter_mut() { + if now.duration_since(peer.last_reverse).as_secs_f64() + >= REVERSE_PEERING_INTERVAL + { + for (_name, ll_addr, scope_id) in &snapshot { + let beacon = make_beacon(&rev_group_id, ll_addr); + let dest = + SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id); + let _ = unicast_sock.send_to(&beacon, dest).await; + } + peer.last_reverse = now; + } + } + } + }); + } else { + tracing::debug!( + "auto: could not bind unicast discovery port {}", + unicast_disc_port + ); + } + + // Periodic jobs: NIC re-enum, peer aging, carrier detection (every PEER_JOB_INTERVAL). + // Decoupled from beacon loop to avoid multicast-join thrash on link flap. + let jobs_link_locals = link_locals.clone(); + let jobs_peers = peers.clone(); + let jobs_online = online.clone(); + let jobs_devices = config.devices.clone(); + let jobs_ignored = config.ignored_devices.clone(); + let jobs_disc_sock = disc_sock.clone(); + let jobs_mcast = mcast_group; + let jobs_echoes = multicast_echoes.clone(); + let jobs_iface_name = config.name.clone(); + tokio::spawn(async move { + let mut interval = + tokio::time::interval(std::time::Duration::from_secs_f64(PEER_JOB_INTERVAL)); + // Skip immediate first tick — initial joins happened at spawn. + interval.tick().await; + let mut carrier_state: HashMap = HashMap::new(); + loop { + interval.tick().await; + if !jobs_online.load(Ordering::SeqCst) { + break; + } + + // (1) Age out stale peers. + { + let now = Instant::now(); + let mut table = jobs_peers.lock().await; + table.retain(|_ip, peer| { + now.duration_since(peer.last_seen).as_secs_f64() < PEER_EXPIRY + }); + } + + // (2) Re-enumerate; diff against adopted set; join/leave multicast. + let new_set = get_link_local_addrs(jobs_devices.as_deref(), &jobs_ignored); + let (added, removed): (Vec<_>, Vec<_>) = { + let current = jobs_link_locals.lock().await; + let added: Vec<_> = new_set + .iter() + .filter(|(_, a, _)| !current.iter().any(|(_, ca, _)| ca == a)) + .cloned() + .collect(); + let removed: Vec<_> = current + .iter() + .filter(|(_, a, _)| !new_set.iter().any(|(_, ca, _)| ca == a)) + .cloned() + .collect(); + (added, removed) + }; + if !added.is_empty() || !removed.is_empty() { + tracing::info!( + iface = %jobs_iface_name, + added_count = added.len(), + removed_count = removed.len(), + "AutoInterface link-local set changed" + ); + } + for (ifname, addr, scope_id) in &added { + 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" + ), + Err(e) => { + if 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" + ); + } + } + } + for (ifname, _addr, scope_id) in &removed { + let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id); + jobs_echoes.lock().await.remove(ifname); + carrier_state.remove(ifname); + } + *jobs_link_locals.lock().await = new_set.clone(); + + // (3) Carrier detection: dispatch CarrierState transitions per NIC. + let now = Instant::now(); + let echoes = jobs_echoes.lock().await.clone(); + for (ifname, _, _) in &new_set { + let last = echoes.get(ifname); + let ok = match last { + Some(t) => now.duration_since(*t).as_secs_f64() <= MCAST_ECHO_TIMEOUT, + None => false, + }; + let prev = carrier_state.insert(ifname.clone(), ok); + if prev != Some(ok) { + let reason = match (prev, ok) { + (None, false) => "initial: no echo seen yet".to_string(), + (None, true) => "first multicast echo received".to_string(), + (Some(true), false) => format!( + "no multicast echo for >{:.1}s (firewall? bridge? AP reboot?)", + MCAST_ECHO_TIMEOUT + ), + (Some(false), true) => "multicast echo recovered".to_string(), + _ => unreachable!("prev != Some(ok) was true above"), + }; + let _ = last; + if !ok && prev == Some(true) { + tracing::warn!( + iface = %jobs_iface_name, + nic = %ifname, + "AutoInterface carrier lost on {ifname}: {reason}" + ); + } else if ok { + tracing::info!( + iface = %jobs_iface_name, + nic = %ifname, + "AutoInterface carrier ok on {ifname}: {reason}" + ); + } + dispatch_auto_event(AutoInterfaceEvent::CarrierState { + interface_name: jobs_iface_name.clone(), + ifname: ifname.clone(), + ok, + reason, + }); + } + } + } + }); + + let peers_write = peers.clone(); + let data_sock_w = data_sock.clone(); + let task_txb = shared_txb.clone(); + tokio::spawn(async move { + while let Some(data) = rx.recv().await { + let len = data.len(); + let prefix = hex_prefix(&data, 16); + let table = peers_write.lock().await; + let peer_count = table.len(); + for (_ip, peer) in table.iter() { + let res = data_sock_w.send_to(&data, peer.addr).await; + tracing::debug!( + dst = %peer.addr, + len, + prefix = %prefix, + peer_count, + sent = res.is_ok(), + "auto-instr data TX" + ); + if res.is_ok() { + task_txb.fetch_add(len as u64, Ordering::Relaxed); + } + } + } + }); + + let online_r = online.clone(); + let task_rxb = shared_rxb.clone(); + let dedup = Arc::new(Mutex::new(MultiIfDedup::new())); + let read_task = tokio::spawn(async move { + let mut buf = [0u8; 2048]; + loop { + match data_sock.recv_from(&mut buf).await { + Ok((n, _src)) => { + if n == 0 { + continue; + } + tracing::debug!( + src = %_src, + n, + prefix = %hex_prefix(&buf[..n], 16), + "auto-instr data RX" + ); + { + let mut dd = dedup.lock().await; + if dd.is_duplicate(&buf[..n]) { + tracing::trace!(id, "auto: dropping duplicate packet"); + continue; + } + } + task_rxb.fetch_add(n as u64, Ordering::Relaxed); + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::copy_from_slice(&buf[..n]), + interface_id: id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + break; + } + } + Err(e) => { + tracing::warn!(error = %e, "auto data recv error"); + break; + } + } + } + online_r.store(false, Ordering::SeqCst); + }); + + let bitrate = config.configured_bitrate.unwrap_or(10_000_000); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate, + mtu: HW_MTU, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_multicast_group_derivation() { + let group = multicast_group_for("reticulum"); + assert_eq!(group.segments()[0], 0xff12); + assert_eq!(group.segments()[1], 0); + assert_eq!(group.segments()[2], 0xd70b); + let group2 = multicast_group_for("reticulum"); + assert_eq!(group, group2); + let group3 = multicast_group_for("other_group"); + assert_ne!(group, group3); + // ff12:0:d70b:fb1c:16e4:5e39:485e:31e1. + assert_eq!(group.segments()[3], 0xfb1c); + assert_eq!(group.segments()[4], 0x16e4); + assert_eq!(group.segments()[5], 0x5e39); + assert_eq!(group.segments()[6], 0x485e); + assert_eq!(group.segments()[7], 0x31e1); + } + + #[test] + fn test_derive_multicast_address_all_scopes() { + // High u16 = 0xff_T_S; bytes 2-13 of SHA-256("reticulum") fill the body. + let body = [0xd70b, 0xfb1c, 0x16e4, 0x5e39, 0x485e, 0x31e1]; + + for (scope, scope_hex) in [ + (DiscoveryScope::Link, 0x2u16), + (DiscoveryScope::Admin, 0x4u16), + (DiscoveryScope::Site, 0x5u16), + (DiscoveryScope::Organisation, 0x8u16), + (DiscoveryScope::Global, 0xeu16), + ] { + for (addr_type, type_hex) in [ + (McastAddrType::Temporary, 0x1u16), + (McastAddrType::Permanent, 0x0u16), + ] { + let group = derive_multicast_address("reticulum", scope, addr_type); + let expected_high = 0xff00 | (type_hex << 4) | scope_hex; + assert_eq!( + group.segments()[0], + expected_high, + "scope {scope:?} type {addr_type:?}" + ); + assert_eq!(group.segments()[1], 0); + for (i, want) in body.iter().enumerate() { + assert_eq!(group.segments()[2 + i], *want); + } + } + } + } + + #[test] + fn test_discovery_scope_parse_roundtrip() { + use std::str::FromStr; + for s in [ + "link", + "admin", + "site", + "organisation", + "organization", + "global", + ] { + let parsed = DiscoveryScope::from_str(s).expect("parse"); + // Round-trip through Display (organization → organisation is fine). + let _back = parsed.to_string(); + } + assert!(DiscoveryScope::from_str("LINK").is_ok()); + assert!(DiscoveryScope::from_str("nonsense").is_err()); + } + + #[test] + fn test_mcast_addr_type_parse_roundtrip() { + use std::str::FromStr; + assert_eq!( + McastAddrType::from_str("temporary").unwrap(), + McastAddrType::Temporary + ); + assert_eq!( + McastAddrType::from_str("temp").unwrap(), + McastAddrType::Temporary + ); + assert_eq!( + McastAddrType::from_str("permanent").unwrap(), + McastAddrType::Permanent + ); + assert_eq!( + McastAddrType::from_str("perm").unwrap(), + McastAddrType::Permanent + ); + assert!(McastAddrType::from_str("nope").is_err()); + } + + #[test] + fn test_beacon_deterministic() { + let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); + let b1 = make_beacon("reticulum", &addr); + let b2 = make_beacon("reticulum", &addr); + assert_eq!(b1, b2); + assert_eq!(b1.len(), 32); + } + + #[test] + fn test_beacon_auth() { + let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); + let beacon = make_beacon("reticulum", &addr); + assert!(verify_beacon(&beacon, "reticulum", &addr)); + assert!(!verify_beacon(&beacon, "other_group", &addr)); + let other_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2); + assert!(!verify_beacon(&beacon, "reticulum", &other_addr)); + assert!(!verify_beacon(&beacon[..16], "reticulum", &addr)); + } + + #[test] + fn test_normalize_link_local_addr_clears_embedded_scope_segment() { + let addr = Ipv6Addr::new(0xfe80, 0x18, 0, 0, 0, 0, 0, 1); + let normalized = normalize_link_local_addr(addr); + assert_eq!(normalized, Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)); + + let global = Ipv6Addr::new(0xfddd, 0xebe4, 0, 0, 0, 0, 0, 1); + assert_eq!(normalize_link_local_addr(global), global); + } + + #[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); + } + + #[test] + fn test_multi_if_dedup() { + let mut dedup = MultiIfDedup::new(); + let data1 = b"packet one"; + let data2 = b"packet two"; + + assert!(!dedup.is_duplicate(data1)); + assert!(dedup.is_duplicate(data1)); + assert!(!dedup.is_duplicate(data2)); + } + + #[test] + fn test_dedup_max_capacity() { + let mut dedup = MultiIfDedup::new(); + for i in 0..MULTI_IF_DEQUE_LEN + 10 { + let data = format!("packet_{}", i); + assert!(!dedup.is_duplicate(data.as_bytes())); + } + assert!(dedup.deque.len() <= MULTI_IF_DEQUE_LEN); + } + + #[test] + fn test_reverse_peering_interval() { + let expected = BEACON_INTERVAL * 3.25; + assert!((REVERSE_PEERING_INTERVAL - expected).abs() < 0.001); + } +} diff --git a/crates/rns-interface/src/ax25kiss.rs b/crates/rns-interface/src/ax25kiss.rs new file mode 100644 index 0000000..e928e35 --- /dev/null +++ b/crates/rns-interface/src/ax25kiss.rs @@ -0,0 +1,680 @@ +//! AX.25-over-KISS — prepends a UI header (src/dst call+SSID) and strips on RX. + +#[cfg(feature = "serial")] +use std::sync::Arc; +#[cfg(feature = "serial")] +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +#[cfg(feature = "serial")] +use std::time::Duration; + +#[cfg(feature = "serial")] +use bytes::Bytes; +#[cfg(feature = "serial")] +use tokio::sync::mpsc; + +use crate::kiss; +use crate::traits::InterfaceMode; + +#[cfg(feature = "serial")] +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId}; +#[cfg(feature = "serial")] +use rns_transport::messages::{InboundPacket, TransportMessage}; + +/// "No layer 3 protocol". +pub const AX25_PID_NOLAYER3: u8 = 0xF0; +/// Unnumbered Information control field. +pub const AX25_CTRL_UI: u8 = 0x03; +/// 2×7 (addresses) + 1 (control) + 1 (PID). +pub const AX25_HEADER_SIZE: usize = 16; + +pub const HW_MTU: u16 = 564; + +pub const BITRATE_GUESS: u64 = 1200; + +pub const DEFAULT_DST_CALL: &[u8] = b"APZRNS"; +pub const DEFAULT_DST_SSID: u8 = 0; + +#[derive(Debug, Clone)] +pub struct AX25KISSConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + /// 3-6 uppercase ASCII. + pub src_call: String, + /// 0-15. + pub src_ssid: u8, + pub dst_call: String, + pub dst_ssid: u8, + /// ms (default 350). + pub preamble: u16, + /// ms (default 20). + pub txtail: u16, + /// CSMA persistence 0-255 (default 64). + pub persistence: u8, + /// CSMA slot time ms (default 20). + pub slottime: u16, + /// Honour CMD_READY from TNC. + pub flow_control: bool, + pub mode: InterfaceMode, +} + +impl AX25KISSConfig { + pub fn new(name: &str, port: &str, callsign: &str, ssid: u8) -> Self { + Self { + name: name.to_string(), + port: port.to_string(), + baud_rate: 9600, + src_call: callsign.to_uppercase(), + src_ssid: ssid, + dst_call: String::from_utf8_lossy(DEFAULT_DST_CALL).to_string(), + dst_ssid: DEFAULT_DST_SSID, + preamble: 350, + txtail: 20, + persistence: 64, + slottime: 20, + flow_control: false, + mode: InterfaceMode::Full, + } + } + + pub fn validate(&self) -> Result<(), String> { + if self.src_call.len() < 3 || self.src_call.len() > 6 { + return Err(format!( + "Invalid callsign '{}': must be 3-6 characters", + self.src_call + )); + } + if self.src_ssid > 15 { + return Err(format!("Invalid SSID {}: must be 0-15", self.src_ssid)); + } + Ok(()) + } +} + +/// 16-byte AX.25 UI header (AX.25 v2.2 §3.12): +/// `dst_call(6) | dst_ssid(1) | src_call(6) | src_ssid(1) | CTRL | PID`. +/// Callsign bytes left-shifted 1, space-padded to 6. SSID = `0x60 | (ssid<<1)`; +/// src SSID also sets end-of-address bit. +pub fn build_ax25_header( + dst_call: &[u8], + dst_ssid: u8, + src_call: &[u8], + src_ssid: u8, +) -> [u8; AX25_HEADER_SIZE] { + let mut header = [0u8; AX25_HEADER_SIZE]; + + for i in 0..6 { + header[i] = if i < dst_call.len() { + dst_call[i] << 1 + } else { + 0x20 + }; + } + header[6] = 0x60 | (dst_ssid << 1); + + for i in 0..6 { + header[7 + i] = if i < src_call.len() { + src_call[i] << 1 + } else { + 0x20 + }; + } + // End-of-address bit terminates the address field. + header[13] = 0x60 | (src_ssid << 1) | 0x01; + + header[14] = AX25_CTRL_UI; + header[15] = AX25_PID_NOLAYER3; + + header +} + +pub fn frame_ax25_kiss( + data: &[u8], + dst_call: &[u8], + dst_ssid: u8, + src_call: &[u8], + src_ssid: u8, +) -> Vec { + let header = build_ax25_header(dst_call, dst_ssid, src_call, src_ssid); + let mut payload = Vec::with_capacity(header.len() + data.len()); + payload.extend_from_slice(&header); + payload.extend_from_slice(data); + kiss::frame(&payload) +} + +/// Payload after the 16-byte header, or `None` if too short. +pub fn strip_ax25_header(data: &[u8]) -> Option<&[u8]> { + if data.len() > AX25_HEADER_SIZE { + Some(&data[AX25_HEADER_SIZE..]) + } else { + None + } +} + +/// preamble/txtail/slottime are ms→10ms units per KISS spec. +pub fn build_ax25_kiss_init(config: &AX25KISSConfig) -> Vec { + let mut out = Vec::new(); + + let preamble_val = (config.preamble / 10).min(255) as u8; + out.extend_from_slice(&kiss::frame_with_command( + kiss::CMD_TXDELAY, + &[preamble_val], + )); + + let txtail_val = (config.txtail / 10).min(255) as u8; + out.extend_from_slice(&kiss::frame_with_command(kiss::CMD_TXTAIL, &[txtail_val])); + + out.extend_from_slice(&kiss::frame_with_command( + kiss::CMD_P, + &[config.persistence], + )); + + let slottime_val = (config.slottime / 10).min(255) as u8; + out.extend_from_slice(&kiss::frame_with_command( + kiss::CMD_SLOTTIME, + &[slottime_val], + )); + + out.extend_from_slice(&kiss::frame_with_command(kiss::CMD_READY, &[0x01])); + + out +} + +#[cfg(feature = "serial")] +const AX25_READ_TIMEOUT_MS: u64 = 100; + +#[cfg(feature = "serial")] +const FLOW_CONTROL_TIMEOUT_SECS: u64 = 5; + +/// Parse `"CALL-SSID"` or `"CALL"`; uppercased call, SSID defaults to 0. +pub fn parse_callsign_ssid(input: &str) -> Result<(String, u8), String> { + let (call_part, ssid) = if let Some(idx) = input.rfind('-') { + let call = &input[..idx]; + let ssid_str = &input[idx + 1..]; + let ssid: u8 = ssid_str + .parse() + .map_err(|_| format!("Invalid SSID '{}': must be a number 0-15", ssid_str))?; + (call, ssid) + } else { + (input, 0u8) + }; + + let call = call_part.to_uppercase(); + + if call.len() < 3 || call.len() > 6 { + return Err(format!( + "Invalid callsign '{}': must be 3-6 characters", + call + )); + } + + if !call.bytes().all(|b| b.is_ascii_alphanumeric()) { + return Err(format!( + "Invalid callsign '{}': must be ASCII alphanumeric", + call + )); + } + + if ssid > 15 { + return Err(format!("Invalid SSID {}: must be 0-15", ssid)); + } + + Ok((call, ssid)) +} + +#[cfg(feature = "serial")] +pub async fn spawn_ax25kiss_interface( + config: AX25KISSConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + config.validate().map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("ax25kiss config: {}", e)) + })?; + + let port = serialport::new(&config.port, config.baud_rate) + .data_bits(serialport::DataBits::Eight) + .parity(serialport::Parity::None) + .stop_bits(serialport::StopBits::One) + .timeout(Duration::from_millis(AX25_READ_TIMEOUT_MS)) + .open() + .map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("ax25kiss serial open: {}", e)) + })?; + + tracing::info!( + name = %config.name, + port = %config.port, + baud = config.baud_rate, + src_call = %config.src_call, + src_ssid = config.src_ssid, + "AX.25 KISS interface opened" + ); + + let online = Arc::new(AtomicBool::new(true)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let (tx, mut rx) = mpsc::channel::(256); + let name = config.name.clone(); + let mode = config.mode; + let flow_control = config.flow_control; + + let src_call_bytes: Vec = config.src_call.as_bytes().to_vec(); + let dst_call_bytes: Vec = config.dst_call.as_bytes().to_vec(); + let src_ssid = config.src_ssid; + let dst_ssid = config.dst_ssid; + + let port_write = port + .try_clone() + .map_err(|e| crate::traits::InterfaceError::SendFailed(format!("ax25kiss clone: {}", e)))?; + + { + let mut init_port = port_write.try_clone().map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("ax25kiss init clone: {}", e)) + })?; + let init_seq = build_ax25_kiss_init(&config); + use std::io::Write; + let _ = init_port.write_all(&init_seq); + let _ = init_port.flush(); + tracing::debug!(name = %config.name, "AX.25 KISS init commands sent"); + } + + let ready = Arc::new(AtomicBool::new(true)); + + let online_w = online.clone(); + let ready_w = ready.clone(); + let txb_w = shared_txb.clone(); + tokio::spawn(async move { + let mut port_w = port_write; + while let Some(data) = rx.recv().await { + txb_w.fetch_add(data.len() as u64, Ordering::Relaxed); + + if flow_control { + let start = std::time::Instant::now(); + while !ready_w.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + if !online_w.load(Ordering::SeqCst) { + return; + } + if start.elapsed() > Duration::from_secs(FLOW_CONTROL_TIMEOUT_SECS) { + tracing::warn!("AX.25 KISS flow control timeout, unlocking"); + ready_w.store(true, Ordering::SeqCst); + break; + } + } + } + + let framed = + frame_ax25_kiss(&data, &dst_call_bytes, dst_ssid, &src_call_bytes, src_ssid); + + if flow_control { + ready_w.store(false, Ordering::SeqCst); + } + + let online_ref = online_w.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::io::Write; + port_w.write_all(&framed)?; + port_w.flush()?; + Ok::<_, std::io::Error>(port_w) + }) + .await; + match result { + Ok(Ok(p)) => { + port_w = p; + } + Ok(Err(e)) => { + tracing::warn!(error = %e, "AX.25 KISS write error"); + online_ref.store(false, Ordering::SeqCst); + break; + } + Err(e) => { + tracing::warn!(error = %e, "AX.25 KISS write task panicked"); + break; + } + } + } + }); + + let online_r = online.clone(); + let ready_r = ready; + let rxb_r = shared_rxb.clone(); + let read_task = tokio::spawn(async move { + let mut port_r = port; + let mut deframer = kiss::KissDeframer::new(); + let mut buf = [0u8; 1024]; + + loop { + if !online_r.load(Ordering::SeqCst) { + break; + } + let result = tokio::task::spawn_blocking(move || { + use std::io::Read; + match port_r.read(&mut buf) { + Ok(n) => Ok((port_r, buf, n)), + Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)), + Err(e) => Err((port_r, e)), + } + }) + .await; + + match result { + Ok(Ok((p, b, n))) => { + port_r = p; + buf = b; + if n > 0 { + rxb_r.fetch_add(n as u64, Ordering::Relaxed); + for (cmd, frame) in deframer.feed(&buf[..n]) { + match cmd { + kiss::CMD_DATA => { + let payload = match strip_ax25_header(&frame) { + Some(p) if !p.is_empty() => p.to_vec(), + _ => continue, + }; + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(payload), + interface_id: id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + kiss::CMD_READY => { + ready_r.store(true, Ordering::SeqCst); + tracing::debug!(id, "AX.25 KISS flow control: ready"); + } + _ => { + tracing::debug!(id, cmd, "ignoring KISS command"); + } + } + } + } + } + Ok(Err((_p, e))) => { + tracing::warn!(error = %e, "AX.25 KISS read error"); + online_r.store(false, Ordering::SeqCst); + return; + } + Err(e) => { + tracing::warn!(error = %e, "AX.25 KISS read task panicked"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: BITRATE_GUESS, + mtu: HW_MTU as u32, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ax25_config() { + let cfg = AX25KISSConfig::new("ax25-0", "/dev/ttyUSB0", "N0CALL", 7); + assert_eq!(cfg.src_call, "N0CALL"); + assert_eq!(cfg.src_ssid, 7); + assert_eq!(cfg.dst_call, "APZRNS"); + assert_eq!(cfg.preamble, 350); + assert!(cfg.validate().is_ok()); + } + + #[test] + fn test_ax25_config_validation() { + let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "AB", 0); + assert!(cfg.validate().is_err()); + + let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "ABCDEFG", 0); + assert!(cfg.validate().is_err()); + + let mut cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "N0CALL", 0); + cfg.src_ssid = 16; + assert!(cfg.validate().is_err()); + } + + #[test] + fn test_build_ax25_header() { + let header = build_ax25_header(b"APZRNS", 0, b"N0CALL", 7); + assert_eq!(header.len(), AX25_HEADER_SIZE); + + assert_eq!(header[0], b'A' << 1); + assert_eq!(header[6], 0x60); + assert_eq!(header[7], b'N' << 1); + assert_eq!(header[13], 0x60 | (7 << 1) | 0x01); + assert_eq!(header[14], AX25_CTRL_UI); + assert_eq!(header[15], AX25_PID_NOLAYER3); + } + + #[test] + fn test_frame_ax25_kiss_roundtrip() { + let data = b"hello ax25"; + let framed = frame_ax25_kiss(data, b"APZRNS", 0, b"N0CALL", 7); + + let mut deframer = kiss::KissDeframer::new(); + let frames = deframer.feed(&framed); + assert_eq!(frames.len(), 1); + let (cmd, payload) = &frames[0]; + assert_eq!(*cmd, kiss::CMD_DATA); + + let stripped = strip_ax25_header(payload).unwrap(); + assert_eq!(stripped, data); + } + + #[test] + fn test_strip_ax25_header_too_short() { + let short_data = [0u8; AX25_HEADER_SIZE]; + assert!(strip_ax25_header(&short_data).is_none()); + assert!(strip_ax25_header(&[]).is_none()); + } + + #[test] + fn test_ax25_kiss_init_parseable() { + let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "N0CALL", 7); + let init_seq = build_ax25_kiss_init(&cfg); + let mut deframer = kiss::KissDeframer::new(); + let frames = deframer.feed(&init_seq); + assert_eq!(frames.len(), 5); + } + + #[test] + fn test_parse_callsign_ssid_with_ssid() { + let (call, ssid) = parse_callsign_ssid("N0CALL-7").unwrap(); + assert_eq!(call, "N0CALL"); + assert_eq!(ssid, 7); + } + + #[test] + fn test_parse_callsign_ssid_without_ssid() { + let (call, ssid) = parse_callsign_ssid("N0CALL").unwrap(); + assert_eq!(call, "N0CALL"); + assert_eq!(ssid, 0); + } + + #[test] + fn test_parse_callsign_ssid_zero() { + let (call, ssid) = parse_callsign_ssid("ABC-0").unwrap(); + assert_eq!(call, "ABC"); + assert_eq!(ssid, 0); + } + + #[test] + fn test_parse_callsign_ssid_max() { + let (call, ssid) = parse_callsign_ssid("W1AW-15").unwrap(); + assert_eq!(call, "W1AW"); + assert_eq!(ssid, 15); + } + + #[test] + fn test_parse_callsign_ssid_lowercase() { + let (call, ssid) = parse_callsign_ssid("n0call-3").unwrap(); + assert_eq!(call, "N0CALL"); + assert_eq!(ssid, 3); + } + + #[test] + fn test_parse_callsign_ssid_too_short() { + assert!(parse_callsign_ssid("AB-1").is_err()); + assert!(parse_callsign_ssid("AB").is_err()); + } + + #[test] + fn test_parse_callsign_ssid_too_long() { + assert!(parse_callsign_ssid("ABCDEFG-1").is_err()); + } + + #[test] + fn test_parse_callsign_ssid_invalid_ssid() { + assert!(parse_callsign_ssid("N0CALL-16").is_err()); + assert!(parse_callsign_ssid("N0CALL-99").is_err()); + assert!(parse_callsign_ssid("N0CALL-abc").is_err()); + } + + #[test] + fn test_parse_callsign_ssid_non_ascii() { + assert!(parse_callsign_ssid("N0C@LL-1").is_err()); + } + + #[test] + fn test_callsign_shift_and_padding() { + let header = build_ax25_header(b"CQ", 0, b"ABC", 0); + + assert_eq!(header[0], b'C' << 1); + assert_eq!(header[1], b'Q' << 1); + assert_eq!(header[2], 0x20); + assert_eq!(header[3], 0x20); + assert_eq!(header[4], 0x20); + assert_eq!(header[5], 0x20); + + assert_eq!(header[7], b'A' << 1); + assert_eq!(header[8], b'B' << 1); + assert_eq!(header[9], b'C' << 1); + assert_eq!(header[10], 0x20); + assert_eq!(header[11], 0x20); + assert_eq!(header[12], 0x20); + } + + #[test] + fn test_header_ssid_encoding() { + let header = build_ax25_header(b"DST", 0, b"SRC", 0); + assert_eq!(header[6], 0x60); + assert_eq!(header[13], 0x60 | 0x01); + + let header = build_ax25_header(b"DST", 15, b"SRC", 15); + assert_eq!(header[6], 0x7E); + assert_eq!(header[13], 0x7E | 0x01); + } + + #[test] + fn test_header_full_callsign() { + let header = build_ax25_header(b"ABCDEF", 0, b"GHIJKL", 0); + assert_eq!(header[0], b'A' << 1); + assert_eq!(header[1], b'B' << 1); + assert_eq!(header[2], b'C' << 1); + assert_eq!(header[3], b'D' << 1); + assert_eq!(header[4], b'E' << 1); + assert_eq!(header[5], b'F' << 1); + assert_eq!(header[7], b'G' << 1); + assert_eq!(header[8], b'H' << 1); + assert_eq!(header[9], b'I' << 1); + assert_eq!(header[10], b'J' << 1); + assert_eq!(header[11], b'K' << 1); + assert_eq!(header[12], b'L' << 1); + } + + #[test] + fn test_ax25_kiss_init_values() { + let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "N0CALL", 0); + let init_seq = build_ax25_kiss_init(&cfg); + let mut deframer = kiss::KissDeframer::new(); + let frames = deframer.feed(&init_seq); + + assert_eq!(frames[0].0, kiss::CMD_TXDELAY); + assert_eq!(frames[0].1, &[35]); + + assert_eq!(frames[1].0, kiss::CMD_TXTAIL); + assert_eq!(frames[1].1, &[2]); + + assert_eq!(frames[2].0, kiss::CMD_P); + assert_eq!(frames[2].1, &[64]); + + assert_eq!(frames[3].0, kiss::CMD_SLOTTIME); + assert_eq!(frames[3].1, &[2]); + + assert_eq!(frames[4].0, kiss::CMD_READY); + assert_eq!(frames[4].1, &[0x01]); + } + + #[test] + fn test_strip_ax25_header_exact_payload() { + let mut data = [0u8; AX25_HEADER_SIZE + 1]; + data[AX25_HEADER_SIZE] = 0x42; + let payload = strip_ax25_header(&data).unwrap(); + assert_eq!(payload, &[0x42]); + } + + #[test] + fn test_frame_ax25_kiss_wire_vector() { + // Byte-exact wire vector for APZRNS-0 <- N0CALL-7. + let data = b"\x01\x02\x03"; + let framed = frame_ax25_kiss(data, b"APZRNS", 0, b"N0CALL", 7); + + let mut deframer = kiss::KissDeframer::new(); + let frames = deframer.feed(&framed); + assert_eq!(frames.len(), 1); + let inner = &frames[0].1; + + assert_eq!(inner[0], 0x82); + assert_eq!(inner[1], 0xA0); + assert_eq!(inner[2], 0xB4); + assert_eq!(inner[3], 0xA4); + assert_eq!(inner[4], 0x9C); + assert_eq!(inner[5], 0xA6); + assert_eq!(inner[6], 0x60); + + assert_eq!(inner[7], 0x9C); + assert_eq!(inner[8], 0x60); + assert_eq!(inner[9], 0x86); + assert_eq!(inner[10], 0x82); + assert_eq!(inner[11], 0x98); + assert_eq!(inner[12], 0x98); + assert_eq!(inner[13], 0x6F); + + assert_eq!(inner[14], AX25_CTRL_UI); + assert_eq!(inner[15], AX25_PID_NOLAYER3); + + assert_eq!(&inner[16..], data); + } + + #[test] + fn test_config_from_parsed_callsign() { + let (call, ssid) = parse_callsign_ssid("W1AW-12").unwrap(); + let cfg = AX25KISSConfig::new("ax25-0", "/dev/ttyUSB0", &call, ssid); + assert_eq!(cfg.src_call, "W1AW"); + assert_eq!(cfg.src_ssid, 12); + assert!(cfg.validate().is_ok()); + } +} diff --git a/crates/rns-interface/src/backbone.rs b/crates/rns-interface/src/backbone.rs new file mode 100644 index 0000000..1cc930d --- /dev/null +++ b/crates/rns-interface/src/backbone.rs @@ -0,0 +1,609 @@ +//! High-throughput HDLC-over-TCP backbone. Server accepts many peers +//! (each its own [`InterfaceHandle`]); client auto-reconnects. +//! Per-peer tuning: TCP keepalive + TCP_USER_TIMEOUT + NODELAY + large +//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid +//! malformed-peer memory blow-up. + +use std::net::IpAddr; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use bytes::Bytes; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::mpsc; + +use crate::hdlc; +use crate::socket_tuning::{iface_addr_for, set_keepalive_tuned, set_socket_buffers}; +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +/// 1 MiB MTU — also the SO_RCVBUF/SNDBUF target (kernel clamps). +pub const HW_MTU: u32 = 1_048_576; + +/// Listener-side bitrate guess advertised on the parent handle. +pub const BITRATE_GUESS: u64 = 1_000_000_000; + +/// Per-peer guess (100 Mbps) — drives [`crate::traits::optimise_mtu`] → 64 KiB MTU. +pub const CHILD_BITRATE_GUESS: u64 = 100_000_000; + +pub const RECONNECT_WAIT: u64 = 5; +pub const INITIAL_CONNECT_TIMEOUT: u64 = 5; + +pub const TCP_PROBE_AFTER: u32 = 5; +pub const TCP_PROBE_INTERVAL: u32 = 2; +pub const TCP_PROBES: u32 = 12; +/// Linux TCP_USER_TIMEOUT — drops stuck conns when peer goes silent without RST. +pub const TCP_USER_TIMEOUT: u32 = 24; + +const TX_CHANNEL_DEPTH: usize = 1024; + +#[derive(Debug, Clone)] +pub struct BackboneServerConfig { + pub name: String, + pub listen_ip: String, + pub listen_port: u16, + pub prefer_ipv6: bool, + pub mode: InterfaceMode, + /// Optional kernel ifname; binds to its current IP (falls back to `listen_ip`). + pub device: Option, +} + +impl BackboneServerConfig { + pub fn new(name: &str, ip: &str, port: u16) -> Self { + Self { + name: name.to_string(), + listen_ip: ip.to_string(), + listen_port: port, + prefer_ipv6: false, + mode: InterfaceMode::Full, + device: None, + } + } +} + +#[derive(Debug, Clone)] +pub struct BackboneClientConfig { + pub name: String, + pub target_host: String, + pub target_port: u16, + pub prefer_ipv6: bool, + pub connect_timeout_secs: u64, + pub max_reconnect_tries: Option, + pub mode: InterfaceMode, +} + +impl BackboneClientConfig { + pub fn new(name: &str, host: &str, port: u16) -> Self { + Self { + name: name.to_string(), + target_host: host.to_string(), + target_port: port, + prefer_ipv6: false, + connect_timeout_secs: INITIAL_CONNECT_TIMEOUT, + max_reconnect_tries: None, + mode: InterfaceMode::Full, + } + } +} + +fn keepalive_durations() -> (Duration, Duration, u32, Duration) { + ( + Duration::from_secs(TCP_PROBE_AFTER as u64), + Duration::from_secs(TCP_PROBE_INTERVAL as u64), + TCP_PROBES, + Duration::from_secs(TCP_USER_TIMEOUT as u64), + ) +} + +fn tune_stream(stream: &TcpStream) { + let _ = stream.set_nodelay(true); + let (idle, intvl, retries, user_timeout) = keepalive_durations(); + set_keepalive_tuned(stream, idle, intvl, retries, user_timeout); + set_socket_buffers(stream, HW_MTU as usize); +} + +fn child_mtu() -> u32 { + crate::traits::optimise_mtu(CHILD_BITRATE_GUESS) + .map(|m| m.min(HW_MTU)) + .unwrap_or(rns_wire::constants::MTU as u32) +} + +async fn backbone_read_loop( + mut reader: tokio::net::tcp::OwnedReadHalf, + interface_id: InterfaceId, + transport_tx: mpsc::Sender, + online: Arc, + rxb: Arc, +) { + let mut deframer = hdlc::HdlcDeframer::new(); + // Large buffer to amortise syscalls; inbound capped by HdlcDeframer::MAX_FRAME_SIZE. + let mut buf = vec![0u8; 65536]; + loop { + match reader.read(&mut buf).await { + Ok(0) => { + tracing::info!(interface_id, "backbone read: EOF"); + break; + } + Ok(n) => { + rxb.fetch_add(n as u64, Ordering::Relaxed); + for frame in deframer.feed(&buf[..n]) { + if frame.is_empty() { + continue; + } + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(interface_id, "transport channel closed"); + online.store(false, Ordering::SeqCst); + return; + } + } + } + Err(e) => { + tracing::warn!(interface_id, error = %e, "backbone read error"); + break; + } + } + } + online.store(false, Ordering::SeqCst); +} + +async fn backbone_write_loop( + mut writer: tokio::net::tcp::OwnedWriteHalf, + mut rx: mpsc::Receiver, + online: Arc, + txb: Arc, +) { + while let Some(data) = rx.recv().await { + let framed = hdlc::frame(&data); + txb.fetch_add(framed.len() as u64, Ordering::Relaxed); + if let Err(e) = writer.write_all(&framed).await { + tracing::warn!(error = %e, "backbone write error"); + break; + } + } + online.store(false, Ordering::SeqCst); +} + +/// `device` takes precedence over `listen_ip` when its lookup succeeds. +fn resolve_listen_addr(config: &BackboneServerConfig) -> String { + if let Some(name) = config.device.as_deref() { + match iface_addr_for(name, config.prefer_ipv6) { + Some(IpAddr::V4(v4)) => return v4.to_string(), + Some(IpAddr::V6(v6)) => return format!("[{}]", v6), + None => { + tracing::warn!( + device = %name, + listen_ip = %config.listen_ip, + "backbone: device lookup failed, falling back to listen_ip", + ); + } + } + } + config.listen_ip.clone() +} + +/// Resolve `host:port` preferring the configured address family. +async fn resolve_target( + host: &str, + port: u16, + prefer_ipv6: bool, +) -> std::io::Result { + let mut addrs: Vec = + tokio::net::lookup_host((host, port)).await?.collect(); + if addrs.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::AddrNotAvailable, + format!("no addresses resolved for {host}:{port}"), + )); + } + // Prefer the requested family; else first resolved. + let preferred = if prefer_ipv6 { + addrs.iter().find(|a| a.is_ipv6()).copied() + } else { + addrs.iter().find(|a| a.is_ipv4()).copied() + }; + Ok(preferred.unwrap_or_else(|| addrs.remove(0))) +} + +/// Spawn a backbone server; each accepted connection becomes an `InterfaceHandle`. +pub async fn spawn_backbone_server( + config: BackboneServerConfig, + id: InterfaceId, + id_gen: Arc, + transport_tx: mpsc::Sender, + handle_tx: mpsc::Sender, +) -> Result { + let listen_ip = resolve_listen_addr(&config); + let bind_addr = if listen_ip.starts_with('[') { + format!("{}:{}", listen_ip, config.listen_port) + } else if listen_ip.contains(':') && !listen_ip.contains('.') { + format!("[{}]:{}", listen_ip, config.listen_port) + } else { + format!("{}:{}", listen_ip, config.listen_port) + }; + let listener = TcpListener::bind(&bind_addr).await?; + let local_addr = listener.local_addr()?; + tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening"); + + let online = Arc::new(AtomicBool::new(true)); + let online2 = online.clone(); + let name = config.name.clone(); + let mode = config.mode; + + // Parent listener is inbound-only; drain task warns on stray writes. + let (tx, mut listener_rx) = mpsc::channel::(1); + let drain_name = name.clone(); + tokio::spawn(async move { + while listener_rx.recv().await.is_some() { + tracing::warn!( + name = %drain_name, + "backbone listener tx received unexpected outbound data; dropping", + ); + } + }); + + let read_task = tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((stream, peer)) => { + let client_id = id_gen.fetch_add(1, Ordering::SeqCst); + let client_name = format!("{}/client_{}", config.name, client_id); + tracing::info!( + name = %client_name, + peer = %peer, + "backbone: accepted connection", + ); + + tune_stream(&stream); + + let c_online = Arc::new(AtomicBool::new(true)); + let c_rxb = Arc::new(AtomicU64::new(0)); + let c_txb = Arc::new(AtomicU64::new(0)); + let (c_tx, c_rx) = mpsc::channel::(TX_CHANNEL_DEPTH); + let (reader, writer) = stream.into_split(); + + let c_online_w = c_online.clone(); + let c_txb_w = c_txb.clone(); + tokio::spawn(backbone_write_loop(writer, c_rx, c_online_w, c_txb_w)); + + let c_online_r = c_online.clone(); + let c_rxb_r = c_rxb.clone(); + let transport_tx2 = transport_tx.clone(); + let dereg_tx = transport_tx.clone(); + let cname = client_name.clone(); + let read_handle = tokio::spawn(async move { + backbone_read_loop(reader, client_id, transport_tx2, c_online_r, c_rxb_r) + .await; + tracing::info!(name = %cname, "backbone client disconnected"); + // Proactive notify so broadcasts don't target dead tx. + let _ = dereg_tx + .send(TransportMessage::DeregisterInterface { id: client_id }) + .await; + }); + + let handle = InterfaceHandle { + id: client_id, + name: client_name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: CHILD_BITRATE_GUESS, + mtu: child_mtu(), + online: c_online, + rxb: Some(c_rxb), + txb: Some(c_txb), + tx: c_tx, + read_task: read_handle, + }; + if handle_tx.send(handle).await.is_err() { + tracing::warn!("backbone handle registry closed"); + break; + } + } + Err(e) => { + tracing::warn!(error = %e, "backbone accept error"); + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + } + online2.store(false, Ordering::SeqCst); + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: false, + forward: false, + repeat: false, + }, + bitrate: BITRATE_GUESS, + mtu: rns_wire::constants::MTU as u32, + online, + rxb: Some(Arc::new(AtomicU64::new(0))), + txb: Some(Arc::new(AtomicU64::new(0))), + tx, + read_task, + }) +} + +pub async fn spawn_backbone_client( + config: BackboneClientConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let online = Arc::new(AtomicBool::new(false)); + let online2 = online.clone(); + let (tx, rx) = mpsc::channel::(TX_CHANNEL_DEPTH); + let name = config.name.clone(); + let mode = config.mode; + let rx = Arc::new(tokio::sync::Mutex::new(rx)); + + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let task_rxb = shared_rxb.clone(); + let task_txb = shared_txb.clone(); + + let read_task = tokio::spawn(async move { + let max_tries = config.max_reconnect_tries; + let mut tries: usize = 0; + + loop { + let target = match tokio::time::timeout( + Duration::from_secs(config.connect_timeout_secs), + resolve_target(&config.target_host, config.target_port, config.prefer_ipv6), + ) + .await + { + Ok(Ok(addr)) => addr, + Ok(Err(e)) => { + tracing::warn!(name = %config.name, error = %e, "backbone resolve failed"); + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + let _ = transport_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + return; + } + } + tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await; + continue; + } + Err(_) => { + tracing::warn!(name = %config.name, "backbone resolve timed out"); + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + let _ = transport_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + return; + } + } + tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await; + continue; + } + }; + + let stream = match tokio::time::timeout( + Duration::from_secs(config.connect_timeout_secs), + TcpStream::connect(target), + ) + .await + { + Ok(Ok(s)) => s, + Ok(Err(e)) => { + tracing::warn!(name = %config.name, error = %e, "backbone connect failed"); + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + let _ = transport_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + return; + } + } + tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await; + continue; + } + Err(_) => { + tracing::warn!(name = %config.name, "backbone connect timed out"); + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + let _ = transport_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + return; + } + } + tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await; + continue; + } + }; + + tune_stream(&stream); + online2.store(true, Ordering::SeqCst); + tries = 0; + + let c_online = Arc::new(AtomicBool::new(true)); + let (reader, writer) = stream.into_split(); + + let (conn_tx, conn_rx) = mpsc::channel::(TX_CHANNEL_DEPTH); + let c_online_w = c_online.clone(); + let c_txb = task_txb.clone(); + let write_handle = + tokio::spawn(backbone_write_loop(writer, conn_rx, c_online_w, c_txb)); + + let rx_ref = rx.clone(); + let fwd_handle = tokio::spawn(async move { + let mut guard = rx_ref.lock().await; + while let Some(data) = guard.recv().await { + if conn_tx.send(data).await.is_err() { + break; + } + } + }); + + let c_online_r = c_online.clone(); + let c_rxb = task_rxb.clone(); + backbone_read_loop(reader, id, transport_tx.clone(), c_online_r, c_rxb).await; + + online2.store(false, Ordering::SeqCst); + fwd_handle.abort(); + let _ = fwd_handle.await; + write_handle.abort(); + let _ = write_handle.await; + + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + let _ = transport_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + return; + } + } + tracing::info!( + name = %config.name, + "backbone: reconnecting in {}s", + RECONNECT_WAIT, + ); + tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await; + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: CHILD_BITRATE_GUESS, + mtu: child_mtu(), + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_backbone_server_config() { + let cfg = BackboneServerConfig::new("backbone0", "0.0.0.0", 4243); + assert_eq!(cfg.listen_port, 4243); + assert!(!cfg.prefer_ipv6); + assert!(cfg.device.is_none()); + } + + #[test] + fn test_backbone_client_config() { + let cfg = BackboneClientConfig::new("bb-client", "10.0.0.1", 4243); + assert_eq!(cfg.target_host, "10.0.0.1"); + assert_eq!(cfg.connect_timeout_secs, INITIAL_CONNECT_TIMEOUT); + } + + #[test] + fn test_constants() { + assert_eq!(HW_MTU, 1_048_576); + assert_eq!(BITRATE_GUESS, 1_000_000_000); + assert_eq!(CHILD_BITRATE_GUESS, 100_000_000); + assert_eq!(RECONNECT_WAIT, 5); + } + + #[test] + fn test_backbone_server_config_mode() { + let cfg = BackboneServerConfig::new("bb-srv", "0.0.0.0", 4243); + assert_eq!(cfg.mode, InterfaceMode::Full); + assert_eq!(cfg.listen_ip, "0.0.0.0"); + assert_eq!(cfg.name, "bb-srv"); + } + + #[test] + fn test_backbone_client_config_defaults() { + let cfg = BackboneClientConfig::new("bb-cli", "192.168.1.1", 4243); + assert_eq!(cfg.target_host, "192.168.1.1"); + assert_eq!(cfg.target_port, 4243); + assert_eq!(cfg.mode, InterfaceMode::Full); + assert!(cfg.max_reconnect_tries.is_none()); + } + + #[test] + fn test_backbone_config_ipv6() { + let cfg = BackboneServerConfig::new("bb-v6", "::", 4243); + assert!(!cfg.prefer_ipv6); + let mut cfg = cfg; + cfg.prefer_ipv6 = true; + assert!(cfg.prefer_ipv6); + } + + #[test] + fn test_child_mtu_uses_100mbps_curve() { + // optimise_mtu(100 Mbps) is one of the step values; verify the + // result lands inside the HW_MTU ceiling. + let mtu = child_mtu(); + assert!(mtu <= HW_MTU); + assert!(mtu >= rns_wire::constants::MTU as u32 / 2); + } + + #[tokio::test] + async fn test_backbone_max_reconnect_dereg() { + // Connect attempts to a port nobody is listening on; with + // max_reconnect_tries = Some(1) we get one connect attempt, one + // failure, then DeregisterInterface and exit. + let mut cfg = BackboneClientConfig::new("bb-dereg", "127.0.0.1", 1); + cfg.connect_timeout_secs = 1; + cfg.max_reconnect_tries = Some(1); + + let (tx, mut rx) = mpsc::channel::(8); + let handle = spawn_backbone_client(cfg, 99, tx).await.unwrap(); + // Wait for the read_task to finish — guarded by a generous timeout + // to absorb the one RECONNECT_WAIT sleep + connect attempt. + let dereg = tokio::time::timeout(Duration::from_secs(15), async { + loop { + match rx.recv().await { + Some(TransportMessage::DeregisterInterface { id }) => return Some(id), + Some(_) => continue, + None => return None, + } + } + }) + .await + .ok() + .flatten(); + assert_eq!(dereg, Some(99)); + // Drop the handle (aborts read_task if still alive). + drop(handle); + } + + #[tokio::test] + async fn test_resolve_target_loopback_v4() { + let addr = resolve_target("127.0.0.1", 1234, false).await.unwrap(); + assert!(addr.is_ipv4()); + assert_eq!(addr.port(), 1234); + } +} diff --git a/crates/rns-interface/src/ble_central_apple.rs b/crates/rns-interface/src/ble_central_apple.rs new file mode 100644 index 0000000..e96e512 --- /dev/null +++ b/crates/rns-interface/src/ble_central_apple.rs @@ -0,0 +1,932 @@ +//! Apple CBCentralManager scan driver. +//! +//! Exists to pass `CBCentralManagerScanOptionAllowDuplicatesKey = YES` to +//! `scanForPeripheralsWithServices:options:` — btleplug does not expose +//! that key, and without it CoreBluetooth reports each peripheral at most +//! once per scan session. + +#![cfg(any(target_os = "ios", target_os = "macos"))] + +use crate::ble_central_lifecycle::{ + CentralEvent, CentralLifecycle, CentralState, DiscoveryEvent, classify_protocol, +}; +use crate::ble_peer::{COLUMBA_SERVICE_UUID, RATSPEAK_SERVICE_UUID}; +use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; +use objc2::{msg_send, sel}; +use objc2_core_bluetooth::{ + CBAdvertisementDataServiceUUIDsKey, CBCentralManagerOptionRestoreIdentifierKey, + CBCentralManagerRestoredStatePeripheralsKey, CBCentralManagerRestoredStateScanOptionsKey, + CBCentralManagerRestoredStateScanServicesKey, CBCentralManagerScanOptionAllowDuplicatesKey, +}; +use objc2_foundation::NSString; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use tokio::sync::mpsc; +use uuid::Uuid; + +/// Must stay stable across updates; changing forfeits previously-backgrounded connections. +const CENTRAL_RESTORE_ID: &str = "org.ratspeak.ios.central"; + +struct SendPtr(*mut AnyObject); +unsafe impl Send for SendPtr {} +unsafe impl Sync for SendPtr {} + +/// Live CBCentralManager. Null when no scan is in flight. +static MANAGER_PTR: OnceLock> = OnceLock::new(); +static DELEGATE_CLASS: OnceLock<&'static AnyClass> = OnceLock::new(); +static LIFECYCLE: OnceLock = OnceLock::new(); +/// Replaced every `start_scan` so each cycle has a fresh receiver. +static DISCOVERY_TX: OnceLock>>> = + OnceLock::new(); +/// Worker thread waits on this until `did_update_state` reports `PoweredOn`. +static POWERED_ON_TX: OnceLock>>> = OnceLock::new(); +static SCAN_SERVICES: OnceLock>> = OnceLock::new(); + +fn lifecycle() -> &'static CentralLifecycle { + LIFECYCLE.get_or_init(CentralLifecycle::new) +} + +/// Trace invalid transitions instead of panicking — BLE stacks occasionally +/// deliver redundant callbacks. +fn apply_event(event: CentralEvent) -> Option { + match lifecycle().apply(event.clone()) { + Ok(state) => { + tracing::trace!(?event, ?state, "Apple BLE central lifecycle"); + Some(state) + } + Err(err) => { + tracing::warn!(?err, "Apple BLE central lifecycle: rejected transition"); + None + } + } +} + +fn discovery_tx() -> &'static Mutex>> { + DISCOVERY_TX.get_or_init(|| Mutex::new(None)) +} + +fn powered_on_tx() -> &'static Mutex>> { + POWERED_ON_TX.get_or_init(|| Mutex::new(None)) +} + +fn scan_services() -> &'static Mutex> { + SCAN_SERVICES.get_or_init(|| Mutex::new(Vec::new())) +} + +fn manager_slot() -> &'static Mutex { + MANAGER_PTR.get_or_init(|| Mutex::new(SendPtr(std::ptr::null_mut()))) +} + +/// Start a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty +/// `services` scans for all advertisements. +pub async fn start_scan( + services: Vec, +) -> Result, String> { + let cur = lifecycle().current(); + if matches!( + cur, + CentralState::Scanning | CentralState::StartingWaitingPlatform | CentralState::StoppingScan + ) { + return Err(format!("BLE scan already in progress (state={cur:?})")); + } + + apply_event(CentralEvent::StartRequested); + + let (tx, rx) = mpsc::unbounded_channel::(); + { + let mut g = discovery_tx() + .lock() + .map_err(|e| format!("discovery_tx lock poisoned: {e}"))?; + *g = Some(tx); + } + { + let mut g = scan_services() + .lock() + .map_err(|e| format!("scan_services lock poisoned: {e}"))?; + *g = services; + } + + // CoreBluetooth on macOS returns state=Unsupported on rapid alloc/release + // cycles, so the first manager stays retained and later cycles just rotate + // the discovery channel and reissue `scanForPeripheralsWithServices`. + let existing_mgr: Option<*mut AnyObject> = { + match manager_slot().lock() { + Ok(g) if !g.0.is_null() => Some(g.0), + _ => None, + } + }; + if let Some(mgr_raw) = existing_mgr { + unsafe { + scan_with_manager(mgr_raw) + .map_err(|e| format!("rescan on persistent manager failed: {e}"))?; + } + apply_event(CentralEvent::PlatformReady); + tracing::info!( + target: "ble_trace", + step = "central.scan_reused_manager", + "Apple BLE Central: rescan invoked on persistent manager" + ); + return Ok(rx); + } + + let (signal_tx, signal_rx) = std::sync::mpsc::channel::<()>(); + { + let mut g = powered_on_tx() + .lock() + .map_err(|e| format!("powered_on_tx lock poisoned: {e}"))?; + *g = Some(signal_tx); + } + + // OS thread: raw `*mut AnyObject` isn't Send, and + // `initWithDelegate:queue:nil` wires the delegate to CoreBluetooth's + // main dispatch queue. + std::thread::spawn(move || unsafe { + let delegate_cls = get_delegate_class(); + let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc]; + let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init]; + + let Some(mgr_cls) = AnyClass::get("CBCentralManager") else { + tracing::error!("Apple BLE Central: CBCentralManager class not found"); + return; + }; + let mgr_raw: *mut AnyObject = msg_send![mgr_cls, alloc]; + // RestoreIdentifierKey lets iOS resurrect us for a background BLE + // event after the process is killed. + let opts = match build_init_options() { + Ok(d) => d, + Err(e) => { + tracing::error!("Apple BLE Central: init-options build failed: {e}"); + std::ptr::null_mut::() + } + }; + let mgr_raw: *mut AnyObject = msg_send![mgr_raw, + initWithDelegate: delegate_raw, + queue: std::ptr::null::(), + options: opts, + ]; + // `retain` returns `id`; binding as `*mut AnyObject` avoids objc2's + // debug class-verify tripping on KVO-swizzled subclasses. + let _: *mut AnyObject = msg_send![mgr_raw, retain]; + + if let Ok(mut g) = manager_slot().lock() { + *g = SendPtr(mgr_raw); + } + tracing::info!("Apple BLE Central: manager created, waiting for PoweredOn"); + + // 10s safety net; real Bluetooth-off/permission errors surface + // through did_update_state, not here. + if let Err(e) = signal_rx.recv_timeout(Duration::from_secs(10)) { + tracing::error!("Apple BLE Central: timed out waiting for PoweredOn: {e}"); + return; + } + + match scan_with_manager(mgr_raw) { + Ok(()) => tracing::info!( + "Apple BLE Central: scanForPeripherals invoked (AllowDuplicates=YES)" + ), + Err(e) => tracing::error!("Apple BLE Central: scan invocation failed: {e}"), + } + }); + + Ok(rx) +} + +/// Idempotent. +pub async fn stop_scan() -> Result<(), String> { + let cur = lifecycle().current(); + if matches!( + cur, + CentralState::Idle | CentralState::Stopped | CentralState::Failed + ) { + tracing::debug!(state = ?cur, "Apple BLE Central: stop_scan is a no-op"); + return Ok(()); + } + + apply_event(CentralEvent::StopRequested); + + // Issue the ObjC calls outside the manager lock so concurrent + // did_discover callbacks (which take the same lock) can't deadlock. + let mgr_ptr: *mut AnyObject = { + match manager_slot().lock() { + Ok(g) if !g.0.is_null() => g.0, + _ => { + // No manager ever constructed, or already torn down. + finalize_stop(); + return Ok(()); + } + } + }; + + unsafe { + // We do NOT release the manager — the next start_scan reuses it. + // Per-cycle release on macOS triggers CBManagerStateUnsupported. + // `teardown_central` does the full release on interface shutdown. + let _: () = msg_send![&*mgr_ptr, stopScan]; + } + + finalize_stop(); + Ok(()) +} + +/// Full teardown — interface shutdown only. Per-cycle stops use +/// [`stop_scan`] to keep the manager alive (macOS alloc-cycle bug). +pub async fn teardown_central() -> Result<(), String> { + let _ = stop_scan().await; + + let mgr_ptr: *mut AnyObject = match manager_slot().lock() { + Ok(g) if !g.0.is_null() => g.0, + _ => return Ok(()), + }; + + unsafe { + // Detach delegate before release so a late main-queue callback + // can't fire into a freed object. + let _: () = msg_send![&*mgr_ptr, setDelegate: std::ptr::null::()]; + // Balance the explicit retain from start_scan; the original alloc + // ref is intentionally left intact — CoreBluetooth keeps one for + // main-queue drain and a double-release UAFs on contended teardown. + let _: () = msg_send![&*mgr_ptr, release]; + } + + if let Ok(mut g) = manager_slot().lock() { + *g = SendPtr(std::ptr::null_mut()); + } + + Ok(()) +} + +fn finalize_stop() { + if let Some(lock) = POWERED_ON_TX.get() + && let Ok(mut g) = lock.lock() + { + *g = None; + } + // Drop the discovery sender so receivers don't hang on recv. + if let Some(lock) = DISCOVERY_TX.get() + && let Ok(mut g) = lock.lock() + { + *g = None; + } + apply_event(CentralEvent::ScanStopped); + apply_event(CentralEvent::Reset); +} + +pub fn current_state() -> CentralState { + lifecycle().current() +} + +/// Persistent `CBCentralManager` pointer. Apple central peripheral caches +/// are per-manager, not per-process — `ble_central_apple_connect` must +/// drive `connectPeripheral:` against the same manager that scanned. +pub fn central_manager_ptr() -> Option<*mut AnyObject> { + let lock = MANAGER_PTR.get()?; + let g = lock.lock().ok()?; + if g.0.is_null() { None } else { Some(g.0) } +} + +fn get_delegate_class() -> &'static AnyClass { + DELEGATE_CLASS.get_or_init(|| { + let superclass = AnyClass::get("NSObject").expect("NSObject must exist"); + let mut builder = ClassBuilder::new("RatspeakBleCentralDelegate", superclass) + .expect("ClassBuilder for central delegate must succeed"); + + extern "C" fn did_update_state( + _this: *mut AnyObject, + _sel: Sel, + central: *mut AnyObject, + ) { + if central.is_null() { + return; + } + let state: i64 = unsafe { msg_send![&*central, state] }; + tracing::info!( + state, + name = cb_state_name(state), + "Apple BLE Central: state update" + ); + + match state { + // CBManagerState: 0=Unknown 1=Resetting 2=Unsupported + // 3=Unauthorized 4=PoweredOff 5=PoweredOn. + 0 => {} + + 1 => { + apply_event(CentralEvent::PlatformUnavailable { + reason: "resetting".into(), + }); + } + + 2 => { + apply_event(CentralEvent::FatalError { + reason: "bluetooth unsupported".into(), + }); + } + + 3 => { + apply_event(CentralEvent::FatalError { + reason: "bluetooth permission denied".into(), + }); + } + + 4 => { + apply_event(CentralEvent::PlatformUnavailable { + reason: "bluetooth off".into(), + }); + } + + // PoweredOn: signal the start_scan worker, or reissue + // scanForPeripherals if the worker already exited (recovery). + 5 => { + let tx = match powered_on_tx().lock() { + Ok(mut g) => g.take(), + Err(e) => { + tracing::error!("Apple BLE Central: powered_on_tx lock err: {e}"); + return; + } + }; + if let Some(tx) = tx { + if let Err(e) = tx.send(()) { + tracing::error!( + "Apple BLE Central: powered_on signal send err: {e}" + ); + return; + } + apply_event(CentralEvent::PlatformReady); + tracing::info!( + "Apple BLE Central: powered on (initial), releasing worker" + ); + return; + } + + let s = lifecycle().current(); + if !matches!(s, CentralState::StartingWaitingPlatform) { + tracing::info!(state = ?s, "Apple BLE Central: PoweredOn with no recovery needed"); + return; + } + let Some(mgr_lock) = MANAGER_PTR.get() else { + tracing::warn!( + "Apple BLE Central: recovery PoweredOn but manager slot unset" + ); + return; + }; + let mgr_ptr = match mgr_lock.lock() { + Ok(g) if !g.0.is_null() => g.0, + _ => { + tracing::warn!( + "Apple BLE Central: recovery PoweredOn but manager is null" + ); + return; + } + }; + unsafe { + match scan_with_manager(mgr_ptr) { + Ok(()) => { + apply_event(CentralEvent::PlatformReady); + tracing::info!( + "Apple BLE Central: powered on (recovery), scan resumed" + ); + } + Err(e) => { + tracing::error!( + "Apple BLE Central: recovery scan invocation failed: {e}" + ); + } + } + } + } + + _ => { + tracing::warn!(state, "Apple BLE Central: unknown CBManagerState"); + } + } + } + + // iOS calls this BEFORE `centralManagerDidUpdateState:` when + // resurrecting our process for a background BLE event. Restored TX + // subscriptions survive; we just need a live per-peripheral delegate + // before any further callbacks fire. + extern "C" fn will_restore_state( + _this: *mut AnyObject, + _sel: Sel, + _central: *mut AnyObject, + dict: *mut AnyObject, + ) { + if dict.is_null() { + tracing::info!("Apple BLE Central: willRestoreState (empty dict)"); + return; + } + unsafe { + let peripherals: *mut AnyObject = + msg_send![&*dict, objectForKey: CBCentralManagerRestoredStatePeripheralsKey]; + let scan_services: *mut AnyObject = + msg_send![&*dict, objectForKey: CBCentralManagerRestoredStateScanServicesKey]; + let scan_options: *mut AnyObject = + msg_send![&*dict, objectForKey: CBCentralManagerRestoredStateScanOptionsKey]; + + let peripheral_count: usize = if peripherals.is_null() { + 0 + } else { + msg_send![&*peripherals, count] + }; + let service_count: usize = if scan_services.is_null() { + 0 + } else { + msg_send![&*scan_services, count] + }; + let has_options = !scan_options.is_null(); + + tracing::info!( + target: "ble_trace", + step = "central.will_restore_state", + peripheral_count, + service_count, + has_options, + "Apple BLE Central: willRestoreState" + ); + + // Adopt only Connected peripherals; other states fall through + // to the next scan cycle. On error `adopt_restored_peer` + // releases the retain. + if !peripherals.is_null() { + for i in 0..peripheral_count { + let p: *mut AnyObject = msg_send![&*peripherals, objectAtIndex: i]; + if p.is_null() { + continue; + } + let state: i64 = msg_send![&*p, state]; + let identifier = peripheral_identifier(p); + if identifier.is_empty() { + tracing::warn!( + target: "ble_trace", + step = "central.restore_skip_no_id", + cb_state = state, + "Apple BLE Central: skipping restored peripheral with no identifier" + ); + continue; + } + const CB_PERIPHERAL_STATE_CONNECTED: i64 = 2; + if state != CB_PERIPHERAL_STATE_CONNECTED { + tracing::info!( + target: "ble_trace", + step = "central.restore_skip_state", + address = %identifier, + cb_state = state, + "Apple BLE Central: restored peripheral not in Connected state \u{2014} deferring to scan rediscovery" + ); + continue; + } + // ConnectedPeer::drop balances this retain on success; + // adopt_restored_peer releases on failure. + let _: *mut AnyObject = msg_send![p, retain]; + match crate::ble_central_apple_connect::adopt_restored_peer( + identifier.clone(), + p, + ) { + Ok(()) => { + tracing::info!( + target: "ble_trace", + step = "central.restore_adopted", + address = %identifier, + "Apple BLE Central: restored Connected peripheral adopted" + ); + } + Err(e) => { + tracing::warn!( + target: "ble_trace", + step = "central.restore_adopt_failed", + address = %identifier, + error = %e, + "Apple BLE Central: adopt_restored_peer failed; the helper already released the retain" + ); + } + } + } + } + } + } + + extern "C" fn did_discover( + _this: *mut AnyObject, + _sel: Sel, + _central: *mut AnyObject, + peripheral: *mut AnyObject, + ad_data: *mut AnyObject, + rssi: *mut AnyObject, + ) { + if peripheral.is_null() { + return; + } + let identifier = unsafe { peripheral_identifier(peripheral) }; + let rssi_i16: i16 = unsafe { nsnumber_to_i16(rssi) }; + if identifier.is_empty() { + tracing::debug!( + target: "ble_trace", + step = "central.discover_drop_no_id", + rssi = rssi_i16, + "Apple BLE Central: didDiscoverPeripheral with empty identifier" + ); + return; + } + let services = unsafe { extract_advertised_services(ad_data) }; + let classified = + classify_protocol(&services, RATSPEAK_SERVICE_UUID, COLUMBA_SERVICE_UUID); + tracing::debug!( + target: "ble_trace", + step = "central.discover", + peripheral = %identifier, + rssi = rssi_i16, + advertised_services = ?services, + classified = ?classified, + "Apple BLE Central: didDiscoverPeripheral" + ); + let protocol = match classified { + Some(p) => p, + // Duplicates mode occasionally reports ads that don't fully + // match the filter. + None => return, + }; + + // The connect path needs the same CBPeripheral pointer the scan + // saw — Apple central peripheral caches don't cross managers. + // CoreBluetooth delivers a valid `CBPeripheral *` for this delegate call. + unsafe { + crate::ble_central_apple_connect::record_discovered( + identifier.clone(), + peripheral, + ); + } + + let event = DiscoveryEvent { + identifier, + rssi: rssi_i16, + services, + protocol, + seen_at: Instant::now(), + }; + + // No sender means stop_scan raced us between the radio event + // and this callback — drop silently. + if let Some(lock) = DISCOVERY_TX.get() + && let Ok(g) = lock.lock() + && let Some(tx) = g.as_ref() + { + let _ = tx.send(event); + } + } + + // Connection-state callbacks share this delegate (one delegate per + // CBCentralManager) and forward to ble_central_apple_connect. + extern "C" fn did_connect( + _this: *mut AnyObject, + _sel: Sel, + _central: *mut AnyObject, + peripheral: *mut AnyObject, + ) { + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + tracing::info!( + target: "ble_trace", + step = "central.did_connect", + address = %address, + "Apple BLE Central: didConnectPeripheral" + ); + crate::ble_central_apple_connect::on_did_connect(&address); + } + + extern "C" fn did_fail_to_connect( + _this: *mut AnyObject, + _sel: Sel, + _central: *mut AnyObject, + peripheral: *mut AnyObject, + error: *mut AnyObject, + ) { + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + let err = if error.is_null() { + "didFailToConnect (no error description)".to_string() + } else { + unsafe { nserror_message(error) } + }; + tracing::warn!( + target: "ble_trace", + step = "central.did_fail_connect", + address = %address, + error = %err, + "Apple BLE Central: didFailToConnectPeripheral" + ); + crate::ble_central_apple_connect::on_did_fail_connect(&address, err); + } + + extern "C" fn did_disconnect( + _this: *mut AnyObject, + _sel: Sel, + _central: *mut AnyObject, + peripheral: *mut AnyObject, + error: *mut AnyObject, + ) { + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + let err = if error.is_null() { + None + } else { + Some(unsafe { nserror_message(error) }) + }; + tracing::info!( + target: "ble_trace", + step = "central.did_disconnect", + address = %address, + error = ?err, + "Apple BLE Central: didDisconnectPeripheral" + ); + crate::ble_central_apple_connect::on_did_disconnect(&address, err); + } + + unsafe { + builder.add_method( + sel!(centralManagerDidUpdateState:), + did_update_state as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject), + ); + builder.add_method( + sel!(centralManager:willRestoreState:), + will_restore_state + as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject), + ); + builder.add_method( + sel!(centralManager:didDiscoverPeripheral:advertisementData:RSSI:), + did_discover + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(centralManager:didConnectPeripheral:), + did_connect + as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject), + ); + builder.add_method( + sel!(centralManager:didFailToConnectPeripheral:error:), + did_fail_to_connect + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(centralManager:didDisconnectPeripheral:error:), + did_disconnect + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + } + + builder.register() + }) +} + +unsafe fn nserror_message(err: *mut AnyObject) -> String { + if err.is_null() { + return String::new(); + } + unsafe { + let desc: *mut AnyObject = msg_send![&*err, localizedDescription]; + nsstring_to_string(desc) + } +} + +/// # Safety +/// `mgr_raw` must be a retained, non-null `CBCentralManager` whose delegate +/// has been installed and whose `state` is PoweredOn. +unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> { + let services = scan_services() + .lock() + .map_err(|e| format!("scan_services lock poisoned: {e}"))? + .clone(); + + unsafe { + // nil filter = scan all. + let svc_arr: *mut AnyObject = if services.is_empty() { + std::ptr::null_mut() + } else { + let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?; + let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(services.len()); + for u in &services { + raw_ptrs.push(cbuuid(u) as *const AnyObject); + } + msg_send![arr_cls, + arrayWithObjects: raw_ptrs.as_ptr(), + count: raw_ptrs.len()] + }; + + let number_cls = AnyClass::get("NSNumber").ok_or("NSNumber not found")?; + let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?; + let yes: *mut AnyObject = msg_send![number_cls, numberWithBool: true]; + let opts: *mut AnyObject = msg_send![dict_cls, + dictionaryWithObject: yes, + forKey: CBCentralManagerScanOptionAllowDuplicatesKey]; + + tracing::info!( + target: "ble_trace", + step = "central.scan_invoked", + filter_count = services.len(), + filter_uuids = ?services, + "Apple BLE Central: scanForPeripheralsWithServices" + ); + let _: () = msg_send![&*mgr_raw, + scanForPeripheralsWithServices: svc_arr, + options: opts]; + } + Ok(()) +} + +/// `{ RestoreIdentifierKey: CENTRAL_RESTORE_ID }`. Ignored on macOS. +unsafe fn build_init_options() -> Result<*mut AnyObject, String> { + unsafe { + let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?; + let restore_id = NSString::from_str(CENTRAL_RESTORE_ID); + let opts: *mut AnyObject = msg_send![dict_cls, + dictionaryWithObject: &*restore_id, + forKey: CBCentralManagerOptionRestoreIdentifierKey]; + Ok(opts) + } +} + +fn cb_state_name(state: i64) -> &'static str { + match state { + 0 => "unknown", + 1 => "resetting", + 2 => "unsupported", + 3 => "unauthorized", + 4 => "poweredOff", + 5 => "poweredOn", + _ => "?", + } +} + +unsafe fn peripheral_identifier(peripheral: *mut AnyObject) -> String { + unsafe { + let id_obj: *mut AnyObject = msg_send![&*peripheral, identifier]; + if id_obj.is_null() { + return String::new(); + } + let uuid_str: *mut AnyObject = msg_send![&*id_obj, UUIDString]; + nsstring_to_string(uuid_str) + } +} + +/// Short SIG forms like "180D" are expanded to the Bluetooth base UUID. +unsafe fn extract_advertised_services(ad_data: *mut AnyObject) -> Vec { + if ad_data.is_null() { + return Vec::new(); + } + unsafe { + let arr: *mut AnyObject = + msg_send![&*ad_data, objectForKey: CBAdvertisementDataServiceUUIDsKey]; + if arr.is_null() { + return Vec::new(); + } + let count: usize = msg_send![&*arr, count]; + let mut out = Vec::with_capacity(count); + for i in 0..count { + let cb: *mut AnyObject = msg_send![&*arr, objectAtIndex: i]; + if cb.is_null() { + continue; + } + let s_obj: *mut AnyObject = msg_send![&*cb, UUIDString]; + if s_obj.is_null() { + continue; + } + let s = nsstring_to_string(s_obj); + match Uuid::parse_str(&s) { + Ok(u) => out.push(u), + Err(_) => { + if let Ok(u) = parse_short_uuid(&s) { + out.push(u); + } + } + } + } + out + } +} + +/// Null → `-100` (treated as far-away, not drop-worthy). +unsafe fn nsnumber_to_i16(n: *mut AnyObject) -> i16 { + if n.is_null() { + return -100; + } + let v: i32 = unsafe { msg_send![&*n, intValue] }; + v.clamp(i16::MIN as i32, i16::MAX as i32) as i16 +} + +unsafe fn nsstring_to_string(s: *mut AnyObject) -> String { + if s.is_null() { + return String::new(); + } + unsafe { + let utf8: *const std::ffi::c_char = msg_send![&*s, UTF8String]; + // 4 = NSUTF8StringEncoding + let len: usize = msg_send![&*s, lengthOfBytesUsingEncoding: 4usize]; + if utf8.is_null() || len == 0 { + return String::new(); + } + let bytes = std::slice::from_raw_parts(utf8 as *const u8, len); + String::from_utf8_lossy(bytes).into_owned() + } +} + +fn cbuuid(uuid: &Uuid) -> *mut AnyObject { + let s = NSString::from_str(&uuid.to_string()); + unsafe { + let cls = AnyClass::get("CBUUID").expect("CBUUID must exist at runtime"); + let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s]; + // UUIDWithString: returns autoreleased; retain so the pointer + // survives the autorelease pool drain. + let _: *mut AnyObject = msg_send![obj, retain]; + obj + } +} + +/// Expand a SIG short UUID ("180D" / "0000180D") to its 128-bit form using +/// the Bluetooth base UUID. +fn parse_short_uuid(s: &str) -> Result { + let hex = s.trim(); + match hex.len() { + 4 => { + let v = u16::from_str_radix(hex, 16).map_err(|_| ())?; + Uuid::parse_str(&format!("0000{v:04x}-0000-1000-8000-00805f9b34fb")).map_err(|_| ()) + } + 8 => { + let v = u32::from_str_radix(hex, 16).map_err(|_| ())?; + Uuid::parse_str(&format!("{v:08x}-0000-1000-8000-00805f9b34fb")).map_err(|_| ()) + } + _ => Err(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_short_uuid_expands_16bit_to_base_uuid() { + let u = parse_short_uuid("180D").expect("must parse"); + assert_eq!( + u, + Uuid::parse_str("0000180d-0000-1000-8000-00805f9b34fb").unwrap() + ); + } + + #[test] + fn parse_short_uuid_expands_32bit_to_base_uuid() { + let u = parse_short_uuid("0000180D").expect("must parse"); + assert_eq!( + u, + Uuid::parse_str("0000180d-0000-1000-8000-00805f9b34fb").unwrap() + ); + } + + #[test] + fn parse_short_uuid_is_case_insensitive() { + let u1 = parse_short_uuid("180d").unwrap(); + let u2 = parse_short_uuid("180D").unwrap(); + assert_eq!(u1, u2); + } + + #[test] + fn parse_short_uuid_rejects_non_hex() { + assert!(parse_short_uuid("zzzz").is_err()); + assert!(parse_short_uuid("").is_err()); + assert!(parse_short_uuid("180").is_err()); + assert!(parse_short_uuid("1800000D").is_ok()); + } + + #[test] + fn cb_state_name_covers_documented_states() { + assert_eq!(cb_state_name(0), "unknown"); + assert_eq!(cb_state_name(1), "resetting"); + assert_eq!(cb_state_name(2), "unsupported"); + assert_eq!(cb_state_name(3), "unauthorized"); + assert_eq!(cb_state_name(4), "poweredOff"); + assert_eq!(cb_state_name(5), "poweredOn"); + assert_eq!(cb_state_name(99), "?"); + } +} diff --git a/crates/rns-interface/src/ble_central_apple_connect.rs b/crates/rns-interface/src/ble_central_apple_connect.rs new file mode 100644 index 0000000..a565779 --- /dev/null +++ b/crates/rns-interface/src/ble_central_apple_connect.rs @@ -0,0 +1,1296 @@ +//! Apple central-role connect lifecycle. Sister to +//! [`ble_central_apple`](crate::ble_central_apple) (which owns scanning). +//! +//! Apple-specific because btleplug's CoreBluetooth backend allocates its +//! own manager, and two managers in the same process don't share peripheral +//! caches on macOS, so `adapter.peripherals()` returns empty every cycle. + +#![cfg(any(target_os = "ios", target_os = "macos"))] + +use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; +use objc2::{msg_send, sel}; +use objc2_foundation::NSString; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use tokio::sync::oneshot; +use uuid::Uuid; + +use crate::ble_peer::{ + COLUMBA_RX_UUID, COLUMBA_SERVICE_UUID, COLUMBA_TX_UUID, PeerProtocol, RATSPEAK_RX_UUID, + RATSPEAK_SERVICE_UUID, RATSPEAK_TX_UUID, +}; + +/// `connectPeripheral:` does not self-time-out; iOS RPA rotation leaves +/// ghost identifiers in `Connecting` state forever. 5s recycles ghosts +/// before they block the scan-loop pipeline. +pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + +/// Generous safety net for service / characteristic / notify discovery +/// (CoreBluetooth normally responds in ~200 ms). +pub const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(10); + +const DISCOVERED_TTL: Duration = Duration::from_secs(60); + +/// Sized to absorb an LXMF fragment burst (~40 × 244B) without unbounded +/// growth on a stuck peer. FIFO drop-oldest. +const PENDING_WRITE_CAP: usize = 128; + +struct SendPtr(*mut AnyObject); +unsafe impl Send for SendPtr {} +unsafe impl Sync for SendPtr {} + +/// Keyed by `CBPeripheral.identifier.UUIDString`. +static CONNECTED_PEERS: OnceLock>>> = OnceLock::new(); + +/// `std::sync::Mutex` so the CB-main-queue delegate can resolve without +/// crossing `.await`. +type PendingKey = (String, CallbackKind); +type PendingSender = oneshot::Sender>; +type PendingMap = HashMap; + +static PENDING: OnceLock> = OnceLock::new(); + +/// Each entry holds a +1 retain — released on prune or replace. +static DISCOVERED: OnceLock>> = OnceLock::new(); + +static DELEGATE_CLASS: OnceLock<&'static AnyClass> = OnceLock::new(); + +/// Per-peer online flag the disconnect callback can flip without going +/// through the `ConnectedPeer` map. +static ONLINE_FLAGS: OnceLock>>> = OnceLock::new(); + +/// One-shot disconnect classification, consumed by +/// [`take_last_disconnect_reason`] so the scan loop can distinguish +/// transient RPA-rotation drops from genuine peer failures. +static LAST_DISCONNECT_REASON: OnceLock>> = OnceLock::new(); + +/// Drained by `peripheralIsReadyToSendWriteWithoutResponse:`. +static PENDING_WRITE: OnceLock>>>> = OnceLock::new(); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DisconnectReason { + /// `CBErrorPeripheralConnectionTimeout` — almost always an iPhone / + /// Pixel RPA rotating out from under our open link. The peer + /// re-advertises within ~1s. + Rotation, + OtherError, +} + +#[derive(Hash, Eq, PartialEq, Clone, Copy, Debug)] +enum CallbackKind { + Connect, + Services, + Chars, + Notify, +} + +struct DiscoveredEntry { + peripheral: SendPtr, + seen_at: Instant, +} + +impl Drop for DiscoveredEntry { + fn drop(&mut self) { + if !self.peripheral.0.is_null() { + unsafe { + let _: () = msg_send![self.peripheral.0, release]; + } + } + } +} + +fn connected_peers() -> &'static Mutex>> { + CONNECTED_PEERS.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn pending() -> &'static Mutex { + PENDING.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn discovered() -> &'static Mutex> { + DISCOVERED.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn online_flags() -> &'static Mutex>> { + ONLINE_FLAGS.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn last_disconnect_reason() -> &'static Mutex> { + LAST_DISCONNECT_REASON.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn pending_write() -> &'static Mutex>>> { + PENDING_WRITE.get_or_init(|| Mutex::new(HashMap::new())) +} + +pub fn take_last_disconnect_reason(address: &str) -> Option { + last_disconnect_reason() + .lock() + .ok() + .and_then(|mut g| g.remove(address)) +} + +/// Drop frees the retained ObjC objects. Disconnect goes via +/// [`disconnect_peer`] (`cancelPeripheralConnection:`); the delegate +/// callback removes the map entry, dropping the last `Arc`. +pub struct ConnectedPeer { + pub address: String, + pub protocol: PeerProtocol, + pub write_mtu: usize, + pub online: Arc, + peripheral: SendPtr, + delegate: SendPtr, + rx_char: SendPtr, + tx_char: SendPtr, +} + +impl Drop for ConnectedPeer { + fn drop(&mut self) { + unsafe { + // Clear the (weakly-retained) delegate first so a late callback + // can't fire into freed memory after the release below. + if !self.peripheral.0.is_null() { + let _: () = + msg_send![self.peripheral.0, setDelegate: std::ptr::null::()]; + } + for p in [ + &self.delegate, + &self.rx_char, + &self.tx_char, + &self.peripheral, + ] { + if !p.0.is_null() { + let _: () = msg_send![p.0, release]; + } + } + } + } +} + +/// connect → discoverServices → discoverCharacteristics → setNotifyValue, +/// gated on each step's delegate callback. Tears down partial state on Err. +pub async fn connect_peer( + address: String, + protocol: PeerProtocol, +) -> Result, String> { + if is_connected(&address) { + return Err(format!("already connected: {address}")); + } + + prune_discovered(); + + // SendPtr keeps the future `Send` across awaits. + let peripheral = SendPtr( + take_discovered(&address) + .ok_or_else(|| format!("peripheral {address} not in discovered cache"))?, + ); + + let manager = match crate::ble_central_apple::central_manager_ptr() { + Some(p) => SendPtr(p), + None => { + unsafe { + let _: () = msg_send![peripheral.0, release]; + } + return Err("central manager not initialized".into()); + } + }; + + let delegate_cls = peripheral_delegate_class(); + let delegate = SendPtr(unsafe { + let alloced: *mut AnyObject = msg_send![delegate_cls, alloc]; + let inited: *mut AnyObject = msg_send![alloced, init]; + inited + }); + + // Free fn (not closure) so the future stays `Send` past the captured + // raw pointers. + fn teardown_partial( + address: &str, + manager: *mut AnyObject, + peripheral: *mut AnyObject, + delegate: *mut AnyObject, + reason: &str, + ) { + tracing::warn!( + target: "ble_trace", + step = "apple_connect.partial_teardown", + address = %address, + reason = %reason, + "Apple BLE central connect: tearing down partial connection" + ); + unsafe { + let _: () = msg_send![&*manager, cancelPeripheralConnection: peripheral]; + let _: () = msg_send![peripheral, setDelegate: std::ptr::null::()]; + let _: () = msg_send![delegate, release]; + let _: () = msg_send![peripheral, release]; + } + if let Ok(mut g) = pending().lock() { + for kind in [ + CallbackKind::Connect, + CallbackKind::Services, + CallbackKind::Chars, + CallbackKind::Notify, + ] { + g.remove(&(address.to_owned(), kind)); + } + } + } + + // Step 1: connectPeripheral + tracing::info!( + target: "ble_trace", + step = "apple_connect.connect_issued", + address = %address, + protocol = ?protocol, + "Apple BLE central: connectPeripheral" + ); + let rx = install_pending(&address, CallbackKind::Connect); + unsafe { + let _: () = msg_send![&*manager.0, + connectPeripheral: peripheral.0, + options: std::ptr::null::()]; + } + if let Err(e) = await_step(rx, "connect", CONNECT_TIMEOUT).await { + teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e); + return Err(e); + } + tracing::info!( + target: "ble_trace", + step = "apple_connect.did_connect", + address = %address, + "Apple BLE central: peripheral connected" + ); + + // Step 2: setDelegate, then discoverServices for the target only. + let target_service_uuid = match protocol { + PeerProtocol::Ratspeak => RATSPEAK_SERVICE_UUID, + PeerProtocol::Columba => COLUMBA_SERVICE_UUID, + }; + // install_pending must run BEFORE the CB call so a fast-path callback + // (cached service data) can't race ahead of its own entry. + let rx = install_pending(&address, CallbackKind::Services); + unsafe { + let _: () = msg_send![peripheral.0, setDelegate: delegate.0]; + let svc_filter = build_cbuuid_array(&[target_service_uuid]); + let _: () = msg_send![peripheral.0, discoverServices: svc_filter]; + } + if let Err(e) = await_step(rx, "discoverServices", DISCOVERY_TIMEOUT).await { + teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e); + return Err(e); + } + + let service = match unsafe { find_service(peripheral.0, target_service_uuid) } { + Some(p) => SendPtr(p), + None => { + let msg = format!("target service {target_service_uuid} not present after discovery"); + teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg); + return Err(msg); + } + }; + tracing::info!( + target: "ble_trace", + step = "apple_connect.services_discovered", + address = %address, + service = %target_service_uuid, + "Apple BLE central: services discovered" + ); + + // Step 3: discoverCharacteristics for rx + tx UUIDs. + let (rx_uuid, tx_uuid) = match protocol { + PeerProtocol::Ratspeak => (RATSPEAK_RX_UUID, RATSPEAK_TX_UUID), + PeerProtocol::Columba => (COLUMBA_RX_UUID, COLUMBA_TX_UUID), + }; + let rx = install_pending(&address, CallbackKind::Chars); + unsafe { + let chars_filter = build_cbuuid_array(&[rx_uuid, tx_uuid]); + let _: () = msg_send![peripheral.0, + discoverCharacteristics: chars_filter, + forService: service.0]; + } + if let Err(e) = await_step(rx, "discoverCharacteristics", DISCOVERY_TIMEOUT).await { + teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e); + return Err(e); + } + + let rx_char = match unsafe { find_char(service.0, rx_uuid) } { + Some(p) => SendPtr(p), + None => { + let msg = format!("rx characteristic {rx_uuid} missing after discovery"); + teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg); + return Err(msg); + } + }; + let tx_char = match unsafe { find_char(service.0, tx_uuid) } { + Some(p) => SendPtr(p), + None => { + let msg = format!("tx characteristic {tx_uuid} missing after discovery"); + teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg); + return Err(msg); + } + }; + // The peripheral owns these; retain so they outlive any single + // delegate callback frame. + unsafe { + let _: *mut AnyObject = msg_send![rx_char.0, retain]; + let _: *mut AnyObject = msg_send![tx_char.0, retain]; + } + tracing::info!( + target: "ble_trace", + step = "apple_connect.chars_discovered", + address = %address, + rx = %rx_uuid, + tx = %tx_uuid, + "Apple BLE central: characteristics discovered" + ); + + // Step 4: setNotifyValue:YES on tx_char (CB handles CCCD internally). + let rx = install_pending(&address, CallbackKind::Notify); + unsafe { + let _: () = msg_send![peripheral.0, + setNotifyValue: true, + forCharacteristic: tx_char.0]; + } + if let Err(e) = await_step(rx, "setNotifyValue", DISCOVERY_TIMEOUT).await { + // Balance the rx/tx retains on failure. + unsafe { + let _: () = msg_send![rx_char.0, release]; + let _: () = msg_send![tx_char.0, release]; + } + teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e); + return Err(e); + } + tracing::info!( + target: "ble_trace", + step = "apple_connect.notify_enabled", + address = %address, + tx_char = %tx_uuid, + "Apple BLE central: notifications enabled" + ); + + let online = Arc::new(AtomicBool::new(true)); + { + let mut g = online_flags().lock().expect("online_flags lock"); + g.insert(address.clone(), online.clone()); + } + 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, + online: online.clone(), + peripheral, + delegate, + rx_char, + tx_char, + }); + { + let mut g = connected_peers().lock().expect("connected_peers lock"); + g.insert(address.clone(), peer.clone()); + } + Ok(peer) +} + +/// Queues into [`PENDING_WRITE`] when `canSendWriteWithoutResponse` is +/// false — without queueing, fragmented LXMF messages silently lose every +/// fragment past the first on a loaded radio. +pub fn write_peer(address: &str, data: &[u8]) -> Result<(), String> { + let peer = { + let g = connected_peers().lock().expect("connected_peers lock"); + g.get(address).cloned() + }; + let peer = peer.ok_or_else(|| format!("peer {address} not connected"))?; + if !peer.online.load(Ordering::SeqCst) { + return Err(format!("peer {address} marked offline")); + } + + // The flag can flip back to false at any time after returning true + // (per Apple's docs); the ready-to-send delegate drains the queue. + let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] }; + if ready { + unsafe { issue_write(&peer, data) }; + return Ok(()); + } + + let mut g = pending_write().lock().expect("pending_write lock"); + let q = g.entry(address.to_owned()).or_default(); + if q.len() >= PENDING_WRITE_CAP { + q.pop_front(); + tracing::warn!( + target: "ble_trace", + step = "central.write_overflow_drop", + peer = %address, + cap = PENDING_WRITE_CAP, + "Apple BLE central: pending-write ring overflowed, dropping oldest" + ); + } + q.push_back(data.to_vec()); + tracing::debug!( + target: "ble_trace", + step = "central.write_queued", + peer = %address, + bytes = data.len(), + depth = q.len(), + "Apple BLE central: write queued (radio queue full)" + ); + Ok(()) +} + +/// Requeues at front if canSend flips false mid-drain. +unsafe fn drain_pending_writes(address: &str) { + let peer = { + let g = connected_peers().lock().expect("connected_peers lock"); + match g.get(address) { + Some(p) => p.clone(), + None => return, + } + }; + if !peer.online.load(Ordering::SeqCst) { + return; + } + let mut drained = 0usize; + loop { + let entry = { + let mut g = pending_write().lock().expect("pending_write lock"); + g.get_mut(address).and_then(|q| q.pop_front()) + }; + let Some(data) = entry else { + break; + }; + let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] }; + if !ready { + let mut g = pending_write().lock().expect("pending_write lock"); + g.entry(address.to_owned()).or_default().push_front(data); + break; + } + unsafe { issue_write(&peer, &data) }; + drained += 1; + } + if drained > 0 { + tracing::debug!( + target: "ble_trace", + step = "central.write_drained", + peer = %address, + drained, + "Apple BLE central: pending writes drained" + ); + } +} + +/// Caller must have either confirmed `canSendWriteWithoutResponse` or be +/// OK with silent drop on a full radio queue. +/// +/// # Safety +/// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB +/// pointers. +unsafe fn issue_write(peer: &Arc, data: &[u8]) { + unsafe { + let nsdata = nsdata_from_slice(data); + const WRITE_WITHOUT_RESPONSE: i64 = 1; + let _: () = msg_send![peer.peripheral.0, + writeValue: nsdata, + forCharacteristic: peer.rx_char.0, + type: WRITE_WITHOUT_RESPONSE]; + } +} + +/// Idempotent. +pub fn disconnect_peer(address: &str) { + let peer = { + let mut g = connected_peers().lock().expect("connected_peers lock"); + g.remove(address) + }; + let Some(peer) = peer else { + return; + }; + peer.online.store(false, Ordering::SeqCst); + if let Ok(mut g) = pending_write().lock() { + g.remove(address); + } + if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() { + unsafe { + let _: () = msg_send![&*manager_ptr, + cancelPeripheralConnection: peer.peripheral.0]; + } + } + // online_flags entry stays — the disconnect callback flips it. + tracing::info!( + target: "ble_trace", + step = "apple_connect.disconnect_issued", + address = %address, + "Apple BLE central: cancelPeripheralConnection" + ); +} + +pub fn is_connected(address: &str) -> bool { + connected_peers() + .lock() + .map(|g| g.contains_key(address)) + .unwrap_or(false) +} + +pub fn disconnect_all() { + let addrs: Vec = { + let g = connected_peers().lock().expect("connected_peers lock"); + g.keys().cloned().collect() + }; + for addr in addrs { + disconnect_peer(&addr); + } + if let Ok(mut g) = online_flags().lock() { + g.clear(); + } +} + +/// Adopt a CBPeripheral handed back via `centralManager:willRestoreState:`. +/// Apple guarantees `peripheral.services` is populated and prior TX-char +/// subscriptions are preserved — only the delegate needs rebinding. On +/// success ownership of the +1 retain passes to `ConnectedPeer::drop`; on +/// Err the retain is released. +/// +/// # Safety +/// `peripheral` must be a retained, non-null `CBPeripheral *` whose state +/// is `Connected (= 2)`. +pub unsafe fn adopt_restored_peer( + address: String, + peripheral: *mut AnyObject, +) -> Result<(), String> { + if address.is_empty() || peripheral.is_null() { + return Err("adopt_restored_peer: empty address or null peripheral".into()); + } + if is_connected(&address) { + unsafe { + let _: () = msg_send![peripheral, release]; + } + return Ok(()); + } + + let (service, protocol, rx_uuid, tx_uuid) = unsafe { + if let Some(s) = find_service(peripheral, RATSPEAK_SERVICE_UUID) { + ( + s, + PeerProtocol::Ratspeak, + RATSPEAK_RX_UUID, + RATSPEAK_TX_UUID, + ) + } else if let Some(s) = find_service(peripheral, COLUMBA_SERVICE_UUID) { + (s, PeerProtocol::Columba, COLUMBA_RX_UUID, COLUMBA_TX_UUID) + } else { + let _: () = msg_send![peripheral, release]; + return Err(format!( + "adopt_restored_peer: peripheral {address} has no Ratspeak or Columba service" + )); + } + }; + + let rx_char = match unsafe { find_char(service, rx_uuid) } { + Some(p) => SendPtr(p), + None => { + unsafe { + let _: () = msg_send![peripheral, release]; + } + return Err(format!( + "adopt_restored_peer: peripheral {address} missing RX char {rx_uuid}" + )); + } + }; + let tx_char = match unsafe { find_char(service, tx_uuid) } { + Some(p) => SendPtr(p), + None => { + unsafe { + let _: () = msg_send![rx_char.0, retain]; + let _: () = msg_send![rx_char.0, release]; + let _: () = msg_send![peripheral, release]; + } + return Err(format!( + "adopt_restored_peer: peripheral {address} missing TX char {tx_uuid}" + )); + } + }; + unsafe { + // Outlive the autorelease-pool drain; ConnectedPeer::drop balances. + let _: *mut AnyObject = msg_send![rx_char.0, retain]; + let _: *mut AnyObject = msg_send![tx_char.0, retain]; + } + + let delegate_cls = peripheral_delegate_class(); + let delegate = SendPtr(unsafe { + let alloced: *mut AnyObject = msg_send![delegate_cls, alloc]; + let inited: *mut AnyObject = msg_send![alloced, init]; + inited + }); + unsafe { + let _: () = msg_send![peripheral, setDelegate: delegate.0]; + } + + let online = Arc::new(AtomicBool::new(true)); + { + let mut g = online_flags().lock().expect("online_flags lock"); + g.insert(address.clone(), online.clone()); + } + let peer = Arc::new(ConnectedPeer { + address: address.clone(), + protocol, + write_mtu: 244, + online, + peripheral: SendPtr(peripheral), + delegate, + rx_char, + tx_char, + }); + { + let mut g = connected_peers().lock().expect("connected_peers lock"); + g.insert(address.clone(), peer); + } + tracing::info!( + target: "ble_trace", + step = "apple_connect.adopted_restored", + address = %address, + protocol = ?protocol, + "Apple BLE central: adopted restored peripheral" + ); + Ok(()) +} + +/// CB keeps connections alive thanks to `bluetooth-central` +/// UIBackgroundMode + restore-identifier; this just logs inventory. +pub fn on_app_will_resign_active() { + let connected = connected_peers().lock().map(|g| g.len()).unwrap_or(0); + let pending = pending_write() + .lock() + .map(|g| g.values().map(|q| q.len()).sum::()) + .unwrap_or(0); + tracing::info!( + target: "ble_trace", + step = "apple_connect.foregrounding_inventory", + connected_peers = connected, + pending_writes = pending, + "Apple BLE central: app will resign active \u{2014} connections kept alive by bluetooth-central background mode" + ); +} + +/// Prune discovered pointers older than [`DISCOVERED_TTL`] — after a long +/// background those are RPA-rotated ghosts. +pub fn on_app_did_become_active() { + prune_discovered(); + let discovered_remaining = match discovered().lock() { + Ok(g) => g.len(), + Err(_) => 0, + }; + let connected = connected_peers().lock().map(|g| g.len()).unwrap_or(0); + tracing::info!( + target: "ble_trace", + step = "apple_connect.foregrounded", + connected_peers = connected, + discovered_remaining, + "Apple BLE central: app did become active \u{2014} discovery cache pruned" + ); +} + +/// Replacing an entry releases the old one. +/// +/// # Safety +/// `peripheral` must be valid and non-null; this function retains it. +pub unsafe fn record_discovered(address: String, peripheral: *mut AnyObject) { + if address.is_empty() || peripheral.is_null() { + return; + } + unsafe { + // Survive the scan delegate's autorelease-pool drain. + let _: *mut AnyObject = msg_send![peripheral, retain]; + } + let mut g = match discovered().lock() { + Ok(g) => g, + Err(_) => return, + }; + let entry = DiscoveredEntry { + peripheral: SendPtr(peripheral), + seen_at: Instant::now(), + }; + g.insert(address, entry); +} + +pub fn prune_discovered() { + let mut g = match discovered().lock() { + Ok(g) => g, + Err(_) => return, + }; + g.retain(|_, e| e.seen_at.elapsed() < DISCOVERED_TTL); +} + +fn take_discovered(address: &str) -> Option<*mut AnyObject> { + let mut g = discovered().lock().ok()?; + let entry = g.remove(address)?; + // Forget so DiscoveredEntry::drop doesn't release — caller now owns the + // +1 retain from record_discovered. + let p = entry.peripheral.0; + std::mem::forget(entry); + Some(p) +} + +pub fn on_did_connect(address: &str) { + resolve_pending(address, CallbackKind::Connect, Ok(())); +} + +pub fn on_did_fail_connect(address: &str, err: String) { + resolve_pending(address, CallbackKind::Connect, Err(err)); +} + +pub fn on_did_disconnect(address: &str, err: Option) { + let removed = { + let mut g = match connected_peers().lock() { + Ok(g) => g, + Err(_) => return, + }; + g.remove(address) + }; + if let Some(peer) = removed { + peer.online.store(false, Ordering::SeqCst); + } + if let Ok(mut g) = online_flags().lock() + && let Some(flag) = g.remove(address) + { + flag.store(false, Ordering::SeqCst); + } + + let classified = classify_disconnect_reason(err.as_deref()); + if let Ok(mut g) = last_disconnect_reason().lock() { + g.insert(address.to_string(), classified); + } + + let reason = err.clone().unwrap_or_else(|| "peer disconnected".into()); + // Short-circuit any in-flight step so the awaiting task returns without + // burning the 10s timeout. + for kind in [ + CallbackKind::Connect, + CallbackKind::Services, + CallbackKind::Chars, + CallbackKind::Notify, + ] { + resolve_pending(address, kind, Err(format!("peer disconnected: {reason}"))); + } + tracing::info!( + target: "ble_trace", + step = "apple_connect.did_disconnect", + address = %address, + error = ?err, + "Apple BLE central: didDisconnectPeripheral" + ); + crate::ble_peer::dispatch_event(crate::ble_peer::BlePeerEvent::Disconnected { + address: address.into(), + reason, + }); +} + +fn install_pending(address: &str, kind: CallbackKind) -> oneshot::Receiver> { + let (tx, rx) = oneshot::channel(); + let mut g = pending().lock().expect("pending lock"); + g.insert((address.to_owned(), kind), tx); + rx +} + +fn resolve_pending(address: &str, kind: CallbackKind, result: Result<(), String>) { + let tx = { + let mut g = match pending().lock() { + Ok(g) => g, + Err(_) => return, + }; + g.remove(&(address.to_owned(), kind)) + }; + if let Some(tx) = tx { + let _ = tx.send(result); + } +} + +/// English-locale, case-insensitive substring match against rotation +/// signatures: `CBErrorPeripheralConnectionTimeout` (constant or localized +/// "timed out unexpectedly") and "specified device has disconnected". +fn classify_disconnect_reason(err: Option<&str>) -> DisconnectReason { + let Some(s) = err else { + return DisconnectReason::OtherError; + }; + let lower = s.to_ascii_lowercase(); + if lower.contains("timed out unexpectedly") + || lower.contains("cberrorperipheralconnectiontimeout") + || lower.contains("specified device has disconnected") + { + DisconnectReason::Rotation + } else { + DisconnectReason::OtherError + } +} + +async fn await_step( + rx: oneshot::Receiver>, + label: &'static str, + timeout: Duration, +) -> Result<(), String> { + match tokio::time::timeout(timeout, rx).await { + Ok(Ok(Ok(()))) => Ok(()), + Ok(Ok(Err(e))) => Err(format!("{label}: {e}")), + Ok(Err(_)) => Err(format!("{label}: oneshot dropped before reply")), + Err(_) => Err(format!("{label}: timed out after {timeout:?}")), + } +} + +fn peripheral_delegate_class() -> &'static AnyClass { + DELEGATE_CLASS.get_or_init(|| { + let superclass = AnyClass::get("NSObject").expect("NSObject must exist"); + let mut builder = ClassBuilder::new("RatspeakBlePeripheralDelegate", superclass) + .expect("ClassBuilder for peripheral delegate must succeed"); + + extern "C" fn did_discover_services( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + error: *mut AnyObject, + ) { + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + let result = if error.is_null() { + Ok(()) + } else { + Err(unsafe { nserror_message(error) }) + }; + resolve_pending(&address, CallbackKind::Services, result); + } + + extern "C" fn did_discover_characteristics( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + _service: *mut AnyObject, + error: *mut AnyObject, + ) { + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + let result = if error.is_null() { + Ok(()) + } else { + Err(unsafe { nserror_message(error) }) + }; + resolve_pending(&address, CallbackKind::Chars, result); + } + + extern "C" fn did_update_notification_state( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + _characteristic: *mut AnyObject, + error: *mut AnyObject, + ) { + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + let result = if error.is_null() { + Ok(()) + } else { + Err(unsafe { nserror_message(error) }) + }; + resolve_pending(&address, CallbackKind::Notify, result); + } + + extern "C" fn did_update_value_for_characteristic( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + characteristic: *mut AnyObject, + error: *mut AnyObject, + ) { + if peripheral.is_null() || characteristic.is_null() || !error.is_null() { + return; + } + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + let bytes = unsafe { characteristic_value_bytes(characteristic) }; + if bytes.is_empty() { + return; + } + tracing::debug!( + target: "ble_trace", + step = "apple_connect.notify_recv", + address = %address, + len = bytes.len(), + "Apple BLE central: notify received" + ); + // Same INBOUND_TX as apple_peripheral's GATT-server delegate — + // one reassembler downstream. + if !crate::ble_peer::try_push_apple_inbound(address.clone(), bytes) { + tracing::warn!( + target: "ble_trace", + step = "apple_connect.inbound_drop", + address = %address, + "Apple BLE central: inbound channel full or uninitialised" + ); + } + } + + // Kept registered so a future With-Response write doesn't crash on + // missing selector. We use WriteWithoutResponse, so this is informational. + extern "C" fn did_write_value_for_characteristic( + _this: *mut AnyObject, + _sel: Sel, + _peripheral: *mut AnyObject, + _characteristic: *mut AnyObject, + _error: *mut AnyObject, + ) { + } + + extern "C" fn is_ready_to_send_write_without_response( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + ) { + let address = unsafe { peripheral_identifier(peripheral) }; + if address.is_empty() { + return; + } + unsafe { drain_pending_writes(&address) }; + } + + unsafe { + builder.add_method( + sel!(peripheral:didDiscoverServices:), + did_discover_services + as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject), + ); + builder.add_method( + sel!(peripheral:didDiscoverCharacteristicsForService:error:), + did_discover_characteristics + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheral:didUpdateNotificationStateForCharacteristic:error:), + did_update_notification_state + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheral:didUpdateValueForCharacteristic:error:), + did_update_value_for_characteristic + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheral:didWriteValueForCharacteristic:error:), + did_write_value_for_characteristic + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheralIsReadyToSendWriteWithoutResponse:), + is_ready_to_send_write_without_response + as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject), + ); + } + builder.register() + }) +} + +/// Autoreleased `NSArray`; CB retains internally. +fn build_cbuuid_array(uuids: &[Uuid]) -> *mut AnyObject { + if uuids.is_empty() { + return std::ptr::null_mut(); + } + let cbuuid_cls = match AnyClass::get("CBUUID") { + Some(c) => c, + None => return std::ptr::null_mut(), + }; + let nsarr_cls = match AnyClass::get("NSArray") { + Some(c) => c, + None => return std::ptr::null_mut(), + }; + let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(uuids.len()); + for u in uuids { + let s = NSString::from_str(&u.to_string()); + unsafe { + let cb: *mut AnyObject = msg_send![cbuuid_cls, UUIDWithString: &*s]; + raw_ptrs.push(cb as *const AnyObject); + } + } + unsafe { + msg_send![nsarr_cls, + arrayWithObjects: raw_ptrs.as_ptr(), + count: raw_ptrs.len()] + } +} + +/// Autoreleased `NSData` over a copy of `bytes`; valid for the synchronous +/// CB call only. +unsafe fn nsdata_from_slice(bytes: &[u8]) -> *mut AnyObject { + let cls = AnyClass::get("NSData").expect("NSData class must exist"); + let ptr = bytes.as_ptr() as *const std::ffi::c_void; + let len = bytes.len(); + unsafe { msg_send![cls, dataWithBytes: ptr, length: len] } +} + +unsafe fn find_service(peripheral: *mut AnyObject, uuid: Uuid) -> Option<*mut AnyObject> { + if peripheral.is_null() { + return None; + } + unsafe { + let services: *mut AnyObject = msg_send![&*peripheral, services]; + if services.is_null() { + return None; + } + let count: usize = msg_send![&*services, count]; + for i in 0..count { + let svc: *mut AnyObject = msg_send![&*services, objectAtIndex: i]; + if svc.is_null() { + continue; + } + let cb_uuid: *mut AnyObject = msg_send![&*svc, UUID]; + if cb_uuid.is_null() { + continue; + } + if cbuuid_matches(cb_uuid, uuid) { + return Some(svc); + } + } + } + None +} + +unsafe fn find_char(service: *mut AnyObject, uuid: Uuid) -> Option<*mut AnyObject> { + if service.is_null() { + return None; + } + unsafe { + let chars: *mut AnyObject = msg_send![&*service, characteristics]; + if chars.is_null() { + return None; + } + let count: usize = msg_send![&*chars, count]; + for i in 0..count { + let ch: *mut AnyObject = msg_send![&*chars, objectAtIndex: i]; + if ch.is_null() { + continue; + } + let cb_uuid: *mut AnyObject = msg_send![&*ch, UUID]; + if cb_uuid.is_null() { + continue; + } + if cbuuid_matches(cb_uuid, uuid) { + return Some(ch); + } + } + } + None +} + +/// CBUUID's `UUIDString` returns whichever form (16-bit short or 128-bit) +/// CB canonicalised to. +unsafe fn cbuuid_matches(cb_uuid: *mut AnyObject, target: Uuid) -> bool { + unsafe { + let s_obj: *mut AnyObject = msg_send![&*cb_uuid, UUIDString]; + if s_obj.is_null() { + return false; + } + let s = nsstring_to_string(s_obj); + if let Ok(parsed) = Uuid::parse_str(&s) { + return parsed == target; + } + if let Ok(expanded) = expand_short_uuid(&s) { + return expanded == target; + } + } + false +} + +fn expand_short_uuid(s: &str) -> Result { + let hex = s.trim(); + match hex.len() { + 4 => { + let v = u16::from_str_radix(hex, 16).map_err(|_| ())?; + Uuid::parse_str(&format!("0000{v:04x}-0000-1000-8000-00805f9b34fb")).map_err(|_| ()) + } + 8 => { + let v = u32::from_str_radix(hex, 16).map_err(|_| ())?; + Uuid::parse_str(&format!("{v:08x}-0000-1000-8000-00805f9b34fb")).map_err(|_| ()) + } + _ => Err(()), + } +} + +unsafe fn peripheral_identifier(peripheral: *mut AnyObject) -> String { + if peripheral.is_null() { + return String::new(); + } + unsafe { + let id_obj: *mut AnyObject = msg_send![&*peripheral, identifier]; + if id_obj.is_null() { + return String::new(); + } + let uuid_str: *mut AnyObject = msg_send![&*id_obj, UUIDString]; + nsstring_to_string(uuid_str) + } +} + +unsafe fn characteristic_value_bytes(characteristic: *mut AnyObject) -> Vec { + if characteristic.is_null() { + return Vec::new(); + } + unsafe { + let value: *mut AnyObject = msg_send![&*characteristic, value]; + if value.is_null() { + return Vec::new(); + } + let len: usize = msg_send![&*value, length]; + if len == 0 { + return Vec::new(); + } + let ptr: *const std::ffi::c_void = msg_send![&*value, bytes]; + if ptr.is_null() { + return Vec::new(); + } + std::slice::from_raw_parts(ptr as *const u8, len).to_vec() + } +} + +unsafe fn nserror_message(err: *mut AnyObject) -> String { + if err.is_null() { + return String::new(); + } + unsafe { + let desc: *mut AnyObject = msg_send![&*err, localizedDescription]; + nsstring_to_string(desc) + } +} + +unsafe fn nsstring_to_string(s: *mut AnyObject) -> String { + if s.is_null() { + return String::new(); + } + unsafe { + let utf8: *const std::ffi::c_char = msg_send![&*s, UTF8String]; + let len: usize = msg_send![&*s, lengthOfBytesUsingEncoding: 4usize]; + if utf8.is_null() || len == 0 { + return String::new(); + } + let bytes = std::slice::from_raw_parts(utf8 as *const u8, len); + String::from_utf8_lossy(bytes).into_owned() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expand_short_uuid_round_trip_16bit() { + let u = expand_short_uuid("180D").expect("must parse"); + assert_eq!( + u, + Uuid::parse_str("0000180d-0000-1000-8000-00805f9b34fb").unwrap() + ); + } + + #[test] + fn expand_short_uuid_round_trip_32bit() { + let u = expand_short_uuid("0000180D").expect("must parse"); + assert_eq!( + u, + Uuid::parse_str("0000180d-0000-1000-8000-00805f9b34fb").unwrap() + ); + } + + #[test] + fn expand_short_uuid_rejects_unsupported_lengths() { + assert!(expand_short_uuid("180").is_err()); + assert!(expand_short_uuid("zzzz").is_err()); + assert!(expand_short_uuid("").is_err()); + } + + #[test] + fn pending_install_and_resolve_round_trip() { + let _ = pending().lock().unwrap().drain(); + let mut rx = install_pending("test-addr", CallbackKind::Connect); + resolve_pending("test-addr", CallbackKind::Connect, Ok(())); + let got = rx.try_recv().unwrap(); + assert!(got.is_ok()); + } + + #[test] + fn pending_resolve_unknown_is_silent_noop() { + resolve_pending("nope", CallbackKind::Notify, Err("ignored".into())); + } + + #[test] + fn classify_rotation_via_localized_description() { + let r = classify_disconnect_reason(Some("The connection has timed out unexpectedly.")); + assert_eq!(r, DisconnectReason::Rotation); + } + + #[test] + fn classify_rotation_via_cb_error_constant() { + let r = + classify_disconnect_reason(Some("CBErrorPeripheralConnectionTimeout: connection lost")); + assert_eq!(r, DisconnectReason::Rotation); + } + + #[test] + fn classify_rotation_is_case_insensitive() { + let r = classify_disconnect_reason(Some("TIMED OUT UNEXPECTEDLY")); + assert_eq!(r, DisconnectReason::Rotation); + } + + #[test] + fn classify_rotation_via_specified_device_disconnected() { + let r = classify_disconnect_reason(Some("The specified device has disconnected from us.")); + assert_eq!(r, DisconnectReason::Rotation); + } + + #[test] + fn classify_other_error_fallthrough() { + assert_eq!( + classify_disconnect_reason(Some("Bluetooth radio off")), + DisconnectReason::OtherError + ); + assert_eq!( + classify_disconnect_reason(None), + DisconnectReason::OtherError + ); + } + + #[test] + fn last_disconnect_reason_round_trip() { + let _ = last_disconnect_reason().lock().unwrap().drain(); + last_disconnect_reason() + .lock() + .unwrap() + .insert("addr-x".into(), DisconnectReason::Rotation); + let got = take_last_disconnect_reason("addr-x"); + assert_eq!(got, Some(DisconnectReason::Rotation)); + assert_eq!(take_last_disconnect_reason("addr-x"), None); + } +} diff --git a/crates/rns-interface/src/ble_central_lifecycle.rs b/crates/rns-interface/src/ble_central_lifecycle.rs new file mode 100644 index 0000000..925f88b --- /dev/null +++ b/crates/rns-interface/src/ble_central_lifecycle.rs @@ -0,0 +1,487 @@ +//! BLE central (scan) lifecycle. `PlatformUnavailable` rewinds active states +//! to `StartingWaitingPlatform` so scanning resumes after a Bluetooth toggle. + +use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::time::Instant; +use uuid::Uuid; + +/// Which GATT service a peer advertises (adapter reports the primary it saw). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum AdvertisedProtocol { + Ratspeak, + Columba, +} + +/// `identifier` is platform-stable (Apple UUIDString, bluer D-Bus path, Android MAC). +#[derive(Debug, Clone)] +pub struct DiscoveryEvent { + pub identifier: String, + pub rssi: i16, + pub services: Vec, + pub protocol: AdvertisedProtocol, + pub seen_at: Instant, +} + +/// Classify ad services. Ratspeak beats Columba when both advertised. +pub fn classify_protocol( + services: &[Uuid], + ratspeak_uuid: Uuid, + columba_uuid: Uuid, +) -> Option { + if services.contains(&ratspeak_uuid) { + Some(AdvertisedProtocol::Ratspeak) + } else if services.contains(&columba_uuid) { + Some(AdvertisedProtocol::Columba) + } else { + None + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum CentralState { + Idle, + /// `start_scan` issued; awaiting `CBManagerState == PoweredOn` etc. + StartingWaitingPlatform, + Scanning, + /// `stop_scan` issued; awaiting platform ack (synthetic on Apple where + /// stopScan is synchronous, real on bluer). + StoppingScan, + /// Cleanly torn down. Distinct from `Idle` for telemetry. + Stopped, + /// Bluetooth unsupported / permission denied; requires explicit `Reset`. + Failed, +} + +impl CentralState { + pub fn is_active(self) -> bool { + !matches!(self, Self::Idle | Self::Stopped | Self::Failed) + } + + pub fn is_starting(self) -> bool { + matches!(self, Self::StartingWaitingPlatform) + } + + pub fn is_scanning(self) -> bool { + matches!(self, Self::Scanning) + } + + pub fn is_stopping(self) -> bool { + matches!(self, Self::StoppingScan) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CentralEvent { + StartRequested, + /// Platform ready: adapter calls `scanForPeripheralsWithServices` here. + PlatformReady, + /// Active states rewind to `StartingWaitingPlatform` so recovery + /// resumes scanning. + PlatformUnavailable { + reason: String, + }, + StopRequested, + /// `stopScan` completed (synthetic on Apple where it's synchronous). + ScanStopped, + FatalError { + reason: String, + }, + Reset, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CentralTransitionError { + pub from: CentralState, + pub event: CentralEvent, +} + +impl std::fmt::Display for CentralTransitionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "invalid BLE central lifecycle transition: event {:?} is not valid from state {:?}", + self.event, self.from + ) + } +} + +impl std::error::Error for CentralTransitionError {} + +/// Idempotent re-requests return `Ok` with state unchanged. +pub fn transition( + state: CentralState, + event: &CentralEvent, +) -> Result { + use CentralEvent::*; + use CentralState::*; + + if let FatalError { .. } = event { + return Ok(Failed); + } + + let next = match (state, event) { + (Idle, StartRequested) => StartingWaitingPlatform, + (Stopped, StartRequested) => StartingWaitingPlatform, + (StartingWaitingPlatform, PlatformReady) => Scanning, + + (Scanning, StopRequested) => StoppingScan, + (StartingWaitingPlatform, StopRequested) => Stopped, + (StoppingScan, ScanStopped) => Stopped, + (Stopped, Reset) => Idle, + + (Scanning, PlatformUnavailable { .. }) => StartingWaitingPlatform, + (StartingWaitingPlatform, PlatformUnavailable { .. }) => StartingWaitingPlatform, + + (Failed, Reset) => Idle, + + (StartingWaitingPlatform | Scanning, StartRequested) => state, + (Idle | Stopped | StoppingScan, StopRequested) => state, + (Idle, Reset) => Idle, + + _ => { + return Err(CentralTransitionError { + from: state, + event: event.clone(), + }); + } + }; + + Ok(next) +} + +pub struct CentralLifecycle { + state: Mutex, +} + +impl CentralLifecycle { + pub fn new() -> Self { + Self { + state: Mutex::new(CentralState::Idle), + } + } + + pub fn current(&self) -> CentralState { + *self.lock().expect("poisoned") + } + + pub fn apply(&self, event: CentralEvent) -> Result { + let mut guard = self.lock().expect("poisoned"); + let next = transition(*guard, &event)?; + *guard = next; + Ok(next) + } + + pub fn is_scanning(&self) -> bool { + matches!(self.current(), CentralState::Scanning) + } + + fn lock( + &self, + ) -> Result, PoisonError>> { + self.state.lock() + } +} + +impl Default for CentralLifecycle { + fn default() -> Self { + Self::new() + } +} + +impl std::fmt::Debug for CentralLifecycle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CentralLifecycle") + .field("state", &self.current()) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn unavail(reason: &str) -> CentralEvent { + CentralEvent::PlatformUnavailable { + reason: reason.into(), + } + } + + fn fatal(reason: &str) -> CentralEvent { + CentralEvent::FatalError { + reason: reason.into(), + } + } + + fn drive(start: CentralState, events: &[CentralEvent]) -> CentralState { + let lc = CentralLifecycle { + state: Mutex::new(start), + }; + for e in events { + lc.apply(e.clone()) + .unwrap_or_else(|err| panic!("transition failed: {err}")); + } + lc.current() + } + + // ---- Happy-path transitions ---- + + #[test] + fn full_start_cycle_reaches_scanning() { + let final_state = drive( + CentralState::Idle, + &[CentralEvent::StartRequested, CentralEvent::PlatformReady], + ); + assert_eq!(final_state, CentralState::Scanning); + } + + #[test] + fn full_stop_cycle_reaches_stopped() { + let final_state = drive( + CentralState::Scanning, + &[CentralEvent::StopRequested, CentralEvent::ScanStopped], + ); + assert_eq!(final_state, CentralState::Stopped); + } + + #[test] + fn stopped_can_start_again() { + let final_state = drive( + CentralState::Stopped, + &[ + CentralEvent::Reset, + CentralEvent::StartRequested, + CentralEvent::PlatformReady, + ], + ); + assert_eq!(final_state, CentralState::Scanning); + } + + // ---- Teardown sequencing ---- + + #[test] + fn stop_request_alone_does_not_reach_stopped_from_scanning() { + // Apple's stopScan is synchronous, but the machine still requires + // an explicit ScanStopped for symmetry with async backends. + let lc = CentralLifecycle::new(); + lc.apply(CentralEvent::StartRequested).unwrap(); + lc.apply(CentralEvent::PlatformReady).unwrap(); + assert_eq!(lc.current(), CentralState::Scanning); + lc.apply(CentralEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), CentralState::StoppingScan); + let err = lc.apply(CentralEvent::Reset); + assert!(err.is_err()); + assert_eq!(lc.current(), CentralState::StoppingScan); + } + + #[test] + fn stop_before_platform_ready_reaches_stopped_immediately() { + let final_state = drive( + CentralState::StartingWaitingPlatform, + &[CentralEvent::StopRequested], + ); + assert_eq!(final_state, CentralState::Stopped); + } + + // ---- Platform availability ---- + + #[test] + fn bluetooth_off_mid_scan_rewinds_to_waiting_platform() { + let final_state = drive(CentralState::Scanning, &[unavail("bluetooth off")]); + assert_eq!(final_state, CentralState::StartingWaitingPlatform); + } + + #[test] + fn bluetooth_recovery_cycle_returns_to_scanning() { + let final_state = drive( + CentralState::Scanning, + &[unavail("bluetooth off"), CentralEvent::PlatformReady], + ); + assert_eq!(final_state, CentralState::Scanning); + } + + #[test] + fn double_unavailable_while_waiting_is_idempotent() { + let final_state = drive( + CentralState::StartingWaitingPlatform, + &[unavail("resetting"), unavail("resetting")], + ); + assert_eq!(final_state, CentralState::StartingWaitingPlatform); + } + + // ---- Idempotency ---- + + #[test] + fn double_start_from_scanning_is_noop() { + let lc = CentralLifecycle::new(); + lc.apply(CentralEvent::StartRequested).unwrap(); + lc.apply(CentralEvent::PlatformReady).unwrap(); + lc.apply(CentralEvent::StartRequested).unwrap(); + assert_eq!(lc.current(), CentralState::Scanning); + } + + #[test] + fn double_stop_while_stopping_is_noop() { + let lc = CentralLifecycle::new(); + lc.apply(CentralEvent::StartRequested).unwrap(); + lc.apply(CentralEvent::PlatformReady).unwrap(); + lc.apply(CentralEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), CentralState::StoppingScan); + lc.apply(CentralEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), CentralState::StoppingScan); + } + + #[test] + fn reset_from_idle_is_noop() { + let lc = CentralLifecycle::new(); + lc.apply(CentralEvent::Reset).unwrap(); + assert_eq!(lc.current(), CentralState::Idle); + } + + // ---- Fatal ---- + + #[test] + fn fatal_from_any_state_reaches_failed() { + for from in [ + CentralState::Idle, + CentralState::StartingWaitingPlatform, + CentralState::Scanning, + CentralState::StoppingScan, + CentralState::Stopped, + ] { + let final_state = drive(from, &[fatal("oom")]); + assert_eq!(final_state, CentralState::Failed, "from {from:?}"); + } + } + + #[test] + fn failed_requires_reset_to_restart() { + let lc = CentralLifecycle { + state: Mutex::new(CentralState::Failed), + }; + let err = lc + .apply(CentralEvent::StartRequested) + .expect_err("StartRequested from Failed must be rejected"); + assert_eq!(err.from, CentralState::Failed); + } + + #[test] + fn reset_from_failed_returns_to_idle() { + let final_state = drive(CentralState::Failed, &[CentralEvent::Reset]); + assert_eq!(final_state, CentralState::Idle); + } + + // ---- Invalid transitions ---- + + #[test] + fn platform_ready_from_idle_is_rejected() { + let lc = CentralLifecycle::new(); + let err = lc + .apply(CentralEvent::PlatformReady) + .expect_err("PlatformReady from Idle must be rejected"); + assert_eq!(err.from, CentralState::Idle); + assert_eq!(lc.current(), CentralState::Idle); + } + + #[test] + fn scan_stopped_from_idle_is_rejected() { + let lc = CentralLifecycle::new(); + assert!(lc.apply(CentralEvent::ScanStopped).is_err()); + } + + #[test] + fn predicates_match_intuition() { + assert!(!CentralState::Idle.is_active()); + assert!(CentralState::Scanning.is_active()); + assert!(CentralState::Scanning.is_scanning()); + assert!(CentralState::StartingWaitingPlatform.is_starting()); + assert!(CentralState::StoppingScan.is_stopping()); + + let lc = CentralLifecycle::new(); + assert!(!lc.is_scanning()); + lc.apply(CentralEvent::StartRequested).unwrap(); + lc.apply(CentralEvent::PlatformReady).unwrap(); + assert!(lc.is_scanning()); + } + + // ---- End-to-end scenarios for the iOS / macOS adapter ---- + + #[test] + fn full_enable_disable_enable_cycle_ends_idle_ready_to_scan() { + let lc = CentralLifecycle::new(); + lc.apply(CentralEvent::StartRequested).unwrap(); + lc.apply(CentralEvent::PlatformReady).unwrap(); + assert_eq!(lc.current(), CentralState::Scanning); + lc.apply(CentralEvent::StopRequested).unwrap(); + lc.apply(CentralEvent::ScanStopped).unwrap(); + lc.apply(CentralEvent::Reset).unwrap(); + lc.apply(CentralEvent::StartRequested).unwrap(); + lc.apply(CentralEvent::PlatformReady).unwrap(); + assert_eq!(lc.current(), CentralState::Scanning); + } + + // ---- Protocol classification ---- + + fn ratspeak_uuid() -> Uuid { + Uuid::from_u128(0xa1b2c3d4_e5f6_4a5b_8c9d_0e1f2a3b4c5d) + } + fn columba_uuid() -> Uuid { + Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42c5da28e3) + } + fn unrelated_uuid() -> Uuid { + Uuid::from_u128(0xdead_dead_dead_dead_dead_dead_dead_dead) + } + + #[test] + fn classify_picks_ratspeak_over_columba_when_both_advertised() { + let services = vec![ratspeak_uuid(), columba_uuid()]; + let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid()); + assert_eq!(got, Some(AdvertisedProtocol::Ratspeak)); + } + + #[test] + fn classify_returns_ratspeak_when_only_ratspeak_present() { + let services = vec![ratspeak_uuid()]; + let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid()); + assert_eq!(got, Some(AdvertisedProtocol::Ratspeak)); + } + + #[test] + fn classify_returns_columba_when_only_columba_present() { + let services = vec![columba_uuid()]; + let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid()); + assert_eq!(got, Some(AdvertisedProtocol::Columba)); + } + + #[test] + fn classify_returns_none_when_neither_present() { + let services = vec![unrelated_uuid()]; + let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid()); + assert_eq!(got, None); + } + + #[test] + fn classify_returns_none_on_empty_ad() { + let got = classify_protocol(&[], ratspeak_uuid(), columba_uuid()); + assert_eq!(got, None); + } + + #[test] + fn classify_ignores_unrelated_services_mixed_in() { + let services = vec![unrelated_uuid(), columba_uuid(), unrelated_uuid()]; + let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid()); + assert_eq!(got, Some(AdvertisedProtocol::Columba)); + } + + #[test] + fn platform_unavailable_during_scan_rewinds_and_recovers_automatically() { + let lc = CentralLifecycle::new(); + lc.apply(CentralEvent::StartRequested).unwrap(); + lc.apply(CentralEvent::PlatformReady).unwrap(); + lc.apply(unavail("bluetooth off")).unwrap(); + assert_eq!(lc.current(), CentralState::StartingWaitingPlatform); + lc.apply(unavail("resetting")).unwrap(); + assert_eq!(lc.current(), CentralState::StartingWaitingPlatform); + lc.apply(CentralEvent::PlatformReady).unwrap(); + assert_eq!(lc.current(), CentralState::Scanning); + } +} diff --git a/crates/rns-interface/src/ble_peer.rs b/crates/rns-interface/src/ble_peer.rs new file mode 100644 index 0000000..34ada00 --- /dev/null +++ b/crates/rns-interface/src/ble_peer.rs @@ -0,0 +1,5981 @@ +//! BLE Peer-to-Peer mesh interface. Each device acts as both Central +//! (scanner/GATT client) and Peripheral (advertiser/GATT server) +//! simultaneously. +//! +//! ## Dual-service GATT +//! +//! ### Ratspeak (primary) +//! - Service: `a1b2c3d4-e5f6-4a5b-8c9d-0e1f2a3b4c5d` +//! - RX: `…4c5e` (WRITE, WRITE_NO_RESPONSE) +//! - TX: `…4c5f` (READ, NOTIFY) +//! - ID: `…4c60` (READ) — 16-byte identity hash +//! +//! ### Columba (cross-app compat) +//! - Service: `37145b00-442d-4a94-917f-8f42c5da28e3` +//! - RX: `…28e5` (WRITE, WRITE_NO_RESPONSE) +//! - TX: `…28e4` (READ, NOTIFY, INDICATE) +//! - ID: `…28e6` (READ) +//! +//! ## Fragmentation +//! +//! Packets larger than (MTU - 3) use a 5-byte header +//! `[type:1][seq:2-BE][total:2-BE]`. Types: LONE / START / CONTINUE / END. +//! Reassembly timeout 30s. +//! +//! Keepalive: 15s interval, 1-byte ping; 3 misses → disconnect. Cap 7 +//! simultaneous peers. + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use tokio::sync::mpsc; +use uuid::Uuid; + +use crate::traits::{ + InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode, +}; +use rns_transport::messages::TransportMessage; + +// Peer writes RX, we notify TX, ID is hash. +pub const RATSPEAK_SERVICE_UUID: Uuid = Uuid::from_u128(0xa1b2c3d4_e5f6_4a5b_8c9d_0e1f2a3b4c5d); +pub const RATSPEAK_RX_UUID: Uuid = Uuid::from_u128(0xa1b2c3d4_e5f6_4a5b_8c9d_0e1f2a3b4c5e); +pub const RATSPEAK_TX_UUID: Uuid = Uuid::from_u128(0xa1b2c3d4_e5f6_4a5b_8c9d_0e1f2a3b4c5f); +pub const RATSPEAK_ID_UUID: Uuid = Uuid::from_u128(0xa1b2c3d4_e5f6_4a5b_8c9d_0e1f2a3b4c60); + +// Same shape with different UUIDs. +pub const COLUMBA_SERVICE_UUID: Uuid = Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42c5da28e3); +pub const COLUMBA_TX_UUID: Uuid = Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42c5da28e4); +pub const COLUMBA_RX_UUID: Uuid = Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42c5da28e5); +pub const COLUMBA_ID_UUID: Uuid = Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42c5da28e6); + +pub const MAX_PEERS: usize = 7; +pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15); +pub const KEEPALIVE_MAX_MISSES: u32 = 3; +pub const FRAGMENT_TIMEOUT: Duration = Duration::from_secs(30); +pub const MIN_RSSI: i16 = -85; +pub const SCAN_ACTIVE_INTERVAL: Duration = Duration::from_secs(5); +pub const SCAN_IDLE_INTERVAL: Duration = Duration::from_secs(30); + +/// Recently-disconnected peers stay "wanted" — scan loop uses the active +/// interval for them until they reconnect or the entry expires. +pub const RECONNECT_BACKOFF_FAILURES: u32 = 3; +pub const RECONNECT_BACKOFF_DURATION: Duration = Duration::from_secs(300); +pub const RECONNECT_PRUNE_AFTER: Duration = Duration::from_secs(600); + +/// `(disconnect_time, consecutive_failure_count)` keyed by identity hex. +pub type RecentlyDisconnected = Arc>>; + +pub fn new_recently_disconnected() -> RecentlyDisconnected { + Arc::new(std::sync::Mutex::new(HashMap::new())) +} + +/// Seeded entries start at `(now, 0)` — candidate, not in backoff. +pub fn seed_recently_disconnected(map: &RecentlyDisconnected, identities: Vec) { + if identities.is_empty() { + return; + } + if let Ok(mut guard) = map.lock() { + let now = Instant::now(); + for id in identities { + guard.entry(id).or_insert((now, 0)); + } + } +} + +/// All-zero is the sentinel ("no identity yet") and must never reach +/// advertising. +pub fn is_valid_identity_hash(bytes: &[u8]) -> bool { + bytes.len() == 16 && bytes.iter().any(|b| *b != 0) +} + +/// Long enough to absorb transport store-and-forward jitter; short enough +/// that legitimate retransmits eventually reach the original sender. +pub const ANTI_LOOP_TTL: Duration = Duration::from_secs(30); + +/// `payload_hash → (sources, first_seen)`. Lets the fan-out skip echoing +/// a packet back to the peers it arrived from. +pub type AntiLoopMap = + Arc, Instant)>>>; + +pub fn new_anti_loop_map() -> AntiLoopMap { + Arc::new(std::sync::Mutex::new(HashMap::new())) +} + +fn payload_hash(data: &[u8]) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + data.hash(&mut h); + h.finish() +} + +/// A second call from the same source within `ANTI_LOOP_TTL` refreshes the timestamp. +pub fn anti_loop_record(map: &AntiLoopMap, source: String, payload: &[u8]) { + let h = payload_hash(payload); + if let Ok(mut g) = map.lock() { + let entry = g + .entry(h) + .or_insert_with(|| (std::collections::HashSet::new(), Instant::now())); + entry.0.insert(source); + entry.1 = Instant::now(); + } +} + +/// false iff `dest` is one of the peers `payload` arrived from. +pub fn anti_loop_should_send(map: &AntiLoopMap, dest: &str, payload: &[u8]) -> bool { + let h = payload_hash(payload); + if let Ok(g) = map.lock() + && let Some((srcs, t)) = g.get(&h) + && t.elapsed() < ANTI_LOOP_TTL + && srcs.contains(dest) + { + return false; + } + true +} + +pub fn anti_loop_prune(map: &AntiLoopMap) { + if let Ok(mut g) = map.lock() { + g.retain(|_, (_, t)| t.elapsed() < ANTI_LOOP_TTL); + } +} + +fn reconnect_in_backoff(map: &RecentlyDisconnected, identity_hex: &str) -> bool { + if let Ok(guard) = map.lock() + && let Some((when, fails)) = guard.get(identity_hex) + { + return *fails >= RECONNECT_BACKOFF_FAILURES && when.elapsed() < RECONNECT_BACKOFF_DURATION; + } + false +} + +fn record_disconnect(map: &RecentlyDisconnected, identity_hex: &str) { + if let Ok(mut guard) = map.lock() { + guard + .entry(identity_hex.to_string()) + .and_modify(|(when, _)| *when = Instant::now()) + .or_insert((Instant::now(), 0)); + } +} + +fn record_reconnect_failure(map: &RecentlyDisconnected, identity_hex: &str) { + if let Ok(mut guard) = map.lock() { + guard + .entry(identity_hex.to_string()) + .and_modify(|(when, fails)| { + *when = Instant::now(); + *fails = fails.saturating_add(1); + }) + .or_insert((Instant::now(), 1)); + } +} + +fn record_reconnect_success(map: &RecentlyDisconnected, identity_hex: &str) { + if let Ok(mut guard) = map.lock() { + guard.remove(identity_hex); + } +} + +/// iOS-rotated CBPeripheral.identifier whose advertising address moved — +/// seed at the backoff threshold so later scan cycles skip it instead of +/// burning another 5s connect timeout. Apple-only because the caller path +/// is gated on Apple BLE central plumbing (`ble_central_apple_connect`). +#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] +fn record_connect_timeout_ghost(map: &RecentlyDisconnected, address: &str) { + if let Ok(mut guard) = map.lock() { + guard.insert( + address.to_string(), + (Instant::now(), RECONNECT_BACKOFF_FAILURES), + ); + } +} + +/// Drop the entry on RPA-rotation disconnects so the next scan reconnects +/// without backoff drag. Apple-only — RPA rotation is a CoreBluetooth +/// concept (`DisconnectReason::Rotation`). +#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] +fn record_rotation_disconnect(map: &RecentlyDisconnected, address: &str) { + if let Ok(mut guard) = map.lock() { + guard.remove(address); + } +} + +fn prune_recently_disconnected(map: &RecentlyDisconnected) { + if let Ok(mut guard) = map.lock() { + guard.retain(|_, (when, _)| when.elapsed() < RECONNECT_PRUNE_AFTER); + } +} + +/// True if any entry is still "wanted" — not pruned and not in backoff. +fn has_wanted_reconnects(map: &RecentlyDisconnected) -> bool { + if let Ok(guard) = map.lock() { + guard.iter().any(|(_, (when, fails))| { + when.elapsed() < RECONNECT_PRUNE_AFTER + && (*fails < RECONNECT_BACKOFF_FAILURES + || when.elapsed() >= RECONNECT_BACKOFF_DURATION) + }) + } else { + false + } +} + +/// Already-connected peers stay alive via keepalive. +pub const SCAN_BACKGROUND_INTERVAL: Duration = Duration::from_secs(60); + +const SCAN_SLEEP_SLICE: Duration = Duration::from_secs(2); + +/// Exits early on foreground-resume or `wake` notify. +async fn scan_sleep( + total: Duration, + foreground: &Arc, + was_foreground: bool, + wake: &Arc, +) { + if was_foreground { + tokio::select! { + _ = tokio::time::sleep(total) => {} + _ = wake.notified() => {} + } + return; + } + let deadline = std::time::Instant::now() + total; + loop { + let now = std::time::Instant::now(); + if now >= deadline { + return; + } + let remaining = (deadline - now).min(SCAN_SLEEP_SLICE); + tokio::select! { + _ = tokio::time::sleep(remaining) => {} + _ = wake.notified() => return, + } + if foreground.load(Ordering::Relaxed) { + return; + } + } +} + +/// BLE 5.0 max. +pub const TARGET_MTU: u16 = 517; + +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FragmentType { + Lone = 0x00, + Start = 0x01, + Continue = 0x02, + End = 0x03, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct BlePeer { + /// 16-byte hex Reticulum identity hash. + pub identity_hash: String, + /// May rotate on Android. + pub ble_address: String, + pub rssi: i16, + pub protocol: PeerProtocol, + pub connected: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum PeerProtocol { + Ratspeak, + Columba, +} + +/// Surfaces as `ble_peer_*` events for embedding UIs. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum BlePeerEvent { + Discovered { + address: String, + rssi: i16, + protocol: PeerProtocol, + }, + Connected { + address: String, + identity_hash: String, + protocol: PeerProtocol, + }, + Disconnected { + address: String, + reason: String, + }, + /// Notify pipe wired — subscribed-to-TX completed on either side. + /// Embedding UIs can fire an immediate announce on this so identity + /// exchange happens on first contact rather than waiting for auto-announce. + SubscribeReady { + address: String, + }, + /// Identity hash learned from the first signed Reticulum announce. + /// Used to dedup peers across central+peripheral roles where the BLE + /// address differs for the same physical device — notably on Apple, + /// where `CBPeripheral.identifier` vs `CBCentral.identifier` don't + /// match without bonding. + IdentityResolved { + address: String, + identity_hash: String, + }, + RssiUpdate { + address: String, + rssi: i16, + }, + /// Peripheral role failed to start (e.g. Windows without packaged-app + /// identity). Mesh continues central-only. + PeripheralUnavailable { + reason: String, + }, + StatusChanged { + state: PeerState, + peer_count: usize, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PeerState { + Off, + Starting, + On, + PermissionNeeded, + BluetoothOff, + Unavailable, +} + +/// Lets sync JNI/ObjC callbacks publish without threading senders through +/// every site. Replaced at each spawn. +static EVENT_DISPATCH: std::sync::OnceLock>>> = + std::sync::OnceLock::new(); + +fn event_dispatch_slot() -> &'static std::sync::RwLock>> { + EVENT_DISPATCH.get_or_init(|| std::sync::RwLock::new(None)) +} + +/// Replaces any previous installation. +pub fn install_event_dispatcher(tx: mpsc::Sender) { + if let Ok(mut slot) = event_dispatch_slot().write() { + *slot = Some(tx); + } +} + +pub fn clear_event_dispatcher() { + if let Ok(mut slot) = event_dispatch_slot().write() { + *slot = None; + } +} + +/// `try_send` — sync callbacks must not block. A drop here means the relay +/// channel is full, which on tight Rust scan loops (Windows central path) +/// can happen during burst events. Log so we see it instead of state silently +/// going stale (e.g. UI stuck "Scanning…" because a Connected was dropped). +pub(crate) fn dispatch_event(event: BlePeerEvent) { + if let Ok(slot) = event_dispatch_slot().read() + && let Some(tx) = slot.as_ref() + && let Err(e) = tx.try_send(event) + { + tracing::warn!( + error = %e, + "BLE peer event dispatch dropped — relay channel full or closed" + ); + } +} + +/// `false` means the radio truly stops, not just the TX channel dropping. +static BLE_PEER_RUNNING: std::sync::OnceLock> = std::sync::OnceLock::new(); + +pub(crate) fn running_flag() -> Arc { + BLE_PEER_RUNNING + .get_or_init(|| Arc::new(AtomicBool::new(false))) + .clone() +} + +/// Called from the spawn path so a previous teardown doesn't poison boot. +pub(crate) fn mark_running() { + running_flag().store(true, Ordering::SeqCst); +} + +/// Caller must still `DeregisterInterface` on the transport actor to drop +/// paths + remove the interface entry. +pub async fn stop_ble_peer_interface() { + tracing::info!("stop_ble_peer_interface: signalling shutdown + stopping peripheral"); + running_flag().store(false, Ordering::SeqCst); + if let Err(e) = stop_peripheral().await { + tracing::warn!(error = %e, "BLE peer: stop_peripheral failed during teardown"); + } else { + tracing::info!("stop_ble_peer_interface: peripheral stopped"); + } + clear_event_dispatcher(); + tracing::info!("stop_ble_peer_interface: done"); +} + +#[derive(Debug, Clone)] +pub struct BlePeerConfig { + pub name: String, + /// 16-byte Reticulum identity hash for this node. + pub identity_hash: Vec, + pub mode: InterfaceMode, +} + +impl BlePeerConfig { + pub fn new(name: &str, identity_hash: Vec) -> Self { + Self { + name: name.to_string(), + identity_hash, + mode: InterfaceMode::Full, + } + } +} + +pub fn fragment_packet(data: &[u8], mtu: usize) -> Vec> { + let payload_mtu = mtu.saturating_sub(5); // 5-byte header + if payload_mtu == 0 || data.len() <= mtu.saturating_sub(3) { + return vec![data.to_vec()]; + } + + let chunks: Vec<&[u8]> = data.chunks(payload_mtu).collect(); + let total = chunks.len() as u16; + let mut fragments = Vec::with_capacity(chunks.len()); + + for (i, chunk) in chunks.iter().enumerate() { + let ftype = if chunks.len() == 1 { + FragmentType::Lone + } else if i == 0 { + FragmentType::Start + } else if i == chunks.len() - 1 { + FragmentType::End + } else { + FragmentType::Continue + }; + + let seq = i as u16; + let mut frag = Vec::with_capacity(5 + chunk.len()); + frag.push(ftype as u8); + frag.extend_from_slice(&seq.to_be_bytes()); + frag.extend_from_slice(&total.to_be_bytes()); + frag.extend_from_slice(chunk); + fragments.push(frag); + } + + fragments +} + +pub fn reassemble_fragments(fragments: &[Vec]) -> Option> { + if fragments.is_empty() { + return None; + } + + let mut result = Vec::new(); + for frag in fragments { + if frag.len() < 5 { + return None; + } + result.extend_from_slice(&frag[5..]); + } + Some(result) +} + +/// 60s positive-ID cache for the btleplug scan path. WinRT's advertisement +/// parse is empirically eventually-consistent: the same iOS RPA can yield +/// services_count=1 in one 3s scan window and 0 in the next, even when iOS +/// is broadcasting continuously. Once we've classified an address as +/// Ratspeak/Columba, remembering it for a TTL > the inter-scan gap means a +/// flaky parse on the next sighting doesn't kick the peer out of recognition. +/// 60s is comfortably less than iOS's ~15-minute RPA rotation window, so +/// stale entries can't false-positive a different device. +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +const RECENT_PEER_TTL: Duration = Duration::from_secs(60); + +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +fn recent_ratspeak_cache() -> &'static std::sync::Mutex> { + static CACHE: std::sync::OnceLock>> = + std::sync::OnceLock::new(); + CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new())) +} + +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +fn recent_ratspeak_remember(address: &str, protocol: PeerProtocol) { + if let Ok(mut cache) = recent_ratspeak_cache().lock() { + cache.insert(address.to_string(), (Instant::now(), protocol)); + } +} + +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +fn recent_ratspeak_lookup(address: &str) -> Option { + let cache = recent_ratspeak_cache().lock().ok()?; + let (seen_at, protocol) = cache.get(address)?; + if seen_at.elapsed() < RECENT_PEER_TTL { + Some(*protocol) + } else { + None + } +} + +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +fn recent_ratspeak_prune() { + if let Ok(mut cache) = recent_ratspeak_cache().lock() { + cache.retain(|_, (t, _)| t.elapsed() < RECENT_PEER_TTL); + } +} + +// Apple goes through `crate::ble_central_apple` for `AllowDuplicatesKey=YES` +// (btleplug doesn't expose it, so peers "disappear" after a couple minutes). +// Linux/Windows/Android stay on btleplug. + +/// Scan for BLE mesh peers advertising Ratspeak or Columba. +/// +/// Creates a fresh btleplug adapter, so use this only for scan-only callers. +/// Scan-then-connect flows must use [`scan_mesh_peers_shared`] with the same +/// adapter they later pass to `connect_mesh_peer`; btleplug adapter instances +/// do not share peripheral registries. +/// +/// Safe entry point for one-off scan-only callers and the Apple branch +/// (which uses the native CoreBluetooth path). +pub async fn scan_mesh_peers(timeout_secs: u64) -> Result, String> { + #[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] + { + apple_scan_mesh_peers(timeout_secs).await + } + + #[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] + { + // On Android, btleplug must be initialized or global_adapter() will panic. + #[cfg(target_os = "android")] + if !crate::ble_rnode::is_btleplug_initialized() { + return Err( + "BLE not initialized on Android — grant Bluetooth permissions and restart".into(), + ); + } + + use btleplug::api::Manager as _; + use btleplug::platform::Manager; + + let manager = Manager::new() + .await + .map_err(|e| format!("BLE manager init failed: {e}"))?; + let adapters = manager + .adapters() + .await + .map_err(|e| format!("No BLE adapters: {e}"))?; + let adapter = adapters.into_iter().next().ok_or("No BLE adapter found")?; + return scan_mesh_peers_shared(&adapter, timeout_secs).await; + } + + #[cfg(not(feature = "ble"))] + Err("BLE feature not enabled".into()) +} + +/// Scan for BLE mesh peers using a caller-provided adapter. +/// +/// Scan with the adapter that will also be used for connect. +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +pub async fn scan_mesh_peers_shared( + adapter: &btleplug::platform::Adapter, + timeout_secs: u64, +) -> Result, String> { + use btleplug::api::{Central, Peripheral as _, ScanFilter}; + + // WinRT UUID filters miss real advertisements on common chipsets. Scan + // unfiltered and classify service UUIDs ourselves so discovery is visible. + adapter + .start_scan(ScanFilter::default()) + .await + .map_err(|e| format!("Scan failed: {e}"))?; + + tokio::time::sleep(Duration::from_secs(timeout_secs)).await; + adapter.stop_scan().await.ok(); + + let peripherals = adapter + .peripherals() + .await + .map_err(|e| format!("Peripheral list failed: {e}"))?; + + recent_ratspeak_prune(); + + let mut peers = Vec::new(); + for p in peripherals { + let Ok(Some(props)) = p.properties().await else { + continue; + }; + // RSSI is display-only here. BlueZ/WinRT often omit RSSI on cached + // peripherals, and service UUID plus link watchdogs are the real gates. + // -100 is a UI sentinel for "Unknown". + let rssi = props.rssi.unwrap_or(-100); + let address_str = props.address.to_string(); + + // WinRT populates `services` from the parsed advertisement payload, + // but its parse is eventually-consistent and frequently empty. + // `service_data` keys come from a separate parse path that often + // succeeds when `services` is empty. Check both. + let saw_ratspeak_now = props.services.contains(&RATSPEAK_SERVICE_UUID) + || props.service_data.contains_key(&RATSPEAK_SERVICE_UUID); + let saw_columba_now = props.services.contains(&COLUMBA_SERVICE_UUID) + || props.service_data.contains_key(&COLUMBA_SERVICE_UUID); + + if saw_ratspeak_now || saw_columba_now { + let proto = if saw_ratspeak_now { + PeerProtocol::Ratspeak + } else { + PeerProtocol::Columba + }; + recent_ratspeak_remember(&address_str, proto); + } + let cached = recent_ratspeak_lookup(&address_str); + let saw_ratspeak = saw_ratspeak_now || cached == Some(PeerProtocol::Ratspeak); + let saw_columba = saw_columba_now || cached == Some(PeerProtocol::Columba); + let from_cache = !saw_ratspeak_now && !saw_columba_now && cached.is_some(); + + tracing::info!( + target: "ble_trace", + step = "scan.peripheral_seen", + address = %props.address, + rssi, + services_count = props.services.len(), + service_data_keys = props.service_data.len(), + saw_ratspeak, + saw_columba, + from_cache, + local_name = ?props.local_name, + "BLE scan peripheral seen" + ); + + // No RSSI floor — see the comment above where `rssi` is + // captured. The UUID match below is the only connection gate. + if !saw_ratspeak && !saw_columba { + continue; + } + + peers.push(BlePeer { + // Identity is learned from the first signed announce. + identity_hash: String::new(), + ble_address: address_str, + rssi, + protocol: if saw_ratspeak { + PeerProtocol::Ratspeak + } else { + PeerProtocol::Columba + }, + connected: false, + }); + } + Ok(peers) +} + +/// Dedupes by peripheral identifier, keeps strongest RSSI. +#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] +async fn apple_scan_mesh_peers(timeout_secs: u64) -> Result, String> { + use crate::ble_central_apple; + + let services = vec![RATSPEAK_SERVICE_UUID, COLUMBA_SERVICE_UUID]; + let mut rx = ble_central_apple::start_scan(services).await?; + + let deadline = Instant::now() + Duration::from_secs(timeout_secs); + let mut seen: HashMap = HashMap::new(); + + while let Some(remaining) = deadline.checked_duration_since(Instant::now()) { + let event = match tokio::time::timeout(remaining, rx.recv()).await { + Err(_) | Ok(None) => break, + Ok(Some(ev)) => ev, + }; + merge_sighting(&mut seen, event); + } + + // Best-effort — lifecycle rewinds on next toggle if this fails. + if let Err(e) = ble_central_apple::stop_scan().await { + tracing::warn!("Apple BLE scan teardown warning: {e}"); + } + + let peers: Vec = seen.into_values().collect(); + tracing::info!( + target: "ble_trace", + step = "scan.cycle_summary", + peer_count = peers.len(), + peers = ?peers.iter().map(|p| format!("{}@{}dBm/{:?}", p.ble_address, p.rssi, p.protocol)).collect::>(), + "Apple BLE scan cycle complete" + ); + Ok(peers) +} + +/// Drops weaker-than-[`MIN_RSSI`]; keeps strongest RSSI per peer; upgrades +/// Columba → Ratspeak but never the reverse. Used by Apple's +/// `apple_scan_mesh_peers` (Apple-only) and by `sighting_tests` (all +/// platforms when `cfg(test, feature = "ble")`); on a Linux/Windows +/// release build neither caller is compiled, so the compiler reports +/// it dead — the allow keeps the function available for both contexts. +#[cfg(feature = "ble")] +#[allow(dead_code)] +fn merge_sighting( + seen: &mut HashMap, + event: crate::ble_central_lifecycle::DiscoveryEvent, +) { + use crate::ble_central_lifecycle::AdvertisedProtocol; + + if event.rssi < MIN_RSSI { + return; + } + let protocol = match event.protocol { + AdvertisedProtocol::Ratspeak => PeerProtocol::Ratspeak, + AdvertisedProtocol::Columba => PeerProtocol::Columba, + }; + seen.entry(event.identifier.clone()) + .and_modify(|p| { + if event.rssi > p.rssi { + p.rssi = event.rssi; + } + if matches!(protocol, PeerProtocol::Ratspeak) { + p.protocol = PeerProtocol::Ratspeak; + } + }) + .or_insert_with(|| BlePeer { + // Identity is learned from the first signed announce after a + // GATT link opens. + identity_hash: String::new(), + ble_address: event.identifier.clone(), + rssi: event.rssi, + protocol, + connected: false, + }); +} + +#[cfg(all(test, feature = "ble"))] +mod sighting_tests { + use super::*; + use crate::ble_central_lifecycle::{AdvertisedProtocol, DiscoveryEvent}; + use std::time::Instant; + + fn mk( + ident: &str, + rssi: i16, + protocol: AdvertisedProtocol, + services: Vec, + ) -> DiscoveryEvent { + DiscoveryEvent { + identifier: ident.into(), + rssi, + services, + protocol, + seen_at: Instant::now(), + } + } + + #[test] + fn empty_input_produces_empty_map() { + let seen: HashMap = HashMap::new(); + assert_eq!(seen.len(), 0); + } + + #[test] + fn single_ratspeak_sighting_is_inserted() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + -60, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + assert_eq!(seen.len(), 1); + let p = seen.get("AABB").unwrap(); + assert_eq!(p.ble_address, "AABB"); + assert_eq!(p.rssi, -60); + assert_eq!(p.protocol, PeerProtocol::Ratspeak); + assert!(!p.connected); + assert!(p.identity_hash.is_empty()); + } + + #[test] + fn below_min_rssi_is_dropped() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + MIN_RSSI - 1, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + assert!(seen.is_empty(), "weak sighting must not produce a peer"); + } + + #[test] + fn rssi_strengthens_on_subsequent_sighting() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + -80, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + merge_sighting( + &mut seen, + mk( + "AABB", + -55, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + assert_eq!(seen.get("AABB").unwrap().rssi, -55); + } + + #[test] + fn rssi_does_not_weaken_on_subsequent_sighting() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + -55, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + merge_sighting( + &mut seen, + mk( + "AABB", + -85, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + assert_eq!( + seen.get("AABB").unwrap().rssi, + -55, + "strongest RSSI must stick even after a weaker sighting" + ); + } + + #[test] + fn columba_upgrades_to_ratspeak_when_both_seen() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + -60, + AdvertisedProtocol::Columba, + vec![COLUMBA_SERVICE_UUID], + ), + ); + assert_eq!(seen.get("AABB").unwrap().protocol, PeerProtocol::Columba); + merge_sighting( + &mut seen, + mk( + "AABB", + -60, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + assert_eq!( + seen.get("AABB").unwrap().protocol, + PeerProtocol::Ratspeak, + "full Ratspeak protocol must win once advertised" + ); + } + + #[test] + fn ratspeak_does_not_downgrade_to_columba() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + -60, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + merge_sighting( + &mut seen, + mk( + "AABB", + -60, + AdvertisedProtocol::Columba, + vec![COLUMBA_SERVICE_UUID], + ), + ); + assert_eq!(seen.get("AABB").unwrap().protocol, PeerProtocol::Ratspeak); + } + + #[test] + fn distinct_peers_each_get_their_own_entry() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + -55, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + merge_sighting( + &mut seen, + mk( + "CCDD", + -70, + AdvertisedProtocol::Columba, + vec![COLUMBA_SERVICE_UUID], + ), + ); + assert_eq!(seen.len(), 2); + assert_eq!(seen.get("AABB").unwrap().protocol, PeerProtocol::Ratspeak); + assert_eq!(seen.get("CCDD").unwrap().protocol, PeerProtocol::Columba); + } + + #[test] + fn at_exact_min_rssi_threshold_peer_is_kept() { + let mut seen = HashMap::new(); + merge_sighting( + &mut seen, + mk( + "AABB", + MIN_RSSI, + AdvertisedProtocol::Ratspeak, + vec![RATSPEAK_SERVICE_UUID], + ), + ); + assert_eq!(seen.len(), 1, "peer at exactly MIN_RSSI must be kept"); + } +} + +/// Called from `JNI_OnLoad`. +#[cfg(target_os = "android")] +pub fn init_android_jvm(vm: jni::JavaVM) { + android_peripheral::init_jvm(vm); +} + +pub async fn start_peripheral(_identity_hash: &[u8]) -> Result<(), String> { + #[cfg(any(target_os = "ios", target_os = "macos"))] + { + return apple_peripheral::start_advertising(_identity_hash).await; + } + + #[cfg(target_os = "android")] + { + return android_peripheral::start_advertising(_identity_hash).await; + } + + #[cfg(target_os = "linux")] + { + return linux_peripheral::start_advertising(_identity_hash).await; + } + + #[cfg(target_os = "windows")] + { + return windows_peripheral::start_advertising(_identity_hash).await; + } + + #[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "android", + target_os = "linux", + target_os = "windows" + )))] + { + tracing::warn!("BLE Peripheral not available on this platform"); + Err("BLE Peripheral not supported on this platform".into()) + } +} + +pub async fn stop_peripheral() -> Result<(), String> { + #[cfg(any(target_os = "ios", target_os = "macos"))] + { + apple_peripheral::stop_advertising().await + } + + #[cfg(target_os = "android")] + { + android_peripheral::stop_advertising().await + } + + #[cfg(target_os = "linux")] + { + linux_peripheral::stop_advertising().await + } + + #[cfg(target_os = "windows")] + { + windows_peripheral::stop_advertising().await + } + + #[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "android", + target_os = "linux", + target_os = "windows" + )))] + { + Ok(()) + } +} + +// Apple peripheral (CBPeripheralManager). State restoration is iOS-specific; +// macOS doesn't suspend processes the same way, so cold-rescan works there. + +/// Funnels into the GATT-server reassembler so both directions share +/// reassembly state. +#[cfg(any(target_os = "ios", target_os = "macos"))] +pub(crate) fn try_push_apple_inbound(peer: String, data: Vec) -> bool { + apple_peripheral::try_push_inbound(peer, data) +} + +#[cfg(any(target_os = "ios", target_os = "macos"))] +mod apple_peripheral { + use super::*; + use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; + use objc2::{msg_send, sel}; + use objc2_foundation::NSString; + use std::sync::OnceLock; + + /// 256 × ~200B ≈ 50KB — absorbs an LXMF burst (~40 frags) without OOM. + const INBOUND_CAPACITY: usize = 256; + + /// `peer_id` is `CBCentral.identifier.UUIDString` (or empty if unknown). + static INBOUND_TX: OnceLock)>> = OnceLock::new(); + type InboundReceiver = tokio::sync::mpsc::Receiver<(String, Vec)>; + + static INBOUND_RX: OnceLock>> = OnceLock::new(); + + pub fn take_inbound_rx() -> Option)>> { + INBOUND_RX + .get() + .and_then(|m| m.lock().ok()) + .and_then(|mut opt| opt.take()) + } + + pub(super) fn try_push_inbound(peer: String, data: Vec) -> bool { + match INBOUND_TX.get() { + Some(tx) => tx.try_send((peer, data)).is_ok(), + None => false, + } + } + + struct SendPtr(*mut AnyObject); + unsafe impl Send for SendPtr {} + unsafe impl Sync for SendPtr {} + static MANAGER_PTR: OnceLock> = OnceLock::new(); + static DELEGATE_CLASS: OnceLock<&'static AnyClass> = OnceLock::new(); + + static LIFECYCLE: OnceLock = OnceLock::new(); + + fn lifecycle() -> &'static crate::ble_peer_lifecycle::PeripheralLifecycle { + LIFECYCLE.get_or_init(crate::ble_peer_lifecycle::PeripheralLifecycle::new) + } + + /// Trace invalid transitions instead of panicking — BLE stacks deliver + /// out-of-order callbacks occasionally. + fn apply_event( + event: crate::ble_peer_lifecycle::LifecycleEvent, + ) -> Option { + match lifecycle().apply(event.clone()) { + Ok(state) => { + tracing::trace!(?event, ?state, "Apple BLE lifecycle"); + Some(state) + } + Err(err) => { + tracing::warn!(?err, "Apple BLE lifecycle: rejected transition"); + None + } + } + } + + /// Must stay stable across updates; changing forfeits + /// previously-backgrounded GATT subscriptions. + const PERIPHERAL_RESTORE_ID: &str = "org.ratspeak.ios.peripheral"; + + // objc2-core-bluetooth 0.2.2 only exports the central-role keys; link + // the peripheral-role NSString constants directly. + #[link(name = "CoreBluetooth", kind = "framework")] + unsafe extern "C" { + static CBPeripheralManagerOptionRestoreIdentifierKey: &'static NSString; + static CBPeripheralManagerRestoredStateServicesKey: &'static NSString; + static CBPeripheralManagerRestoredStateAdvertisementDataKey: &'static NSString; + } + + /// Ratspeak primary + Columba compat. + const EXPECTED_SERVICE_COUNT: usize = 2; + + /// Reset on each start/stop so cycles don't leak stale acks. + static SERVICES_ADDED_COUNT: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + + /// Cleared by `stop_advertising` so a later PoweredOn recovery doesn't + /// silently re-advertise after the user disabled BLE Mesh. + static LAST_IDENTITY_HASH: OnceLock>>> = OnceLock::new(); + + fn last_identity_hash() -> &'static std::sync::Mutex>> { + LAST_IDENTITY_HASH.get_or_init(|| std::sync::Mutex::new(None)) + } + + fn cb_state_name(state: i64) -> &'static str { + match state { + 0 => "Unknown", + 1 => "Resetting", + 2 => "Unsupported", + 3 => "Unauthorized", + 4 => "PoweredOff", + 5 => "PoweredOn", + _ => "UnknownVariant", + } + } + + /// CB disconnects all centrals on PoweredOff but `didUnsubscribe` + /// doesn't fire reliably across the transition — drain defensively. + fn clear_subscribed_centrals_for_recovery() { + if let Ok(mut map) = subscribed_centrals_map().lock() { + for (_, ptr) in map.drain() { + if !ptr.0.is_null() { + unsafe { + let _: () = msg_send![ptr.0, release]; + } + } + } + } + if let Ok(mut map) = central_subscribed_chars_map().lock() { + map.clear(); + } + } + + fn drain_characteristic_registry() { + if let Ok(mut map) = characteristic_registry().lock() { + for (_, ptr) in map.drain() { + if !ptr.0.is_null() { + unsafe { + let _: () = msg_send![ptr.0, release]; + } + } + } + } + } + + /// Must be stashed BEFORE manager construction so the first `PoweredOn` + /// delegate callback (which races the worker thread) finds it. Calling + /// `addService:` / `startAdvertising:` before PoweredOn is silently a + /// no-op in CB. + struct PendingAdvertise { + identity_hash: Vec, + } + static PENDING_ADVERTISE: OnceLock>> = + OnceLock::new(); + + fn pending_advertise() -> &'static std::sync::Mutex> { + PENDING_ADVERTISE.get_or_init(|| std::sync::Mutex::new(None)) + } + + /// The worker (not the delegate) runs `register_services_and_advertise` + /// because objc2's debug class-verify panics when `msg_send` runs from + /// CB's main dispatch queue in delegate context. + static POWERED_ON_TX: OnceLock>>> = + OnceLock::new(); + + fn powered_on_tx() -> &'static std::sync::Mutex>> { + POWERED_ON_TX.get_or_init(|| std::sync::Mutex::new(None)) + } + + /// Each entry holds a +1 retain (released on unsubscribe / disconnect / drain). + static SUBSCRIBED_CENTRALS: OnceLock>> = + OnceLock::new(); + + fn subscribed_centrals_map() -> &'static std::sync::Mutex> { + SUBSCRIBED_CENTRALS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) + } + + /// Lets the fan-out skip writes to characteristics a central never + /// subscribed to. Writing to both Ratspeak + Columba for every fragment + /// doubles radio pressure and drops half of LXMF payloads to queue-full. + static CENTRAL_SUBSCRIBED_CHARS: OnceLock< + std::sync::Mutex>>, + > = OnceLock::new(); + + fn central_subscribed_chars_map() + -> &'static std::sync::Mutex>> { + CENTRAL_SUBSCRIBED_CHARS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) + } + + #[allow(dead_code)] + pub fn subscribed_central_addresses() -> Vec { + match subscribed_centrals_map().lock() { + Ok(g) => g.keys().cloned().collect(), + Err(_) => Vec::new(), + } + } + + pub fn subscribed_centrals_for_char(char_uuid: Uuid) -> Vec { + match central_subscribed_chars_map().lock() { + Ok(g) => g + .iter() + .filter(|(_, chars)| chars.contains(&char_uuid)) + .map(|(id, _)| id.clone()) + .collect(), + Err(_) => Vec::new(), + } + } + + /// Drained by `peripheralManagerIsReadyToUpdateSubscribers:`. + struct PendingNotify { + peer: String, + char_uuid: Uuid, + data: Vec, + } + const PENDING_NOTIFY_CAP: usize = 128; + static PENDING_NOTIFY: OnceLock>> = + OnceLock::new(); + + fn pending_notify_queue() -> &'static std::sync::Mutex> + { + PENDING_NOTIFY.get_or_init(|| std::sync::Mutex::new(std::collections::VecDeque::new())) + } + + /// Returns empty string if input is null or extraction fails. + unsafe fn nsstring_to_string(s: *mut AnyObject) -> String { + if s.is_null() { + return String::new(); + } + unsafe { + let utf8: *const std::ffi::c_char = msg_send![&*s, UTF8String]; + // 4 = NSUTF8StringEncoding + let len: usize = msg_send![&*s, lengthOfBytesUsingEncoding: 4usize]; + if utf8.is_null() || len == 0 { + return String::new(); + } + let bytes = std::slice::from_raw_parts(utf8 as *const u8, len); + String::from_utf8_lossy(bytes).into_owned() + } + } + + unsafe fn central_identifier(req: *mut AnyObject) -> String { + if req.is_null() { + return String::new(); + } + unsafe { + let central: *mut AnyObject = msg_send![&*req, central]; + if central.is_null() { + return String::new(); + } + let identifier: *mut AnyObject = msg_send![&*central, identifier]; + if identifier.is_null() { + return String::new(); + } + let uuid_string: *mut AnyObject = msg_send![&*identifier, UUIDString]; + nsstring_to_string(uuid_string) + } + } + + fn get_delegate_class() -> &'static AnyClass { + DELEGATE_CLASS.get_or_init(|| { + let superclass = AnyClass::get("NSObject").unwrap(); + let mut builder = ClassBuilder::new("RatspeakBleDelegate", superclass).unwrap(); + + extern "C" fn did_update_state( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + ) { + if peripheral.is_null() { + return; + } + let state: i64 = unsafe { msg_send![&*peripheral, state] }; + tracing::info!( + state, + name = cb_state_name(state), + "iOS BLE Peripheral: state update" + ); + + match state { + // 0=Unknown 1=Resetting 2=Unsupported 3=Unauthorized + // 4=PoweredOff 5=PoweredOn. + 0 => {} + + 1 => { + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::PlatformUnavailable { + reason: "resetting".into(), + }, + ); + clear_subscribed_centrals_for_recovery(); + } + + 2 => { + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::FatalError { + reason: "bluetooth unsupported".into(), + }, + ); + } + + 3 => { + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::FatalError { + reason: "bluetooth permission denied".into(), + }, + ); + } + + // PoweredOff: keep manager around so the next PoweredOn + // can re-register. `stop_advertising` clears + // LAST_IDENTITY_HASH, so a user-stopped recovery is a no-op. + 4 => { + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::PlatformUnavailable { + reason: "bluetooth off".into(), + }, + ); + clear_subscribed_centrals_for_recovery(); + } + + // PoweredOn: hand off to the waiting worker (initial + // path), or re-register from `LAST_IDENTITY_HASH` if the + // worker already exited (recovery path). + 5 => { + // `take()` empties the slot so a subsequent PoweredOn + // takes the recovery branch. + let tx = match powered_on_tx().lock() { + Ok(mut g) => g.take(), + Err(e) => { + tracing::error!( + "iOS BLE Peripheral: powered_on_tx lock err: {e}" + ); + return; + } + }; + if let Some(tx) = tx { + if let Err(e) = tx.send(()) { + tracing::error!( + "iOS BLE Peripheral: powered_on signal send err: {e}" + ); + return; + } + tracing::info!( + "iOS BLE Peripheral: powered on (initial), releasing worker" + ); + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::PlatformReady, + ); + return; + } + + // Recovery branch: re-register if the lifecycle was + // rewound to StartingWaitingPlatform and we still + // have a stashed identity hash. + let state = lifecycle().current(); + let should_recover = matches!( + state, + crate::ble_peer_lifecycle::PeripheralState::StartingWaitingPlatform + ); + if !should_recover { + tracing::info!( + ?state, + "iOS BLE Peripheral: powered on, no recovery needed" + ); + return; + } + let Some(id_hash) = ({ + match last_identity_hash().lock() { + Ok(g) => g.clone(), + Err(_) => None, + } + }) else { + tracing::warn!( + "iOS BLE Peripheral: recovery-ready but LAST_IDENTITY_HASH unset" + ); + return; + }; + let Some(mgr_lock) = MANAGER_PTR.get() else { + tracing::warn!( + "iOS BLE Peripheral: recovery-ready but MANAGER_PTR unset" + ); + return; + }; + let mgr_ptr = match mgr_lock.lock() { + Ok(g) if !g.0.is_null() => g.0, + _ => { + tracing::warn!( + "iOS BLE Peripheral: recovery-ready but manager is null" + ); + return; + } + }; + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::PlatformReady, + ); + // Drop stale retained characteristics so the new + // registry reflects fresh CBMutableCharacteristic + // pointers CB is about to hand us. + SERVICES_ADDED_COUNT + .store(0, std::sync::atomic::Ordering::SeqCst); + drain_characteristic_registry(); + // Services must register off the main dispatch queue + // — objc2's debug class-verify rejects msg_send from + // main in delegate context. + // + // Cast to `usize` rather than capturing a `SendPtr`: + // edition-2021+ precise-capture would otherwise + // reduce the capture to the inner `*mut AnyObject` + // (not Send), defeating the wrapper. + let mgr_addr = mgr_ptr as usize; + std::thread::spawn(move || unsafe { + let mgr = mgr_addr as *mut AnyObject; + match register_services_and_advertise(mgr, &id_hash) { + Ok(()) => tracing::info!( + "iOS BLE Peripheral: recovery — re-registered services" + ), + Err(e) => { + tracing::error!( + "iOS BLE Peripheral: recovery register+advertise failed: {e}" + ); + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::PlatformUnavailable { + reason: format!("recovery re-register failed: {e}"), + }, + ); + } + } + }); + } + + _ => { + tracing::warn!( + state, + "iOS BLE Peripheral: unknown CBManagerState variant" + ); + } + } + } + + // Until this fires the lifecycle is StartingAdvertising; + // `err` is null on success. + extern "C" fn did_start_advertising( + _this: *mut AnyObject, + _sel: Sel, + _peripheral: *mut AnyObject, + err: *mut AnyObject, + ) { + if err.is_null() { + tracing::info!("iOS BLE Peripheral: advertising started"); + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStarted); + } else { + // Failure here is typically recoverable (user can toggle + // BT), so rewind to WaitingPlatform rather than Failed. + let reason = unsafe { + let desc: *mut AnyObject = msg_send![&*err, localizedDescription]; + nsstring_to_string(desc) + }; + tracing::warn!( + reason = %reason, + "iOS BLE Peripheral: startAdvertising error" + ); + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::PlatformUnavailable { + reason, + }); + } + } + + extern "C" fn did_add_service( + _this: *mut AnyObject, + _sel: Sel, + _p: *mut AnyObject, + _s: *mut AnyObject, + err: *mut AnyObject, + ) { + if err.is_null() { + tracing::info!("iOS BLE: service registered"); + // Once both Ratspeak + Columba are in, drive the + // lifecycle forward so AdvertiseStarted can legally follow. + let count = SERVICES_ADDED_COUNT + .fetch_add(1, std::sync::atomic::Ordering::SeqCst) + + 1; + if count >= EXPECTED_SERVICE_COUNT { + apply_event( + crate::ble_peer_lifecycle::LifecycleEvent::ServicesAdded, + ); + } + } else { + tracing::warn!("iOS BLE: service registration failed"); + let reason = unsafe { + let desc: *mut AnyObject = msg_send![&*err, localizedDescription]; + nsstring_to_string(desc) + }; + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::PlatformUnavailable { + reason, + }); + } + } + + extern "C" fn did_receive_writes( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + requests: *mut AnyObject, + ) { + if peripheral.is_null() || requests.is_null() { + return; + } + unsafe { + let count: usize = msg_send![&*requests, count]; + for i in 0..count { + let req: *mut AnyObject = msg_send![&*requests, objectAtIndex: i]; + if req.is_null() { + continue; + } + let peer_id = central_identifier(req); + let value: *mut AnyObject = msg_send![&*req, value]; + if value.is_null() { + continue; + } + let len: usize = msg_send![&*value, length]; + let ptr: *const std::ffi::c_void = msg_send![&*value, bytes]; + if !ptr.is_null() && len > 0 { + let data = std::slice::from_raw_parts(ptr as *const u8, len).to_vec(); + tracing::debug!( + target: "ble_trace", + step = "apple_peripheral.write_recv", + peer = %peer_id, + len = data.len(), + "Apple BLE peripheral: write received" + ); + if let Some(tx) = INBOUND_TX.get() { + // CB dispatch queue is synchronous, so try_send + + // drop-on-full instead of blocking the callback. + if let Err(e) = tx.try_send((peer_id, data)) { + tracing::warn!( + "Apple BLE inbound channel full, dropping frame: {e}" + ); + } + } + } + let _: () = + msg_send![&*peripheral, respondToRequest: &*req, withResult: 0i64]; + } + } + } + + extern "C" fn did_subscribe( + _this: *mut AnyObject, + _sel: Sel, + _peripheral: *mut AnyObject, + central: *mut AnyObject, + characteristic: *mut AnyObject, + ) { + if central.is_null() { + return; + } + unsafe { + let identifier: *mut AnyObject = msg_send![&*central, identifier]; + if identifier.is_null() { + return; + } + let uuid_string: *mut AnyObject = msg_send![&*identifier, UUIDString]; + let id = nsstring_to_string(uuid_string); + if id.is_empty() { + return; + } + let char_uuid = uuid_for_characteristic(characteristic); + // First-ever subscribe per central also takes the +1 + // retain that pairs with the release in did_unsubscribe. + let first_ever_sub_for_central = { + let mut chars_map = central_subscribed_chars_map().lock().unwrap(); + let entry = chars_map.entry(id.clone()).or_default(); + let first = entry.is_empty(); + if let Some(u) = char_uuid { + entry.insert(u); + } + first + }; + let mut map = subscribed_centrals_map().lock().unwrap(); + let already_subscribed = map.contains_key(&id); + if !already_subscribed { + let _: *mut AnyObject = msg_send![&*central, retain]; + map.insert(id.clone(), SendPtr(central)); + } + tracing::info!(peer = %id, ?char_uuid, "Apple BLE: central subscribed"); + if first_ever_sub_for_central && !already_subscribed { + drop(map); + // Surface the subscribe as a connected peer for the + // UI cache. identity_hash is left blank until the + // announce resolves it. + super::dispatch_event(BlePeerEvent::Connected { + address: id.clone(), + identity_hash: String::new(), + protocol: PeerProtocol::Ratspeak, + }); + super::dispatch_event(BlePeerEvent::SubscribeReady { address: id }); + } + } + } + + // Unsubscribing from one of two subscribed chars does NOT + // disconnect the peer (matches Android behavior); only when the + // per-central set goes empty do we release + emit Disconnected. + extern "C" fn did_unsubscribe( + _this: *mut AnyObject, + _sel: Sel, + _peripheral: *mut AnyObject, + central: *mut AnyObject, + characteristic: *mut AnyObject, + ) { + if central.is_null() { + return; + } + unsafe { + let identifier: *mut AnyObject = msg_send![&*central, identifier]; + if identifier.is_null() { + return; + } + let uuid_string: *mut AnyObject = msg_send![&*identifier, UUIDString]; + let id = nsstring_to_string(uuid_string); + if id.is_empty() { + return; + } + let char_uuid = uuid_for_characteristic(characteristic); + let all_gone = { + let mut chars_map = central_subscribed_chars_map().lock().unwrap(); + if let Some(u) = char_uuid + && let Some(set) = chars_map.get_mut(&id) + { + set.remove(&u); + } + let empty = chars_map.get(&id).is_none_or(|s| s.is_empty()); + if empty { + chars_map.remove(&id); + } + empty + }; + tracing::info!(peer = %id, ?char_uuid, all_gone, "Apple BLE: central unsubscribed"); + if all_gone { + let mut map = subscribed_centrals_map().lock().unwrap(); + let was_subscribed = map.remove(&id).is_some_and(|ptr| { + let _: () = msg_send![ptr.0, release]; + true + }); + if was_subscribed { + drop(map); + super::dispatch_event(BlePeerEvent::Disconnected { + address: id, + reason: "central unsubscribed".into(), + }); + } + } + } + } + + // Without retrying here, fragmented LXMF messages silently + // lose every fragment past the first because the queue isn't + // ready between writes. + extern "C" fn is_ready_to_update( + _this: *mut AnyObject, + _sel: Sel, + _peripheral: *mut AnyObject, + ) { + loop { + let entry = { + let mut q = pending_notify_queue().lock().unwrap(); + q.pop_front() + }; + let Some(entry) = entry else { break }; + if !notify_tx_inner(Some(&entry.peer), entry.char_uuid, &entry.data) { + // Still full — requeue at front and wait for the + // next ready-to-update callback. + let mut q = pending_notify_queue().lock().unwrap(); + q.push_front(entry); + break; + } + } + } + + // Fires BEFORE `peripheralManagerDidUpdateState:` when iOS + // resurrects the process for a background BLE event. + extern "C" fn will_restore_state( + _this: *mut AnyObject, + _sel: Sel, + peripheral: *mut AnyObject, + dict: *mut AnyObject, + ) { + if dict.is_null() { + tracing::info!( + "iOS BLE Peripheral: willRestoreState (empty dict)" + ); + return; + } + unsafe { + let services: *mut AnyObject = msg_send![&*dict, + objectForKey: CBPeripheralManagerRestoredStateServicesKey]; + let ad_data: *mut AnyObject = msg_send![&*dict, + objectForKey: CBPeripheralManagerRestoredStateAdvertisementDataKey]; + + let service_count: usize = if services.is_null() { + 0 + } else { + msg_send![&*services, count] + }; + let has_ad_data = !ad_data.is_null(); + + tracing::info!( + target: "ble_trace", + step = "peripheral.will_restore_state", + service_count, + has_ad_data, + "iOS BLE Peripheral: willRestoreState" + ); + + // Services + their CBMutableCharacteristics are already + // attached to the manager per Apple's docs; we just need + // to repopulate CHARACTERISTIC_REGISTRY so notify_tx can + // resolve TX pointers by UUID. + if !services.is_null() { + for i in 0..service_count { + let svc: *mut AnyObject = + msg_send![&*services, objectAtIndex: i]; + if svc.is_null() { + continue; + } + let chars: *mut AnyObject = + msg_send![&*svc, characteristics]; + if chars.is_null() { + continue; + } + let cc: usize = msg_send![&*chars, count]; + for j in 0..cc { + let ch: *mut AnyObject = + msg_send![&*chars, objectAtIndex: j]; + if ch.is_null() { + continue; + } + let cb_uuid: *mut AnyObject = + msg_send![&*ch, UUID]; + if cb_uuid.is_null() { + continue; + } + let uuid_str_obj: *mut AnyObject = + msg_send![&*cb_uuid, UUIDString]; + let uuid_str = nsstring_to_string(uuid_str_obj); + let uuid = match Uuid::parse_str(&uuid_str) { + Ok(u) => u, + Err(_) => continue, + }; + // RX is delegate-driven; we only need TX + // pointers in the registry for notify_tx. + if uuid == RATSPEAK_TX_UUID + || uuid == COLUMBA_TX_UUID + { + // Outlive the autorelease-pool drain. + let _: *mut AnyObject = + msg_send![ch, retain]; + register_characteristic(uuid, ch); + tracing::info!( + target: "ble_trace", + step = "peripheral.restore_char", + uuid = %uuid, + "iOS BLE Peripheral: registered restored TX characteristic" + ); + } + } + } + } + + // Skip when ad_data is nil — the app wasn't advertising + // at suspend time, so don't resurrect that state. + if has_ad_data && !peripheral.is_null() { + let _: () = + msg_send![&*peripheral, startAdvertising: ad_data]; + tracing::info!( + target: "ble_trace", + step = "peripheral.restore_resumed_advertising", + "iOS BLE Peripheral: startAdvertising resumed from restored ad data" + ); + } + } + } + + unsafe { + builder.add_method( + sel!(peripheralManagerDidUpdateState:), + did_update_state as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject), + ); + builder.add_method( + sel!(peripheralManagerDidStartAdvertising:error:), + did_start_advertising + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheralManager:didAddService:error:), + did_add_service + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheralManager:didReceiveWriteRequests:), + did_receive_writes + as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject), + ); + builder.add_method( + sel!(peripheralManager:central:didSubscribeToCharacteristic:), + did_subscribe + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheralManager:central:didUnsubscribeFromCharacteristic:), + did_unsubscribe + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + *mut AnyObject, + ), + ); + builder.add_method( + sel!(peripheralManagerIsReadyToUpdateSubscribers:), + is_ready_to_update + as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject), + ); + builder.add_method( + sel!(peripheralManager:willRestoreState:), + will_restore_state + as extern "C" fn( + *mut AnyObject, + Sel, + *mut AnyObject, + *mut AnyObject, + ), + ); + } + + builder.register() + }) + } + + /// Push `data` on the TX characteristic matching `char_uuid`; targets + /// `to_peer` if set, all subscribed centrals otherwise. Targeted writes + /// queue onto PENDING_NOTIFY on backpressure; broadcasts can't be + /// replayed coherently without per-central addressing, so they don't. + pub fn notify_tx(to_peer: Option<&str>, char_uuid: Uuid, data: &[u8]) -> bool { + let ok = notify_tx_inner(to_peer, char_uuid, data); + if !ok && let Some(peer_id) = to_peer { + let mut q = pending_notify_queue().lock().unwrap(); + if q.len() >= PENDING_NOTIFY_CAP { + q.pop_front(); + } + q.push_back(PendingNotify { + peer: peer_id.to_string(), + char_uuid, + data: data.to_vec(), + }); + tracing::warn!(%char_uuid, bytes = data.len(), peer = %peer_id, depth = q.len(), "Apple BLE notify_tx: queued for retry (radio queue full)"); + } + ok + } + + /// Returns the raw `updateValue:` result without touching the retry + /// queue, so it's safe to call from the is-ready-to-update flush loop. + fn notify_tx_inner(to_peer: Option<&str>, char_uuid: Uuid, data: &[u8]) -> bool { + let mgr_lock = match MANAGER_PTR.get() { + Some(m) => m, + None => { + tracing::warn!("Apple BLE notify_tx: no manager ptr"); + return false; + } + }; + let mgr = match mgr_lock.lock() { + Ok(g) if !g.0.is_null() => g.0, + _ => { + tracing::warn!("Apple BLE notify_tx: manager null or poisoned"); + return false; + } + }; + let char_ptr = match characteristic_for_uuid(char_uuid) { + Some(p) => p, + None => { + tracing::warn!(%char_uuid, "Apple BLE notify_tx: characteristic not registered"); + return false; + } + }; + unsafe { + let arr_cls = match AnyClass::get("NSArray") { + Some(c) => c, + None => return false, + }; + let data_cls = match AnyClass::get("NSData") { + Some(c) => c, + None => return false, + }; + let payload: *mut AnyObject = msg_send![data_cls, + dataWithBytes: data.as_ptr() as *const std::ffi::c_void, + length: data.len()]; + let centrals: *mut AnyObject = if let Some(peer_id) = to_peer { + let map = subscribed_centrals_map().lock().unwrap(); + let ptr = match map.get(peer_id) { + Some(p) => p.0, + None => { + tracing::warn!(peer = %peer_id, "Apple BLE notify_tx: peer not in subscribed map"); + return false; + } + }; + let one = [ptr as *const AnyObject]; + msg_send![arr_cls, arrayWithObjects: one.as_ptr(), count: 1usize] + } else { + std::ptr::null_mut() + }; + let ok: bool = msg_send![ + mgr, + updateValue: payload, + forCharacteristic: char_ptr, + onSubscribedCentrals: centrals, + ]; + ok + } + } + + // We only need the TX chars from notify_tx, but the registry is keyed + // by UUID for symmetry. + static CHARACTERISTIC_REGISTRY: OnceLock>> = + OnceLock::new(); + + fn characteristic_registry() -> &'static std::sync::Mutex> { + CHARACTERISTIC_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new())) + } + + fn register_characteristic(uuid: Uuid, ptr: *mut AnyObject) { + let mut map = characteristic_registry().lock().unwrap(); + map.insert(uuid, SendPtr(ptr)); + } + + fn characteristic_for_uuid(uuid: Uuid) -> Option<*mut AnyObject> { + let map = characteristic_registry().lock().ok()?; + map.get(&uuid).map(|p| p.0) + } + + /// Reverse of `characteristic_for_uuid`; lets the subscribe delegate + /// avoid bouncing through `CBCharacteristic.UUID.UUIDString` on the + /// main queue. + fn uuid_for_characteristic(ptr: *mut AnyObject) -> Option { + if ptr.is_null() { + return None; + } + let map = characteristic_registry().lock().ok()?; + map.iter() + .find(|(_, sp)| sp.0 == ptr) + .map(|(uuid, _)| *uuid) + } + + /// Returns a raw retained pointer. + fn cbuuid(uuid: &Uuid) -> *mut AnyObject { + let s = NSString::from_str(&uuid.to_string()); + unsafe { + let cls = AnyClass::get("CBUUID").unwrap(); + let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s]; + let _: *mut AnyObject = msg_send![obj, retain]; + obj + } + } + + pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> { + // Drive the lifecycle BEFORE any side effects. + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::StartRequested); + SERVICES_ADDED_COUNT.store(0, std::sync::atomic::Ordering::SeqCst); + + let id_hash = identity_hash.to_vec(); + // Stash for the PoweredOff → PoweredOn recovery path in + // `did_update_state` (cleared by `stop_advertising`). + if let Ok(mut g) = last_identity_hash().lock() { + *g = Some(id_hash.clone()); + } + let (tx, rx) = tokio::sync::mpsc::channel::<(String, Vec)>(INBOUND_CAPACITY); + let _ = INBOUND_TX.set(tx); + let _ = INBOUND_RX.set(std::sync::Mutex::new(Some(rx))); + + // Stash pending + signal sender BEFORE creating the manager — + // `peripheralManagerDidUpdateState:` fires on the main queue and + // can race ahead of our worker thread. If either is still None when + // PoweredOn lands, services never register. + match pending_advertise().lock() { + Ok(mut g) => { + *g = Some(PendingAdvertise { + identity_hash: id_hash.clone(), + }); + } + Err(e) => return Err(format!("pending_advertise lock poisoned: {e}")), + } + + let (signal_tx, signal_rx) = std::sync::mpsc::channel::<()>(); + match powered_on_tx().lock() { + Ok(mut g) => *g = Some(signal_tx), + Err(e) => return Err(format!("powered_on_tx lock poisoned: {e}")), + } + + // Dedicated thread (detached): sidesteps Send issues with raw ObjC + // pointers, and keeps register_services_and_advertise off the main + // queue (objc2's debug class-verify panics when msg_send runs from + // CB's main dispatch queue in delegate context). + std::thread::spawn(move || unsafe { + let delegate_cls = get_delegate_class(); + let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc]; + let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init]; + + let Some(mgr_cls) = AnyClass::get("CBPeripheralManager") else { + tracing::error!("iOS BLE Peripheral: CBPeripheralManager class not found"); + return; + }; + let mgr_raw: *mut AnyObject = msg_send![mgr_cls, alloc]; + // RestoreIdentifierKey lets iOS resurrect this peripheral for a + // background BLE event after the process is killed. + let opts: *mut AnyObject = { + let dict_cls = + AnyClass::get("NSDictionary").expect("NSDictionary must exist at runtime"); + let id = NSString::from_str(PERIPHERAL_RESTORE_ID); + msg_send![dict_cls, + dictionaryWithObject: &*id, + forKey: CBPeripheralManagerOptionRestoreIdentifierKey] + }; + let mgr_raw: *mut AnyObject = msg_send![mgr_raw, + initWithDelegate: delegate_raw, + queue: std::ptr::null::(), + options: opts, + ]; + // `retain` returns `id`; binding as `*mut AnyObject` avoids + // objc2's debug class-verify tripping on KVO-swizzled subclasses + // like `NSKVONotifying_CBPeripheralManager`. + let _: *mut AnyObject = msg_send![mgr_raw, retain]; + + let _ = MANAGER_PTR.set(std::sync::Mutex::new(SendPtr(mgr_raw))); + tracing::info!("iOS BLE Peripheral: manager created, waiting for PoweredOn"); + + // 10s safety net; CB normally reports state within ~100ms. + match signal_rx.recv_timeout(std::time::Duration::from_secs(10)) { + Ok(()) => {} + Err(e) => { + tracing::error!("iOS BLE Peripheral: timed out waiting for PoweredOn: {e}"); + if let Ok(mut g) = pending_advertise().lock() { + *g = None; + } + return; + } + } + + // On subsequent Bluetooth-cycled PoweredOn firings there will + // be nothing to do. + let pending = match pending_advertise().lock() { + Ok(mut g) => g.take(), + Err(e) => { + tracing::error!("iOS BLE Peripheral: pending lock err: {e}"); + return; + } + }; + let Some(pending) = pending else { + tracing::info!("iOS BLE Peripheral: pending was already taken, skipping"); + return; + }; + + match register_services_and_advertise(mgr_raw, &pending.identity_hash) { + Ok(()) => tracing::info!( + "iOS BLE Peripheral: powered on, registering services + advertising" + ), + Err(e) => tracing::error!("iOS BLE Peripheral: register+advertise failed: {e}"), + } + }); + + Ok(()) + } + + /// Columba is registered in the GATT server for post-connect service + /// discovery but intentionally NOT in `kCBAdvDataServiceUUIDs` — two + /// 128-bit UUIDs exceed the BLE 4.x 31-byte advertising payload, and + /// iOS would overflow one into the scan response (which some Android + /// `ScanFilter.setServiceUuid` paths miss). + unsafe fn register_services_and_advertise( + mgr_raw: *mut AnyObject, + id_hash: &[u8], + ) -> Result<(), String> { + unsafe { + let char_cls = AnyClass::get("CBMutableCharacteristic") + .ok_or("CBMutableCharacteristic not found")?; + let svc_cls = AnyClass::get("CBMutableService").ok_or("CBMutableService not found")?; + let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?; + let data_cls = AnyClass::get("NSData").ok_or("NSData not found")?; + let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?; + + // RX (write + writeNoResponse) + let rx_raw: *mut AnyObject = msg_send![char_cls, alloc]; + let rx_raw: *mut AnyObject = msg_send![rx_raw, + initWithType: cbuuid(&RATSPEAK_RX_UUID), properties: 0x0Cu64, + value: std::ptr::null::(), permissions: 0x02u64]; + // TX (read + notify) + let tx_raw: *mut AnyObject = msg_send![char_cls, alloc]; + let tx_raw: *mut AnyObject = msg_send![tx_raw, + initWithType: cbuuid(&RATSPEAK_TX_UUID), properties: 0x12u64, + value: std::ptr::null::(), permissions: 0x01u64]; + // Keep the registry pointer valid for notify_tx. + let _: *mut AnyObject = msg_send![tx_raw, retain]; + register_characteristic(RATSPEAK_TX_UUID, tx_raw); + // ID (read, static value) + let id_data: *mut AnyObject = msg_send![data_cls, + dataWithBytes: id_hash.as_ptr() as *const std::ffi::c_void, + length: id_hash.len()]; + let id_raw: *mut AnyObject = msg_send![char_cls, alloc]; + let id_raw: *mut AnyObject = msg_send![id_raw, + initWithType: cbuuid(&RATSPEAK_ID_UUID), properties: 0x02u64, + value: id_data, permissions: 0x01u64]; + + // Ratspeak service (primary) + let svc_raw: *mut AnyObject = msg_send![svc_cls, alloc]; + let svc_raw: *mut AnyObject = msg_send![svc_raw, + initWithType: cbuuid(&RATSPEAK_SERVICE_UUID), primary: true]; + let char_ptrs = [ + rx_raw as *const AnyObject, + tx_raw as *const AnyObject, + id_raw as *const AnyObject, + ]; + let chars: *mut AnyObject = msg_send![arr_cls, + arrayWithObjects: char_ptrs.as_ptr(), count: 3usize]; + let _: () = msg_send![svc_raw, setCharacteristics: chars]; + let _: () = msg_send![mgr_raw, addService: svc_raw]; + + // Columba compat (secondary, omitted from advertising payload). + let c_rx_raw: *mut AnyObject = msg_send![char_cls, alloc]; + let c_rx_raw: *mut AnyObject = msg_send![c_rx_raw, + initWithType: cbuuid(&COLUMBA_RX_UUID), properties: 0x0Cu64, + value: std::ptr::null::(), permissions: 0x02u64]; + let c_tx_raw: *mut AnyObject = msg_send![char_cls, alloc]; + let c_tx_raw: *mut AnyObject = msg_send![c_tx_raw, + initWithType: cbuuid(&COLUMBA_TX_UUID), properties: 0x12u64, + value: std::ptr::null::(), permissions: 0x01u64]; + let _: *mut AnyObject = msg_send![c_tx_raw, retain]; + register_characteristic(COLUMBA_TX_UUID, c_tx_raw); + let c_id_data: *mut AnyObject = msg_send![data_cls, + dataWithBytes: id_hash.as_ptr() as *const std::ffi::c_void, + length: id_hash.len()]; + let c_id_raw: *mut AnyObject = msg_send![char_cls, alloc]; + let c_id_raw: *mut AnyObject = msg_send![c_id_raw, + initWithType: cbuuid(&COLUMBA_ID_UUID), properties: 0x02u64, + value: c_id_data, permissions: 0x01u64]; + let c_svc_raw: *mut AnyObject = msg_send![svc_cls, alloc]; + let c_svc_raw: *mut AnyObject = msg_send![c_svc_raw, + initWithType: cbuuid(&COLUMBA_SERVICE_UUID), primary: false]; + let c_char_ptrs = [ + c_rx_raw as *const AnyObject, + c_tx_raw as *const AnyObject, + c_id_raw as *const AnyObject, + ]; + let c_chars: *mut AnyObject = msg_send![arr_cls, + arrayWithObjects: c_char_ptrs.as_ptr(), count: 3usize]; + let _: () = msg_send![c_svc_raw, setCharacteristics: c_chars]; + let _: () = msg_send![mgr_raw, addService: c_svc_raw]; + + // One 128-bit UUID fits in the 31-byte BLE 4.x adv PDU; two do not. + let ad_key = NSString::from_str("kCBAdvDataServiceUUIDs"); + let uuid_ptrs = [cbuuid(&RATSPEAK_SERVICE_UUID) as *const AnyObject]; + let uuid_arr: *mut AnyObject = msg_send![arr_cls, + arrayWithObjects: uuid_ptrs.as_ptr(), count: 1usize]; + let ad_dict: *mut AnyObject = msg_send![dict_cls, + dictionaryWithObject: uuid_arr, forKey: &*ad_key]; + let _: () = msg_send![mgr_raw, startAdvertising: ad_dict]; + + tracing::info!( + target: "ble_trace", + step = "peripheral.advertise_started", + advertised_uuid = %RATSPEAK_SERVICE_UUID, + gatt_services = "Ratspeak (primary) + Columba (secondary)", + identity_hash_bytes = id_hash.len(), + "Apple BLE Peripheral: advertising started" + ); + Ok(()) + } + } + + /// Walks the lifecycle state machine in lockstep with the platform + /// work: stopAdvertising, poll `isAdvertising` until the radio + /// confirms, removeAllServices, release retained resources, detach + /// the delegate, null the stored manager pointer, then Reset. The + /// "fast path" of just calling stopAdvertising + removeAllServices and + /// returning leaves CB in a dirty state that breaks subsequent enables. + pub async fn stop_advertising() -> Result<(), String> { + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::StopRequested); + + if let Ok(mut g) = pending_advertise().lock() { + *g = None; + } + // Dropping the sender wakes the worker thread's recv_timeout with a + // Disconnected error, which it handles as a cancel. + if let Ok(mut g) = powered_on_tx().lock() { + *g = None; + } + // User disabled BLE Mesh, so a later OS-initiated PoweredOn + // recovery in `did_update_state` must NOT silently re-advertise. + if let Ok(mut g) = last_identity_hash().lock() { + *g = None; + } + + let state = lifecycle().current(); + let needs_stop_ad = matches!( + state, + crate::ble_peer_lifecycle::PeripheralState::StoppingAdvertisement + ); + let needs_remove = matches!( + state, + crate::ble_peer_lifecycle::PeripheralState::StoppingAdvertisement + | crate::ble_peer_lifecycle::PeripheralState::StoppingRemovingServices + ); + + // No platform-side work required — finish the lifecycle and return. + if !needs_stop_ad && !needs_remove { + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::Reset); + return Ok(()); + } + + // Holding the lock across `await` would deadlock with concurrent + // notify_tx; take the raw ptr out and drop the guard. + let mgr_ptr: *mut AnyObject = { + let Some(lock) = MANAGER_PTR.get() else { + tracing::warn!("iOS BLE Peripheral: stop requested but MANAGER_PTR unset"); + if needs_stop_ad { + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped); + } + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved); + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::Reset); + return Ok(()); + }; + match lock.lock() { + Ok(g) if !g.0.is_null() => g.0, + _ => { + tracing::warn!( + "iOS BLE Peripheral: stop requested but manager ptr is null/poisoned" + ); + if needs_stop_ad { + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped); + } + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved); + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::Reset); + return Ok(()); + } + } + }; + + // SendPtr lets the raw pointer cross `await` (`*mut AnyObject: !Send`). + let mgr_send = SendPtr(mgr_ptr); + + if needs_stop_ad { + unsafe { + let _: () = msg_send![mgr_send.0, stopAdvertising]; + } + // CB has no peripheralManagerDidStopAdvertising delegate — poll + // `isAdvertising`. Radio flips within ~20ms; 1s budget covers + // contended radios and bounce loops. + const POLL_INTERVAL_MS: u64 = 50; + const POLL_ITERATIONS: u32 = 20; + let mut confirmed = false; + for _ in 0..POLL_ITERATIONS { + let advertising: bool = unsafe { msg_send![mgr_send.0, isAdvertising] }; + if !advertising { + confirmed = true; + break; + } + tokio::time::sleep(std::time::Duration::from_millis(POLL_INTERVAL_MS)).await; + } + if !confirmed { + tracing::warn!( + "iOS BLE Peripheral: isAdvertising still true after {} ms; proceeding with teardown", + POLL_INTERVAL_MS * u64::from(POLL_ITERATIONS) + ); + } + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped); + } + + unsafe { + let _: () = msg_send![mgr_send.0, removeAllServices]; + } + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved); + + // Without this, every toggle cycle leaks two CBMutableCharacteristic + // pointers and notify_tx can race onto dead characteristics post-teardown. + { + let mut map = characteristic_registry().lock().unwrap(); + for (_, ptr) in map.drain() { + if !ptr.0.is_null() { + unsafe { + let _: () = msg_send![ptr.0, release]; + } + } + } + } + SERVICES_ADDED_COUNT.store(0, std::sync::atomic::Ordering::SeqCst); + + // CB fires `didUnsubscribe` as services disappear, but we can't + // depend on those having landed yet. Each entry holds a +1, so + // releasing defensively here is safe. + { + let mut map = subscribed_centrals_map().lock().unwrap(); + for (_, ptr) in map.drain() { + if !ptr.0.is_null() { + unsafe { + let _: () = msg_send![ptr.0, release]; + } + } + } + } + { + let mut map = central_subscribed_chars_map().lock().unwrap(); + map.clear(); + } + + // Detach delegate before release so queued callbacks on CB's main + // dispatch queue become no-ops rather than UAF on the delegate. + unsafe { + let _: () = msg_send![mgr_send.0, setDelegate: std::ptr::null::()]; + } + + // Balance the explicit `retain` from `start_advertising`. The + // original `alloc` reference is intentionally NOT released — the + // radio may still have in-flight delegate invocations queued on CB's + // main dispatch queue, and a second release would race that queue + // with a UAF. The resulting leak is bounded (~KB per toggle cycle). + unsafe { + let _: () = msg_send![mgr_send.0, release]; + } + + // OnceLock can't be cleared, but the inner Mutex lets us + // null the pointer so notify_tx + the next start cycle see no manager. + if let Some(lock) = MANAGER_PTR.get() + && let Ok(mut guard) = lock.lock() + { + *guard = SendPtr(std::ptr::null_mut()); + } + + // Any queued retries reference characteristics we just released; + // drop them rather than let a later flush dereference a dead ptr. + { + let mut q = pending_notify_queue().lock().unwrap(); + q.clear(); + } + + apply_event(crate::ble_peer_lifecycle::LifecycleEvent::Reset); + + tracing::info!("iOS BLE Peripheral: teardown complete"); + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Android Peripheral (JNI to BluetoothGattServer) +// --------------------------------------------------------------------------- + +/// Public wrapper so callers can tear down a single Android peer connection +/// without reaching into the private `android_peripheral` module. +#[cfg(target_os = "android")] +pub fn disconnect_android_peer(address: &str) { + android_peripheral::peer_client_disconnect(address); +} + +#[cfg(target_os = "android")] +mod android_peripheral { + use super::*; + use jni::JavaVM; + use jni::objects::{GlobalRef, JObject, JValue}; + use std::sync::OnceLock; + + static JAVA_VM: OnceLock = OnceLock::new(); + static ADVERTISER_REF: OnceLock = OnceLock::new(); + static CALLBACK_REF: OnceLock = OnceLock::new(); + + /// Registry of per-peer `online` flags so the JNI disconnect callback can + /// flip them without holding a direct handle to the Tokio task that owns + /// the connection. The Android central task registers each peer's flag at + /// connect time and unregisters on cleanup. + static PEER_ONLINE: OnceLock>>> = + OnceLock::new(); + + fn peer_online_map() -> &'static std::sync::Mutex>> { + PEER_ONLINE.get_or_init(|| std::sync::Mutex::new(HashMap::new())) + } + + /// Register an `online` flag the JNI disconnect callback can flip. Called + /// by the Android central task after a successful peer client connect. + pub fn register_peer_online(address: String, flag: Arc) { + if let Ok(mut g) = peer_online_map().lock() { + g.insert(address, flag); + } + } + + /// Remove an entry from the registry. Called from the central task's + /// cleanup phase so the map doesn't grow unbounded. + pub fn unregister_peer_online(address: &str) { + if let Ok(mut g) = peer_online_map().lock() { + g.remove(address); + } + } + + fn signal_peer_offline(address: &str) { + if let Ok(g) = peer_online_map().lock() { + if let Some(flag) = g.get(address) { + flag.store(false, Ordering::SeqCst); + } + } + } + + /// Inbound channel capacity. See apple_peripheral::INBOUND_CAPACITY for rationale. + const INBOUND_CAPACITY: usize = 256; + + /// Inbound channel: each item is `(peer_address, data)` where `peer_address` + /// is the source BluetoothDevice MAC string passed from RatspeakGattCallback.kt. + /// See apple_peripheral::INBOUND_TX for the same shape on Apple platforms — + /// the consumer in spawn_ble_peer_interface keys per-peer reassembly off this. + static INBOUND_TX: OnceLock)>> = OnceLock::new(); + static INBOUND_RX: OnceLock< + std::sync::Mutex)>>>, + > = OnceLock::new(); + + /// Take the inbound receiver (call once from spawn_ble_peer_interface). + pub fn take_inbound_rx() -> Option)>> { + INBOUND_RX + .get() + .and_then(|m| m.lock().ok()) + .and_then(|mut opt| opt.take()) + } + + /// Called from JNI native method when the GATT server receives data from a peer. + /// `peer_address` is the source BluetoothDevice MAC (or random rotating addr). + pub fn on_gatt_data_received(peer_address: String, data: Vec) { + if let Some(tx) = INBOUND_TX.get() { + // JNI callback is synchronous on the binder thread; try_send + drop-on-full + // is preferred over blocking the Android GATT stack when the reassembler stalls. + if let Err(e) = tx.try_send((peer_address, data)) { + tracing::warn!("Android BLE inbound channel full, dropping frame: {e}"); + } + } + } + + /// Store the JavaVM for later JNI calls (called from Tauri Android init). + pub fn init_jvm(vm: JavaVM) { + let _ = JAVA_VM.set(vm); + } + + fn with_env(f: F) -> Result + where + F: FnOnce(&jni::JNIEnv) -> Result, + { + let vm = JAVA_VM.get().ok_or("JavaVM not initialized")?; + let env = vm + .attach_current_thread() + .map_err(|e| format!("JNI attach: {e}"))?; + let result = f(&env); + // Always clear any lingering Java exception before returning. + // jni-rs panics on the next JNI call if the env still has one + // pending — even one we already converted to a Rust error. + jni_clear(&env); + result + } + + /// Clear any pending JNI exception so the next JNI call doesn't see a + /// dirty env. Java exceptions remain pending after a failed JNI call; + /// jni-rs treats subsequent calls as undefined behavior. Call this after + /// any swallowed `.ok()` and on error paths before bubbling up. + fn jni_clear(env: &jni::JNIEnv) { + if env.exception_check().unwrap_or(false) { + let _ = env.exception_describe(); + let _ = env.exception_clear(); + } + } + + /// Resolve the system BluetoothAdapter via the modern BluetoothManager + /// path. Mirrors `RatspeakBleServer.openGattServer` (Kotlin) and avoids + /// the deprecated `BluetoothAdapter.getDefaultAdapter()` which + /// SecurityExceptions on Android 12+ without BLUETOOTH_CONNECT and is + /// removed entirely on some Android 14+ vendor builds. + fn get_bluetooth_adapter<'a>( + env: &'a jni::JNIEnv, + context: JObject<'a>, + ) -> Result, String> { + let svc = env + .new_string("bluetooth") + .map_err(|e| format!("bluetooth service name: {e}"))?; + let manager = env + .call_method( + context, + "getSystemService", + "(Ljava/lang/String;)Ljava/lang/Object;", + &[JValue::Object(svc.into())], + ) + .map_err(|e| { + jni_clear(env); + format!("getSystemService(bluetooth): {e}") + })? + .l() + .map_err(|e| format!("BluetoothManager cast: {e}"))?; + if manager.is_null() { + return Err("BluetoothManager unavailable on this device".into()); + } + let adapter = env + .call_method( + manager, + "getAdapter", + "()Landroid/bluetooth/BluetoothAdapter;", + &[], + ) + .map_err(|e| { + jni_clear(env); + format!("BluetoothManager.getAdapter: {e}") + })? + .l() + .map_err(|e| format!("BluetoothAdapter cast: {e}"))?; + if adapter.is_null() { + return Err("BluetoothAdapter unavailable (radio off?)".into()); + } + Ok(adapter) + } + + /// Get the application Context via ActivityThread.currentApplication(). + fn get_app_context<'a>(env: &'a jni::JNIEnv) -> Result, String> { + let at_cls = env + .find_class("android/app/ActivityThread") + .map_err(|e| format!("ActivityThread class: {e}"))?; + let app = env + .call_static_method( + at_cls, + "currentApplication", + "()Landroid/app/Application;", + &[], + ) + .map_err(|e| format!("currentApplication: {e}"))? + .l() + .map_err(|e| format!("{e}"))?; + if app.is_null() { + return Err("currentApplication returned null".into()); + } + Ok(app) + } + + /// Cached application ClassLoader (a GlobalRef so it survives across + /// thread attaches). Why: env.find_class() uses the *system* ClassLoader + /// when called from a Rust-spawned thread, which doesn't know about + /// app-bundled classes (org.ratspeak.android.*) — they ClassNotFoundException. + /// We must instead route loadClass() through the Application context's + /// loader to reach the app's DEX. + static APP_CLASS_LOADER: OnceLock = OnceLock::new(); + + fn ensure_class_loader(env: &jni::JNIEnv) -> Result<&'static jni::objects::GlobalRef, String> { + if APP_CLASS_LOADER.get().is_none() { + let context = get_app_context(env)?; + let loader = env + .call_method(context, "getClassLoader", "()Ljava/lang/ClassLoader;", &[]) + .map_err(|e| { + jni_clear(env); + format!("getClassLoader: {e}") + })? + .l() + .map_err(|e| format!("ClassLoader cast: {e}"))?; + let global = env + .new_global_ref(loader) + .map_err(|e| format!("global ref: {e}"))?; + let _ = APP_CLASS_LOADER.set(global); + } + APP_CLASS_LOADER + .get() + .ok_or_else(|| "ClassLoader not initialized".to_string()) + } + + /// Resolve a Ratspeak app class (e.g. "org.ratspeak.android.RatspeakBleServer") + /// via the application ClassLoader. Use this — not env.find_class — for + /// any org/ratspeak/android/* class. Accepts dotted form. + fn find_app_class<'a>( + env: &'a jni::JNIEnv, + dotted: &str, + ) -> Result, String> { + let loader = ensure_class_loader(env)?; + let name = env + .new_string(dotted) + .map_err(|e| format!("class name: {e}"))?; + let cls = env + .call_method( + loader.as_obj(), + "loadClass", + "(Ljava/lang/String;)Ljava/lang/Class;", + &[JValue::Object(name.into())], + ) + .map_err(|e| { + jni_clear(env); + format!("loadClass({dotted}): {e}") + })? + .l() + .map_err(|e| format!("Class cast: {e}"))?; + Ok(jni::objects::JClass::from(cls)) + } + + pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> { + // Set up inbound channel for GATT server write callbacks (see INBOUND_TX docs) + let (tx, rx) = tokio::sync::mpsc::channel::<(String, Vec)>(INBOUND_CAPACITY); + let _ = INBOUND_TX.set(tx); + let _ = INBOUND_RX.set(std::sync::Mutex::new(Some(rx))); + + let id_hash = identity_hash.to_vec(); + tokio::task::spawn_blocking(move || { + with_env(|env| { + // ── 1. Open GATT Server ── + let context = get_app_context(env)?; + let id_bytes = env.byte_array_from_slice(&id_hash) + .map_err(|e| format!("byte_array: {e}"))?; + + let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer") + .map_err(|e| format!("RatspeakBleServer class: {e}"))?; + let opened = env.call_static_method( + server_cls, "openGattServer", + "(Landroid/content/Context;[B)Z", + &[JValue::Object(context), JValue::Object(JObject::from(id_bytes))], + ).map_err(|e| format!("openGattServer: {e}"))?.z().unwrap_or(false); + + if !opened { + tracing::warn!("Android BLE Peripheral: GATT server failed to open"); + } else { + tracing::info!("Android BLE Peripheral: GATT server opened"); + } + + // ── 2. Start BLE Advertising ── + // Use BluetoothManager.getAdapter() (modern API), not the + // deprecated BluetoothAdapter.getDefaultAdapter() which + // throws SecurityException on Android 12+ without the + // BLUETOOTH_CONNECT permission and is removed on some 14+ + // vendor builds. + let adapter = get_bluetooth_adapter(env, context)?; + + let advertiser = env.call_method( + adapter, "getBluetoothLeAdvertiser", + "()Landroid/bluetooth/le/BluetoothLeAdvertiser;", &[], + ).map_err(|e| { jni_clear(env); format!("getBluetoothLeAdvertiser: {e}") })? + .l().map_err(|e| format!("{e}"))?; + if advertiser.is_null() { + return Err("BluetoothLeAdvertiser unavailable (multi-adv not supported?)".into()); + } + + // Build AdvertiseSettings + let settings_cls = env.find_class("android/bluetooth/le/AdvertiseSettings$Builder") + .map_err(|e| format!("{e}"))?; + let builder = env.new_object(settings_cls, "()V", &[]).map_err(|e| format!("{e}"))?; + env.call_method(builder, "setAdvertiseMode", + "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;", + &[JValue::Int(1)]).ok(); // BALANCED + jni_clear(env); + env.call_method(builder, "setTxPowerLevel", + "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;", + &[JValue::Int(3)]).ok(); // HIGH + jni_clear(env); + env.call_method(builder, "setConnectable", + "(Z)Landroid/bluetooth/le/AdvertiseSettings$Builder;", + &[JValue::Bool(1)]).ok(); + jni_clear(env); + let settings = env.call_method(builder, "build", + "()Landroid/bluetooth/le/AdvertiseSettings;", &[]) + .map_err(|e| { jni_clear(env); format!("{e}") })? + .l().map_err(|e| format!("{e}"))?; + + // Advertise only the primary Ratspeak service UUID. Two + // 128-bit UUIDs (32 bytes) overflow the 31-byte BLE 4.x + // advertising PDU and the advertiser reports + // ADVERTISE_FAILED_DATA_TOO_LARGE. Columba remains registered + // as a GATT service and is discovered after connect. + let data_cls = env.find_class("android/bluetooth/le/AdvertiseData$Builder") + .map_err(|e| format!("{e}"))?; + let data_b = env.new_object(data_cls, "()V", &[]).map_err(|e| format!("{e}"))?; + + let uuid_cls = env.find_class("java/util/UUID").map_err(|e| format!("{e}"))?; + let puuid_cls = env.find_class("android/os/ParcelUuid").map_err(|e| format!("{e}"))?; + + let r_str = env.new_string(RATSPEAK_SERVICE_UUID.to_string()).map_err(|e| format!("{e}"))?; + let r_uuid = env.call_static_method(uuid_cls, "fromString", + "(Ljava/lang/String;)Ljava/util/UUID;", + &[JValue::Object(r_str.into())]) + .map_err(|e| { jni_clear(env); format!("{e}") })? + .l().map_err(|e| format!("{e}"))?; + let r_puuid = env.new_object(puuid_cls, "(Ljava/util/UUID;)V", + &[JValue::Object(r_uuid)]).map_err(|e| format!("{e}"))?; + env.call_method(data_b, "addServiceUuid", + "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;", + &[JValue::Object(r_puuid)]).ok(); + jni_clear(env); + + let ad_data = env.call_method(data_b, "build", + "()Landroid/bluetooth/le/AdvertiseData;", &[]) + .map_err(|e| { jni_clear(env); format!("{e}") })? + .l().map_err(|e| format!("{e}"))?; + + // Create AdvertiseCallback + let callback_cls = find_app_class(env, "org.ratspeak.android.RatspeakAdvertiseCallback") + .map_err(|e| format!("RatspeakAdvertiseCallback class not found: {e}"))?; + let callback = env.new_object(callback_cls, "()V", &[]) + .map_err(|e| { jni_clear(env); format!("RatspeakAdvertiseCallback init: {e}") })?; + let callback_ref = env.new_global_ref(callback).map_err(|e| format!("{e}"))?; + + env.call_method(advertiser, "startAdvertising", + "(Landroid/bluetooth/le/AdvertiseSettings;Landroid/bluetooth/le/AdvertiseData;Landroid/bluetooth/le/AdvertiseCallback;)V", + &[JValue::Object(settings), JValue::Object(ad_data), JValue::Object(callback_ref.as_obj())]) + .map_err(|e| { jni_clear(env); format!("startAdvertising: {e}") })?; + + let _ = ADVERTISER_REF.set(env.new_global_ref(advertiser).map_err(|e| format!("{e}"))?); + let _ = CALLBACK_REF.set(callback_ref); + tracing::info!("Android BLE Peripheral: advertising started"); + Ok(()) + }) + }).await.map_err(|e| format!("{e}"))? + } + + pub async fn stop_advertising() -> Result<(), String> { + tokio::task::spawn_blocking(|| { + // Close GATT server + with_env(|env| { + let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer") + .map_err(|e| format!("{e}"))?; + env.call_static_method(server_cls, "closeGattServer", "()V", &[]) + .map_err(|e| format!("closeGattServer: {e}"))?; + Ok(()) + }) + .ok(); + + // Stop advertising + if let Some(adv) = ADVERTISER_REF.get() { + with_env(|env| { + let cb = CALLBACK_REF + .get() + .map(|r| r.as_obj()) + .unwrap_or(JObject::null()); + env.call_method( + adv.as_obj(), + "stopAdvertising", + "(Landroid/bluetooth/le/AdvertiseCallback;)V", + &[JValue::Object(cb)], + ) + .map_err(|e| format!("{e}"))?; + tracing::info!("Android BLE Peripheral: advertising stopped"); + Ok(()) + })?; + } + Ok(()) + }) + .await + .map_err(|e| format!("{e}"))? + } + + // ── JNI native methods called by RatspeakGattCallback.kt ── + // + // Use raw jni::sys types in extern signatures to avoid lifetime issues + // (JObject<'a> / JString<'a> can't be expressed in extern "system" fns). + + /// Called when a remote peer writes data to the RX characteristic. + /// The `address` parameter is the source BluetoothDevice MAC; we tag the + /// inbound packet with it so the consumer can keep per-peer reassembly state + /// and skip relaying the packet back to the same peer (anti-loop). + #[unsafe(no_mangle)] + pub extern "system" fn Java_org_ratspeak_android_RatspeakGattCallback_nativeBleGattDataReceived( + env: jni::JNIEnv, + _this: jni::sys::jobject, + address: jni::sys::jstring, + data: jni::sys::jbyteArray, + ) { + let addr = jstring_to_owned(&env, address); + if let Ok(bytes) = env.convert_byte_array(data) { + on_gatt_data_received(addr, bytes); + } + } + + /// Called when a remote peer connects to the GATT server. + /// Wired into the BlePeerEvent dispatcher for real-time connect events. + #[unsafe(no_mangle)] + pub extern "system" fn Java_org_ratspeak_android_RatspeakGattCallback_nativeBleGattPeerConnected( + env: jni::JNIEnv, + _this: jni::sys::jobject, + address: jni::sys::jstring, + ) { + let addr = jstring_to_owned(&env, address); + if !addr.is_empty() { + tracing::info!(peer = %addr, "Android GATT: peer connected"); + super::dispatch_event(BlePeerEvent::Connected { + address: addr, + identity_hash: String::new(), + protocol: PeerProtocol::Ratspeak, + }); + } + } + + /// Remote peer enabled CCCD on the TX characteristic. Triggers an + /// immediate announce so identity is exchanged on first contact. + #[unsafe(no_mangle)] + pub extern "system" fn Java_org_ratspeak_android_RatspeakGattCallback_nativeBleGattPeerSubscribed( + env: jni::JNIEnv, + _this: jni::sys::jobject, + address: jni::sys::jstring, + ) { + let addr = jstring_to_owned(&env, address); + if !addr.is_empty() { + tracing::info!(peer = %addr, "Android GATT: peer subscribed to TX"); + super::dispatch_event(BlePeerEvent::SubscribeReady { address: addr }); + } + } + + /// Called when a remote peer disconnects from the GATT server. + #[unsafe(no_mangle)] + pub extern "system" fn Java_org_ratspeak_android_RatspeakGattCallback_nativeBleGattPeerDisconnected( + env: jni::JNIEnv, + _this: jni::sys::jobject, + address: jni::sys::jstring, + ) { + let addr = jstring_to_owned(&env, address); + if !addr.is_empty() { + tracing::info!(peer = %addr, "Android GATT: peer disconnected"); + super::dispatch_event(BlePeerEvent::Disconnected { + address: addr, + reason: "GATT disconnect".into(), + }); + } + } + + /// Helper: convert a possibly-null jstring into an owned Rust String, + /// falling back to empty on conversion failure. + fn jstring_to_owned(env: &jni::JNIEnv, raw: jni::sys::jstring) -> String { + if raw.is_null() { + return String::new(); + } + let jstr: jni::objects::JString = unsafe { jni::objects::JObject::from(raw) }.into(); + env.get_string(jstr) + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + } + + /// Push a notification to a specific connected GATT-server peer over the named + /// TX characteristic. Returns false if the JVM bridge is unavailable or the + /// Kotlin call fails. Used by the spawn function's outbound fan-out. + pub fn notify_tx(peer_address: &str, char_uuid: Uuid, data: &[u8]) -> bool { + with_env(|env| { + let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer") + .map_err(|e| format!("RatspeakBleServer class: {e}"))?; + let addr_str = env + .new_string(peer_address) + .map_err(|e| format!("addr string: {e}"))?; + let uuid_str = env + .new_string(char_uuid.to_string()) + .map_err(|e| format!("uuid string: {e}"))?; + let payload = env + .byte_array_from_slice(data) + .map_err(|e| format!("byte array: {e}"))?; + let ok = env + .call_static_method( + server_cls, + "notifyTx", + "(Ljava/lang/String;Ljava/lang/String;[B)Z", + &[ + JValue::Object(addr_str.into()), + JValue::Object(uuid_str.into()), + JValue::Object(JObject::from(payload)), + ], + ) + .map_err(|e| format!("notifyTx call: {e}"))? + .z() + .unwrap_or(false); + Ok(ok) + }) + .unwrap_or(false) + } + + /// Snapshot of GATT-server-side central addresses currently subscribed to + /// the named TX characteristic. The fan-out enumerates this list and + /// filters per peer through the in-process anti-loop map before issuing + /// individual `notify_tx` calls. + pub fn subscribed_addresses_for(char_uuid: Uuid) -> Vec { + with_env(|env| { + let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer") + .map_err(|e| format!("RatspeakBleServer class: {e}"))?; + let uuid_str = env + .new_string(char_uuid.to_string()) + .map_err(|e| format!("uuid string: {e}"))?; + let result = env + .call_static_method( + server_cls, + "subscribedAddressesFor", + "(Ljava/lang/String;)Ljava/lang/String;", + &[JValue::Object(uuid_str.into())], + ) + .map_err(|e| format!("subscribedAddressesFor call: {e}"))? + .l() + .map_err(|e| format!("subscribedAddressesFor result: {e}"))?; + let jstr: jni::objects::JString = result.into(); + let owned = env + .get_string(jstr) + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + if owned.is_empty() { + Ok(Vec::new()) + } else { + Ok(owned.split('\n').map(|s| s.to_string()).collect()) + } + }) + .unwrap_or_default() + } + + /// Broadcast a notification to every subscribed central on the named TX + /// characteristic, optionally excluding `exclude_address` (used by the + /// anti-loop filter to skip echoing a packet back to the peer it arrived + /// from). Returns the number of subscribers we attempted to notify. + pub fn broadcast_notify_tx(char_uuid: Uuid, data: &[u8], exclude_address: Option<&str>) -> i32 { + with_env(|env| { + let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer") + .map_err(|e| format!("RatspeakBleServer class: {e}"))?; + let uuid_str = env + .new_string(char_uuid.to_string()) + .map_err(|e| format!("uuid string: {e}"))?; + let payload = env + .byte_array_from_slice(data) + .map_err(|e| format!("byte array: {e}"))?; + let exclude_obj = match exclude_address { + Some(a) => JObject::from( + env.new_string(a) + .map_err(|e| format!("exclude string: {e}"))?, + ), + None => JObject::null(), + }; + let count = env + .call_static_method( + server_cls, + "broadcastTx", + "(Ljava/lang/String;[BLjava/lang/String;)I", + &[ + JValue::Object(uuid_str.into()), + JValue::Object(JObject::from(payload)), + JValue::Object(exclude_obj), + ], + ) + .map_err(|e| format!("broadcastTx call: {e}"))? + .i() + .unwrap_or(0); + Ok(count) + }) + .unwrap_or(0) + } + + // ── Native Central role (Kotlin RatspeakBlePeerClient) ── + // + // btleplug's Android backend is broken on Android 14+ (deprecated + // `BluetoothAdapter.getDefaultAdapter()` and `connectGatt(null, ...)`), + // so we drive the Central role through a native Kotlin GATT client just + // like RNode BLE does. The Rust side owns the peer-connection state + // machine; the Kotlin side just hosts GATT plumbing and forwards bytes. + + /// Inbound from a peer client (we connected as Central). Funnels into the + /// same per-peer reassembly channel the GATT server uses — the consumer + /// in `spawn_ble_peer_interface` keys off `address` so packets from the + /// two roles never collide. + #[unsafe(no_mangle)] + pub extern "system" fn Java_org_ratspeak_android_RatspeakBlePeerClient_nativePeerClientDataReceived( + env: jni::JNIEnv, + _this: jni::sys::jobject, + address: jni::sys::jstring, + data: jni::sys::jbyteArray, + ) { + let addr = jstring_to_owned(&env, address); + if let Ok(bytes) = env.convert_byte_array(data) { + on_gatt_data_received(addr, bytes); + } + } + + /// A peer client connection dropped (centrally-initiated side). + /// We emit a Disconnected event so the mesh-state task can prune it + /// without waiting for a keepalive miss. + #[unsafe(no_mangle)] + pub extern "system" fn Java_org_ratspeak_android_RatspeakBlePeerClient_nativePeerClientDisconnected( + env: jni::JNIEnv, + _this: jni::sys::jobject, + address: jni::sys::jstring, + ) { + let addr = jstring_to_owned(&env, address); + if !addr.is_empty() { + tracing::info!(peer = %addr, "Android peer client: disconnected"); + // Flip the central task's per-peer `online` flag so its write loop + // exits and the connected_addrs entry gets pruned on the next cycle. + signal_peer_offline(&addr); + super::dispatch_event(BlePeerEvent::Disconnected { + address: addr, + reason: "peer client GATT disconnect".into(), + }); + } + } + + /// Connect → discover services → subscribe to notifications. Identity + /// flows in via the first signed announce afterwards. Blocking — must + /// run on `spawn_blocking` because the Kotlin side uses CountDownLatches + /// that deadlock on the GATT callback thread. + pub fn peer_client_connect(address: &str) -> Result<(), String> { + with_env(|env| { + let context = get_app_context(env)?; + let cls = find_app_class(env, "org.ratspeak.android.RatspeakBlePeerClient") + .map_err(|e| format!("RatspeakBlePeerClient class: {e}"))?; + let addr_str = env + .new_string(address) + .map_err(|e| format!("addr string: {e}"))?; + let ok = env + .call_static_method( + cls, + "connectFromNative", + "(Landroid/content/Context;Ljava/lang/String;)Z", + &[JValue::Object(context), JValue::Object(addr_str.into())], + ) + .map_err(|e| format!("connectFromNative: {e}"))? + .z() + .map_err(|e| format!("{e}"))?; + if !ok { + return Err("peer connect failed".into()); + } + Ok(()) + }) + } + + /// Push outbound bytes to a connected peer (Central side). The caller is + /// responsible for fragmentation. Returns false if the address has no + /// live client or the JNI call fails. + pub fn peer_client_write(address: &str, data: &[u8]) -> bool { + with_env(|env| { + let cls = find_app_class(env, "org.ratspeak.android.RatspeakBlePeerClient") + .map_err(|e| format!("RatspeakBlePeerClient class: {e}"))?; + let addr_str = env + .new_string(address) + .map_err(|e| format!("addr string: {e}"))?; + let payload = env + .byte_array_from_slice(data) + .map_err(|e| format!("byte array: {e}"))?; + let ok = env + .call_static_method( + cls, + "write", + "(Ljava/lang/String;[B)Z", + &[ + JValue::Object(addr_str.into()), + JValue::Object(JObject::from(payload)), + ], + ) + .map_err(|e| format!("write: {e}"))? + .z() + .unwrap_or(false); + Ok(ok) + }) + .unwrap_or(false) + } + + /// Minimum negotiated ATT payload across every central subscribed to + /// `char_uuid` on our GATT server. Used by the peripheral broadcast + /// fan-out to size fragments so a single notify reaches everyone. + /// Falls back to 244 bytes when no subscribers. + pub fn min_subscribed_payload(char_uuid: Uuid) -> usize { + const FALLBACK: usize = 244; + let v = with_env(|env| { + let cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer") + .map_err(|e| format!("RatspeakBleServer class: {e}"))?; + let uuid_str = env + .new_string(char_uuid.to_string()) + .map_err(|e| format!("uuid string: {e}"))?; + let mtu = env + .call_static_method( + cls, + "getMinSubscribedPayload", + "(Ljava/lang/String;)I", + &[JValue::Object(uuid_str.into())], + ) + .map_err(|e| format!("getMinSubscribedPayload: {e}"))? + .i() + .map_err(|e| format!("{e}"))?; + Ok(mtu) + }) + .unwrap_or(FALLBACK as i32); + if v <= 0 { FALLBACK } else { v as usize } + } + + /// Negotiated payload size (MTU - 3) for the Central-side peer client at + /// `address`. Returns the conservative 244-byte default if the bridge is + /// unavailable, the address has no live client, or MTU negotiation hasn't + /// completed. Used by the per-peer write loop to size fragments. + pub fn peer_client_mtu(address: &str) -> usize { + const FALLBACK: usize = 244; + let v = with_env(|env| { + let cls = find_app_class(env, "org.ratspeak.android.RatspeakBlePeerClient") + .map_err(|e| format!("RatspeakBlePeerClient class: {e}"))?; + let addr_str = env + .new_string(address) + .map_err(|e| format!("addr string: {e}"))?; + let mtu = env + .call_static_method( + cls, + "getMtu", + "(Ljava/lang/String;)I", + &[JValue::Object(addr_str.into())], + ) + .map_err(|e| format!("getMtu: {e}"))? + .i() + .map_err(|e| format!("{e}"))?; + Ok(mtu) + }) + .unwrap_or(FALLBACK as i32); + if v <= 0 { FALLBACK } else { v as usize } + } + + /// Tear down the peer client connection for `address`. Idempotent. + pub fn peer_client_disconnect(address: &str) { + let _ = with_env(|env| { + let cls = find_app_class(env, "org.ratspeak.android.RatspeakBlePeerClient") + .map_err(|e| format!("RatspeakBlePeerClient class: {e}"))?; + let addr_str = env + .new_string(address) + .map_err(|e| format!("addr string: {e}"))?; + env.call_static_method( + cls, + "disconnect", + "(Ljava/lang/String;)V", + &[JValue::Object(addr_str.into())], + ) + .map_err(|e| format!("disconnect: {e}"))?; + Ok::<(), String>(()) + }); + } + + /// Scan for nearby BLE mesh peers using a service-UUID filter at the + /// radio firmware level (battery-efficient). Returns + /// `(address, rssi, protocol)` tuples. Blocking — runs on `spawn_blocking`. + pub fn peer_scan_mesh(timeout_ms: i64) -> Vec<(String, i16, PeerProtocol)> { + with_env(|env| { + let context = get_app_context(env)?; + let cls = find_app_class(env, "org.ratspeak.android.RatspeakBlePeerClient") + .map_err(|e| format!("RatspeakBlePeerClient class: {e}"))?; + let result = env + .call_static_method( + cls, + "scanMesh", + "(Landroid/content/Context;J)[Ljava/lang/String;", + &[JValue::Object(context), JValue::Long(timeout_ms)], + ) + .map_err(|e| format!("scanMesh: {e}"))? + .l() + .map_err(|e| format!("{e}"))?; + if result.is_null() { + return Ok(Vec::new()); + } + let arr = result.into_inner(); + let len = env + .get_array_length(arr) + .map_err(|e| format!("array len: {e}"))?; + let mut out = Vec::with_capacity(len as usize); + for i in 0..len { + let item = env + .get_object_array_element(arr, i) + .map_err(|e| format!("array idx: {e}"))?; + let s: jni::objects::JString = item.into(); + let owned = env + .get_string(s) + .map(|js| js.to_string_lossy().into_owned()) + .unwrap_or_default(); + if owned.is_empty() { + continue; + } + let parts: Vec<&str> = owned.split('|').collect(); + if parts.len() != 3 { + continue; + } + let rssi = parts[1].parse::().unwrap_or(-100); + let protocol = if parts[2] == "ratspeak" { + PeerProtocol::Ratspeak + } else { + PeerProtocol::Columba + }; + out.push((parts[0].to_string(), rssi, protocol)); + } + Ok(out) + }) + .unwrap_or_default() + } +} + +// --------------------------------------------------------------------------- +// Linux Peripheral (BlueZ GATT server via bluer) +// --------------------------------------------------------------------------- + +#[cfg(target_os = "linux")] +mod linux_peripheral { + //! Real BLE Peripheral on Linux via the `bluer` crate (BlueZ D-Bus). + //! + //! Symmetric counterpart to the Apple/Android peripheral modules: registers + //! the Ratspeak + Columba GATT services, accepts connections from peer + //! centrals, funnels inbound writes through a per-process channel that the + //! spawn function's reassembler consumes (matching the apple/android shape), + //! and exposes a `notify_tx` for the outbound fan-out. + //! + //! Requires BlueZ 5.46+; on older distros the user may need + //! `Experimental = true` in /etc/bluetooth/main.conf for full GATT server + //! support. Registration failures are surfaced as clear UI-facing errors. + use super::*; + use bluer::adv::Advertisement; + use bluer::gatt::local::{ + Application, ApplicationHandle, Characteristic, CharacteristicNotifier, + CharacteristicNotify, CharacteristicNotifyMethod, CharacteristicRead, CharacteristicWrite, + CharacteristicWriteMethod, Service, + }; + use std::sync::OnceLock; + use tokio::sync::Mutex as AsyncMutex; + use tokio::sync::mpsc; + use uuid::Uuid; + + /// Per-process inbound channel — write callbacks push (peer_address, data) + /// pairs that the spawn function's per-peer reassembler consumes. + type InboundFrame = (String, Vec); + type InboundReceiver = mpsc::Receiver; + type InboundReceiverSlot = std::sync::Mutex>; + + static INBOUND_TX: OnceLock> = OnceLock::new(); + static INBOUND_RX: OnceLock = OnceLock::new(); + + /// Per-characteristic notifier registry keyed by TX char UUID. Each value + /// is the latest bluer `CharacteristicNotifier` handed to us by the most + /// recent subscribe; we call `.notify(payload)` on it from notify_tx. + /// `None` means no central is currently subscribed. + type NotifierMap = Arc>>>; + static NOTIFIERS: OnceLock = OnceLock::new(); + + /// App + advertisement handles — held to keep the registration alive for + /// the lifetime of the interface. Dropping these unregisters everything. + static HANDLES: OnceLock< + std::sync::Mutex>, + > = OnceLock::new(); + + fn notifier_map() -> &'static NotifierMap { + NOTIFIERS.get_or_init(|| Arc::new(AsyncMutex::new(HashMap::new()))) + } + + fn handles_slot() + -> &'static std::sync::Mutex> { + HANDLES.get_or_init(|| std::sync::Mutex::new(None)) + } + + /// Drain the inbound channel receiver. The spawn function calls this once + /// at startup and pumps the resulting receiver into the per-peer + /// reassembler. Subsequent calls return `None` so the consumer can't be + /// double-spawned. + pub fn take_inbound_rx() -> Option { + let slot = INBOUND_RX.get_or_init(|| { + let (tx, rx) = mpsc::channel::(256); + // Stash the sender so write callbacks can push into the channel + // even though the receiver is owned by the consumer task. + let _ = INBOUND_TX.set(tx); + std::sync::Mutex::new(Some(rx)) + }); + slot.lock().ok().and_then(|mut g| g.take()) + } + + /// Push a notification on the named TX characteristic. Returns true if + /// there is a live subscriber and the call was queued. The actual + /// notification I/O happens inside bluer asynchronously; we only drive + /// the API call here. + pub fn notify_tx(char_uuid: Uuid, data: &[u8]) -> bool { + let map = notifier_map(); + let payload = data.to_vec(); + // Take the notifier out so we can call `.notify()` (which takes + // `&mut self`) without holding the map lock across an await. + // try_lock failure is rare but not impossible if a subscribe event + // fires concurrently — log it so operators can correlate "notify + // disappeared" with "subscriber rolled in" during handoff. + let notifier_taken = { + let mut g = match map.try_lock() { + Ok(g) => g, + Err(_) => { + tracing::warn!( + target: "ble_trace", + step = "linux_notify.lock_contention", + %char_uuid, + bytes = data.len(), + "Linux BLE notify: notifier map lock contended — dropping payload" + ); + return false; + } + }; + g.get_mut(&char_uuid).and_then(|opt| opt.take()) + }; + if let Some(mut n) = notifier_taken { + let map2 = map.clone(); + tokio::spawn(async move { + if n.notify(payload).await.is_err() { + tracing::warn!( + target: "ble_trace", + step = "linux_notify.notify_failed", + %char_uuid, + "Linux BLE notify failed; central likely dropped" + ); + return; + } + // Reinsert if the notifier is still live. is_stopped() goes + // true once the central unsubscribes or disconnects. + if !n.is_stopped() { + let mut g = map2.lock().await; + g.insert(char_uuid, Some(n)); + } else { + tracing::info!( + target: "ble_trace", + step = "linux_notify.notifier_stopped", + %char_uuid, + "Linux BLE: subscriber dropped — notifier retired from registry" + ); + } + }); + true + } else { + tracing::debug!( + target: "ble_trace", + step = "linux_notify.no_subscriber", + %char_uuid, + bytes = data.len(), + "Linux BLE notify: no subscriber — dropping payload" + ); + false + } + } + + /// Snapshot of TX characteristics currently bound to a notifier sink. The + /// fan-out uses this to decide whether to fragment + push a payload. + /// `pub` for symmetry with the Apple/Windows peripherals' equivalent + /// query — no in-tree caller yet, so the compiler reports it dead. + #[allow(dead_code)] + pub fn subscribed_tx_uuids() -> Vec { + let map = notifier_map(); + match map.try_lock() { + Ok(g) => g + .iter() + .filter(|(_, v)| v.is_some()) + .map(|(k, _)| *k) + .collect(), + Err(_) => Vec::new(), + } + } + + /// Start GATT server + LE advertising. Must be called from a tokio + /// runtime context (bluer needs the current dispatcher). + pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> { + // Ensure inbound channel exists before any write callback fires. + take_inbound_rx_init(); + + let session = bluer::Session::new() + .await + .map_err(|e| format!("bluer session: {e}"))?; + let adapter = session + .default_adapter() + .await + .map_err(|e| format!("bluer default adapter: {e}"))?; + adapter + .set_powered(true) + .await + .map_err(|e| format!("adapter power on: {e}"))?; + + let id_bytes = identity_hash.to_vec(); + let app = Application { + services: vec![ + build_service( + super::RATSPEAK_SERVICE_UUID, + super::RATSPEAK_RX_UUID, + super::RATSPEAK_TX_UUID, + super::RATSPEAK_ID_UUID, + id_bytes.clone(), + ) + .await, + build_service( + super::COLUMBA_SERVICE_UUID, + super::COLUMBA_RX_UUID, + super::COLUMBA_TX_UUID, + super::COLUMBA_ID_UUID, + id_bytes, + ) + .await, + ], + ..Default::default() + }; + let app_handle = match adapter.serve_gatt_application(app).await { + Ok(h) => h, + Err(e) => { + let reason = format!( + "Linux BLE peripheral unavailable: serve_gatt_application: {e}. \ + BlueZ likely needs `Experimental = true` in /etc/bluetooth/main.conf, \ + then `sudo systemctl restart bluetooth`. Mesh continues central-only." + ); + super::dispatch_event(super::BlePeerEvent::PeripheralUnavailable { + reason: reason.clone(), + }); + return Err(reason); + } + }; + + // Advertise only the primary Ratspeak service UUID. Two 128-bit + // UUIDs (32 bytes) plus AD Flags + local name overflow the 31-byte + // legacy BLE adv PDU, and BlueZ rejects the advertisement set with + // kernel mgmt status MGMT_STATUS_INVALID_PARAMS (0x0d) — surfaced + // in `journalctl -u bluetooth` as `src/advertising.c:add_client_complete() + // Failed to add advertisement: Invalid Parameters`. Apple + // (apple_peripheral) and Android (android_peripheral) hit the same + // limit and already drop Columba from the advertised set; Columba + // remains registered as a GATT service and is discovered by centrals + // after connect via primary service discovery. + let mut service_uuids = std::collections::BTreeSet::new(); + service_uuids.insert(super::RATSPEAK_SERVICE_UUID); + let adv = Advertisement { + service_uuids, + discoverable: Some(true), + local_name: Some("Ratspeak".into()), + ..Default::default() + }; + let adv_handle = match adapter.advertise(adv).await { + Ok(h) => h, + Err(e) => { + let reason = format!( + "Linux BLE advertising rejected: {e}. \ + Check `journalctl -u bluetooth` for the kernel mgmt status — \ + `Invalid Parameters` typically means the adv data overflowed \ + 31 bytes; other statuses point to BlueZ/controller config. \ + Mesh continues central-only." + ); + super::dispatch_event(super::BlePeerEvent::PeripheralUnavailable { + reason: reason.clone(), + }); + return Err(reason); + } + }; + + if let Ok(mut slot) = handles_slot().lock() { + *slot = Some((app_handle, adv_handle)); + } + tracing::info!("Linux BLE Peripheral: GATT app + advertising registered via bluer"); + Ok(()) + } + + fn take_inbound_rx_init() { + // Cheap idempotent init so write callbacks always have a sender even + // before the consumer takes the receiver. + let _ = INBOUND_RX.get_or_init(|| { + let (tx, rx) = mpsc::channel::(256); + let _ = INBOUND_TX.set(tx); + std::sync::Mutex::new(Some(rx)) + }); + } + + async fn build_service( + service_uuid: Uuid, + rx_uuid: Uuid, + tx_uuid: Uuid, + id_uuid: Uuid, + identity_hash: Vec, + ) -> Service { + // Inbound RX: peer writes here, we push (peer_addr, data) on the + // shared channel for the spawn function's reassembler. + let rx_uuid_for_trace = rx_uuid; + let rx_char = Characteristic { + uuid: rx_uuid, + write: Some(CharacteristicWrite { + write: true, + write_without_response: true, + method: CharacteristicWriteMethod::Fun(Box::new(move |new_value, req| { + let addr = req.device_address.to_string(); + let char_uuid = rx_uuid_for_trace; + let byte_len = new_value.len(); + Box::pin(async move { + if let Some(tx) = INBOUND_TX.get() + && let Err(e) = tx.try_send((addr.clone(), new_value)) + { + // Channel full — log so operators see the + // backpressure signal instead of finding + // silent fragment loss. + tracing::warn!( + target: "ble_trace", + step = "linux_rx.channel_full", + peer = %addr, + %char_uuid, + bytes = byte_len, + err = %e, + "Linux BLE RX: inbound channel full, dropping frame" + ); + } + Ok(()) + }) + })), + ..Default::default() + }), + ..Default::default() + }; + + // Outbound TX: notify on subscribe. bluer hands the callback a + // `CharacteristicNotifier` per subscribe; we stash it keyed by char + // UUID so notify_tx can find it. Only the latest subscriber's + // notifier is kept (one central per TX char in the common mesh case). + let tx_uuid_for_notify = tx_uuid; + let tx_char = Characteristic { + uuid: tx_uuid, + notify: Some(CharacteristicNotify { + notify: true, + method: CharacteristicNotifyMethod::Fun(Box::new(move |notifier| { + let uuid = tx_uuid_for_notify; + Box::pin(async move { + let map = notifier_map(); + let mut g = map.lock().await; + let displaced = g.insert(uuid, Some(notifier)).is_some(); + tracing::info!( + target: "ble_trace", + step = "linux_notify.subscribe", + char_uuid = %uuid, + displaced, + "Linux BLE: central subscribed to TX characteristic" + ); + }) + })), + ..Default::default() + }), + ..Default::default() + }; + + // ID: static 16-byte Reticulum identity hash, read-only. + let id_bytes = identity_hash; + let id_char = Characteristic { + uuid: id_uuid, + read: Some(CharacteristicRead { + read: true, + fun: Box::new(move |_| { + let bytes = id_bytes.clone(); + Box::pin(async move { Ok(bytes) }) + }), + ..Default::default() + }), + ..Default::default() + }; + + Service { + uuid: service_uuid, + primary: true, + characteristics: vec![rx_char, tx_char, id_char], + ..Default::default() + } + } + + pub async fn stop_advertising() -> Result<(), String> { + let dropped_handles = { + if let Ok(mut slot) = handles_slot().lock() { + // Dropping the handles unregisters the GATT app + advertising. + slot.take().is_some() + } else { + false + } + }; + // Clear notifier sinks — they reference a dropped service handle now. + // Fall back to the async lock if try_lock is contended so we don't + // leak a live notifier that would attempt to notify into a retired + // service. The operation is fast (no await across service ops). + let cleared_notifiers = { + let mut g = notifier_map().lock().await; + let count = g.len(); + g.clear(); + count + }; + tracing::info!( + target: "ble_trace", + step = "linux_peripheral.stop", + dropped_handles, + cleared_notifiers, + "Linux BLE Peripheral: GATT app + advertising deregistered" + ); + Ok(()) + } +} + +#[cfg(target_os = "windows")] +mod windows_peripheral { + //! Windows BLE Peripheral via WinRT `GattServiceProvider`. + //! + //! Works on Windows 10 1809+ for MSIX-packaged apps with the + //! `bluetoothGenericAttributeProfile` capability. Unpackaged Win32 apps + //! hit `AccessDenied` on `CreateAsync` — we detect that path and fall + //! back to central-only with a clear `PeripheralUnavailable` event so + //! embedding UIs can direct users toward a packaged installer. + //! + //! Writes from connected centrals route through a per-process + //! (peer_address, data) channel that the spawn function's reassembler + //! consumes, matching the Apple/Android/Linux shape. Notifications are + //! driven by the outbound fan-out through `notify_tx` — bluer-style, + //! one notifier per characteristic UUID (the common 1-central-per-char + //! case; Windows doesn't surface the subscriber identity in the subscribe + //! event without extra plumbing). + use super::*; + use std::sync::{Mutex, OnceLock}; + use tokio::sync::mpsc; + use windows::Devices::Bluetooth::GenericAttributeProfile::{ + GattCharacteristicProperties, GattLocalCharacteristic, GattLocalCharacteristicParameters, + GattProtectionLevel, GattServiceProvider, GattServiceProviderAdvertisingParameters, + GattSubscribedClient, + }; + use windows::Foundation::TypedEventHandler; + use windows::Storage::Streams::{DataReader, DataWriter}; + use windows::core::GUID; + + /// Per-process inbound channel. `GattLocalCharacteristic` write events + /// push `(session_id_string, data)` pairs on the sender; the spawn + /// function's reassembler consumes them via `take_inbound_rx`. + static INBOUND_TX: OnceLock)>> = OnceLock::new(); + static INBOUND_RX: OnceLock)>>>> = OnceLock::new(); + + /// Held state across a single start/stop cycle. `_provider` keeps the + /// service registration alive; `_tx_chars` keeps the notifiable + /// characteristics alive; `_handlers` keeps the ValueChanged / + /// SubscribedClientsChanged event registrations alive (dropping the + /// registration token leaves the handler orphaned but linked — the + /// runtime will still invoke it; holding them lets us cleanly detach). + /// + /// Stored as a homogeneous `Option` under a single mutex so + /// `stop_advertising` can atomically take + drop the whole bundle. + struct Inner { + provider_ratspeak: GattServiceProvider, + provider_columba: GattServiceProvider, + tx_chars: std::collections::HashMap, + } + static INNER: OnceLock>> = OnceLock::new(); + + fn inner_slot() -> &'static Mutex> { + INNER.get_or_init(|| Mutex::new(None)) + } + + fn ensure_inbound_channel() { + let _ = INBOUND_RX.get_or_init(|| { + let (tx, rx) = mpsc::channel::<(String, Vec)>(256); + let _ = INBOUND_TX.set(tx); + Mutex::new(Some(rx)) + }); + } + + pub fn take_inbound_rx() -> Option)>> { + ensure_inbound_channel(); + INBOUND_RX + .get() + .and_then(|m| m.lock().ok()) + .and_then(|mut opt| opt.take()) + } + + fn uuid_to_guid(u: uuid::Uuid) -> GUID { + let (d1, d2, d3, d4) = u.as_fields(); + GUID::from_values(d1, d2, d3, *d4) + } + + /// Build one service (RX write, TX notify, ID read) and hand back the + /// started provider. Returns the TX characteristic so the caller can + /// stash it in the registry for notify_tx lookups. + /// + /// Blocking: uses `IAsyncOperation::get()` to wait on WinRT async calls + /// instead of `.await`. `windows` 0.58 has an awkward `IntoFuture` + /// story that doesn't cleanly mesh with Rust `.await`; blocking is + /// fine here because this is called once per start/stop cycle from + /// `start_advertising`, which wraps the whole thing in + /// `tokio::task::spawn_blocking` so the executor isn't stalled. + fn build_and_start_service( + service_uuid: uuid::Uuid, + rx_uuid: uuid::Uuid, + tx_uuid: uuid::Uuid, + id_uuid: uuid::Uuid, + identity_hash: &[u8], + ) -> Result<(GattServiceProvider, GattLocalCharacteristic), String> { + let svc_guid = uuid_to_guid(service_uuid); + let create_result = GattServiceProvider::CreateAsync(svc_guid) + .map_err(|e| format!("GattServiceProvider::CreateAsync call: {e}"))? + .get() + .map_err(|e| format!("GattServiceProvider::CreateAsync get: {e}"))?; + if create_result + .Error() + .map_err(|e| format!("CreateResult.Error(): {e}"))? + .0 + != 0 + { + return Err(format!( + "GattServiceProvider creation returned BluetoothError {:?} — likely missing MSIX \ + packaging or `bluetoothGenericAttributeProfile` capability", + create_result.Error().ok() + )); + } + let provider = create_result + .ServiceProvider() + .map_err(|e| format!("CreateResult.ServiceProvider(): {e}"))?; + let service = provider + .Service() + .map_err(|e| format!("ServiceProvider.Service(): {e}"))?; + + // RX characteristic — client writes here. + let rx_params = + GattLocalCharacteristicParameters::new().map_err(|e| format!("rx params: {e}"))?; + rx_params + .SetCharacteristicProperties( + GattCharacteristicProperties::Write + | GattCharacteristicProperties::WriteWithoutResponse, + ) + .map_err(|e| format!("rx props: {e}"))?; + rx_params + .SetWriteProtectionLevel(GattProtectionLevel::Plain) + .map_err(|e| format!("rx write protection: {e}"))?; + let rx_create = service + .CreateCharacteristicAsync(uuid_to_guid(rx_uuid), &rx_params) + .map_err(|e| format!("rx create call: {e}"))? + .get() + .map_err(|e| format!("rx create get: {e}"))?; + let rx_char = rx_create + .Characteristic() + .map_err(|e| format!("rx Characteristic(): {e}"))?; + // Write handler: pull bytes out of the request's Value, push on the + // inbound channel with the session's DeviceId as peer identifier. + let handler = TypedEventHandler::< + GattLocalCharacteristic, + windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs, + >::new(move |_sender, args| { + let args = match args { + Some(a) => a, + None => return Ok(()), + }; + let deferral = args.GetDeferral().ok(); + let session = args.Session()?; + // BluetoothDeviceId isn't stringable directly; go through its + // HSTRING `.Id()`, then use HSTRING's Display impl + // (UTF-16 lossy) via ToString. Used purely as a peer-address + // key for fan-out / anti-loop — format just needs to be stable + // per device for the duration of the session. + let device_id = session + .DeviceId() + .ok() + .and_then(|d| d.Id().ok()) + .map(|s| s.to_string()) + .unwrap_or_default(); + let request = args.GetRequestAsync()?.get()?; + let buf = request.Value()?; + let reader = DataReader::FromBuffer(&buf)?; + let len = reader.UnconsumedBufferLength()? as usize; + let mut bytes = vec![0u8; len]; + reader.ReadBytes(&mut bytes)?; + if let Some(tx) = INBOUND_TX.get() { + if let Err(e) = tx.try_send((device_id.clone(), bytes)) { + tracing::warn!( + target: "ble_trace", + step = "windows_rx.channel_full", + peer = %device_id, + err = %e, + "Windows BLE RX: inbound channel full, dropping frame" + ); + } + } + let _ = request.Respond(); + if let Some(d) = deferral { + let _ = d.Complete(); + } + Ok(()) + }); + rx_char + .WriteRequested(&handler) + .map_err(|e| format!("rx WriteRequested subscribe: {e}"))?; + + // TX characteristic — we push notifications here via notify_tx. + let tx_params = + GattLocalCharacteristicParameters::new().map_err(|e| format!("tx params: {e}"))?; + tx_params + .SetCharacteristicProperties( + GattCharacteristicProperties::Notify | GattCharacteristicProperties::Read, + ) + .map_err(|e| format!("tx props: {e}"))?; + tx_params + .SetReadProtectionLevel(GattProtectionLevel::Plain) + .map_err(|e| format!("tx read protection: {e}"))?; + let tx_create = service + .CreateCharacteristicAsync(uuid_to_guid(tx_uuid), &tx_params) + .map_err(|e| format!("tx create call: {e}"))? + .get() + .map_err(|e| format!("tx create get: {e}"))?; + let tx_char = tx_create + .Characteristic() + .map_err(|e| format!("tx Characteristic(): {e}"))?; + // Subscribe log so operators can correlate "notify failed" with + // "no subscribers yet". + let char_uuid_for_log = tx_uuid; + let sub_handler = + TypedEventHandler::::new( + move |sender, _args| { + let count = match sender { + Some(c) => c.SubscribedClients().and_then(|v| v.Size()).unwrap_or(0), + None => 0, + }; + tracing::info!( + target: "ble_trace", + step = "windows_notify.subscribers_changed", + char_uuid = %char_uuid_for_log, + count, + "Windows BLE: subscribers changed" + ); + Ok(()) + }, + ); + tx_char + .SubscribedClientsChanged(&sub_handler) + .map_err(|e| format!("tx SubscribedClientsChanged subscribe: {e}"))?; + + // ID characteristic — static read-only identity hash. + let id_params = + GattLocalCharacteristicParameters::new().map_err(|e| format!("id params: {e}"))?; + id_params + .SetCharacteristicProperties(GattCharacteristicProperties::Read) + .map_err(|e| format!("id props: {e}"))?; + id_params + .SetReadProtectionLevel(GattProtectionLevel::Plain) + .map_err(|e| format!("id read protection: {e}"))?; + let writer = DataWriter::new().map_err(|e| format!("id DataWriter::new: {e}"))?; + writer + .WriteBytes(identity_hash) + .map_err(|e| format!("id WriteBytes: {e}"))?; + let id_buf = writer + .DetachBuffer() + .map_err(|e| format!("id DetachBuffer: {e}"))?; + id_params + .SetStaticValue(&id_buf) + .map_err(|e| format!("id SetStaticValue: {e}"))?; + let _id_create = service + .CreateCharacteristicAsync(uuid_to_guid(id_uuid), &id_params) + .map_err(|e| format!("id create call: {e}"))? + .get() + .map_err(|e| format!("id create get: {e}"))?; + + // Advertise the service. + let adv_params = GattServiceProviderAdvertisingParameters::new() + .map_err(|e| format!("adv params: {e}"))?; + adv_params + .SetIsConnectable(true) + .map_err(|e| format!("adv IsConnectable: {e}"))?; + adv_params + .SetIsDiscoverable(true) + .map_err(|e| format!("adv IsDiscoverable: {e}"))?; + provider + .StartAdvertisingWithParameters(&adv_params) + .map_err(|e| format!("StartAdvertising: {e}"))?; + + Ok((provider, tx_char)) + } + + pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> { + ensure_inbound_channel(); + + // WinRT GATT setup uses `.get()` internally (see + // build_and_start_service) because windows 0.58 `IAsyncOperation` + // doesn't play well with `.await`. Hop to spawn_blocking so the + // tokio executor isn't parked for the ~tens of ms each service + // registration takes. + let id_hash_rs = identity_hash.to_vec(); + let id_hash_cb = id_hash_rs.clone(); + + // Attempt Ratspeak service first. If CreateAsync fails because the + // app is unpackaged (AccessDenied), surface a user-friendly error + // and bail — further service creates would just repeat the failure. + let ratspeak = match tokio::task::spawn_blocking(move || { + build_and_start_service( + super::RATSPEAK_SERVICE_UUID, + super::RATSPEAK_RX_UUID, + super::RATSPEAK_TX_UUID, + super::RATSPEAK_ID_UUID, + &id_hash_rs, + ) + }) + .await + .map_err(|e| format!("Ratspeak GATT spawn_blocking join: {e}"))? + { + Ok(r) => r, + Err(e) => { + super::dispatch_event(BlePeerEvent::PeripheralUnavailable { + reason: format!( + "Windows BLE peripheral unavailable (install the MSIX build for discoverability): {e}" + ), + }); + return Err(e); + } + }; + let columba = tokio::task::spawn_blocking(move || { + build_and_start_service( + super::COLUMBA_SERVICE_UUID, + super::COLUMBA_RX_UUID, + super::COLUMBA_TX_UUID, + super::COLUMBA_ID_UUID, + &id_hash_cb, + ) + }) + .await + .map_err(|e| format!("Columba GATT spawn_blocking join: {e}"))? + .map_err(|e| format!("Columba compat service failed: {e}"))?; + + let mut tx_chars = std::collections::HashMap::new(); + tx_chars.insert(super::RATSPEAK_TX_UUID, ratspeak.1); + tx_chars.insert(super::COLUMBA_TX_UUID, columba.1); + + let inner = Inner { + provider_ratspeak: ratspeak.0, + provider_columba: columba.0, + tx_chars, + }; + if let Ok(mut slot) = inner_slot().lock() { + *slot = Some(inner); + } + tracing::info!( + target: "ble_trace", + step = "windows_peripheral.start", + "Windows BLE Peripheral: GattServiceProvider registered + advertising" + ); + Ok(()) + } + + pub async fn stop_advertising() -> Result<(), String> { + let inner = { + if let Ok(mut slot) = inner_slot().lock() { + slot.take() + } else { + None + } + }; + let Some(inner) = inner else { + tracing::debug!( + target: "ble_trace", + step = "windows_peripheral.stop.noop", + "Windows BLE Peripheral: stop_advertising with no active provider" + ); + return Ok(()); + }; + // Mirror the start path: WinRT GattServiceProvider calls block until + // the publisher state actually transitions, and on a busy radio the + // synchronous StopAdvertising() can take long enough to stall the + // Tokio executor. Drop the providers from inside spawn_blocking so the + // OS confirms the advertisement is down before this future resolves; + // otherwise a rapid disable->enable can race with the kernel still + // releasing the prior publisher. + if let Err(e) = tokio::task::spawn_blocking(move || { + if let Err(e) = inner.provider_ratspeak.StopAdvertising() { + tracing::warn!( + target: "ble_trace", + step = "windows_peripheral.stop.ratspeak_err", + err = %e, + "Windows BLE Peripheral: Ratspeak StopAdvertising failed" + ); + } + if let Err(e) = inner.provider_columba.StopAdvertising() { + tracing::warn!( + target: "ble_trace", + step = "windows_peripheral.stop.columba_err", + err = %e, + "Windows BLE Peripheral: Columba StopAdvertising failed" + ); + } + // Dropping Inner releases the providers + characteristics (their + // event handlers detach automatically via the WinRT refcount). + drop(inner); + }) + .await + { + tracing::warn!( + target: "ble_trace", + step = "windows_peripheral.stop.join_err", + err = %e, + "Windows BLE Peripheral: StopAdvertising spawn_blocking join failed" + ); + } + tracing::info!( + target: "ble_trace", + step = "windows_peripheral.stop", + "Windows BLE Peripheral: GattServiceProvider stopped + released" + ); + Ok(()) + } + + /// Outbound notify on a specific TX characteristic. Broadcasts to all + /// currently-subscribed clients (Windows doesn't address individual + /// subscribers from the provider side without per-client plumbing we + /// don't yet need). Returns true if the notify was queued. + pub fn notify_tx(char_uuid: uuid::Uuid, data: &[u8]) -> bool { + let Some(slot) = INNER.get() else { + return false; + }; + let guard = match slot.lock() { + Ok(g) => g, + Err(_) => return false, + }; + let Some(inner) = guard.as_ref() else { + return false; + }; + let Some(tx_char) = inner.tx_chars.get(&char_uuid) else { + return false; + }; + let writer = match DataWriter::new() { + Ok(w) => w, + Err(e) => { + tracing::warn!( + target: "ble_trace", + step = "windows_notify.writer_err", + %char_uuid, + err = %e, + "Windows BLE notify: DataWriter::new failed" + ); + return false; + } + }; + if let Err(e) = writer.WriteBytes(data) { + tracing::warn!( + target: "ble_trace", + step = "windows_notify.write_bytes_err", + %char_uuid, + err = %e, + "Windows BLE notify: WriteBytes failed" + ); + return false; + } + let buf = match writer.DetachBuffer() { + Ok(b) => b, + Err(e) => { + tracing::warn!( + target: "ble_trace", + step = "windows_notify.detach_err", + %char_uuid, + err = %e, + "Windows BLE notify: DetachBuffer failed" + ); + return false; + } + }; + match tx_char.NotifyValueAsync(&buf) { + Ok(_op) => true, + Err(e) => { + tracing::warn!( + target: "ble_trace", + step = "windows_notify.notify_err", + %char_uuid, + err = %e, + "Windows BLE notify: NotifyValueAsync failed" + ); + false + } + } + } + + /// Best-effort count of currently-subscribed clients across both TX + /// characteristics. Used by the fan-out to decide whether to fragment. + #[allow(dead_code)] + pub fn subscribed_client_count(char_uuid: uuid::Uuid) -> u32 { + let Some(slot) = INNER.get() else { + return 0; + }; + let guard = match slot.lock() { + Ok(g) => g, + Err(_) => return 0, + }; + let Some(inner) = guard.as_ref() else { + return 0; + }; + let Some(tx_char) = inner.tx_chars.get(&char_uuid) else { + return 0; + }; + tx_char + .SubscribedClients() + .and_then(|v| v.Size()) + .unwrap_or(0) + } + + /// Silence unused-variable warnings for types that are imported but only + /// referenced in specific event-handler paths at compile time. + #[allow(dead_code)] + fn _keep_types_alive(_: Option) {} +} + +// --------------------------------------------------------------------------- +// Spawn — dual-mode mesh interface +// --------------------------------------------------------------------------- + +// --------------------------------------------------------------------------- +// Central role — peer connection via btleplug +// --------------------------------------------------------------------------- + +/// GATT connection to a mesh peer (Central role) — btleplug-typed, used on +/// Linux + Windows. Apple platforms have a parallel native pipeline rooted +/// in [`crate::ble_central_apple_connect`] (because btleplug allocates its +/// own `CBCentralManager` and two managers in one process don't share +/// peripheral caches on macOS); Android drives the same primitives via JNI +/// in `RatspeakBlePeerClient.kt`. +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +struct MeshPeerConnection { + peripheral: btleplug::platform::Peripheral, + rx_char: btleplug::api::Characteristic, + tx_char: btleplug::api::Characteristic, + write_mtu: usize, + /// Source key used by the anti-loop map. Matches the BLE address + /// the Central sees so per-payload "do not echo back" filtering aligns + /// with what the periph_rx consumer records on inbound reassembly. + ble_address: String, +} + +/// Connect to a discovered mesh peer and subscribe to TX notifications. +/// +/// No BLE-level identity exchange. Identity is learned later from the first +/// signed Reticulum announce over the link; sending unframed identity bytes +/// here corrupts the fragment reassembler on first contact. +/// +/// Linux + Windows only — see [`MeshPeerConnection`] header for why Apple +/// uses a parallel native path. +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +async fn connect_mesh_peer( + adapter: &btleplug::platform::Adapter, + peer: &BlePeer, +) -> Result { + use btleplug::api::{Central, Peripheral as _}; + + tracing::info!( + target: "ble_trace", + step = "peer.connect_begin", + address = %peer.ble_address, + rssi = peer.rssi, + protocol = ?peer.protocol, + "BLE mesh: starting connect" + ); + + // Find peripheral by address from the adapter's cached list. + // + // Match on `p.address().to_string()` (MAC) rather than + // `p.id().to_string()` because btleplug's `id()` is platform- + // dependent — D-Bus path on Linux, MAC on Windows, CB UUID on + // Apple — while `peer.ble_address` is always populated from + // `props.address.to_string()` upstream (MAC). Matching on `id()` + // would never resolve the Linux peer and surface the misleading + // "Peer X no longer visible" error even though the peripheral was + // freshly discovered. (Apple uses a separate native central path + // — see `apple_scan_mesh_peers` — and never enters this loop.) + let peripherals = adapter + .peripherals() + .await + .map_err(|e| format!("Peripheral list: {e}"))?; + let peripheral = peripherals + .into_iter() + .find(|p| { + p.address() + .to_string() + .eq_ignore_ascii_case(&peer.ble_address) + }) + .ok_or_else(|| format!("Peer {} no longer visible", peer.ble_address))?; + + // Connect with retry (pattern from ble_rnode.rs) + let mut last_err = String::new(); + for attempt in 1..=3 { + match peripheral.connect().await { + Ok(()) => { + tracing::info!( + target: "ble_trace", + step = "peer.connect_ok", + address = %peer.ble_address, + attempt, + "BLE mesh: GATT connect succeeded" + ); + break; + } + Err(e) => { + last_err = format!("{e}"); + tracing::warn!( + target: "ble_trace", + step = "peer.connect_fail", + attempt, + address = %peer.ble_address, + error = %e, + "BLE mesh connect attempt failed" + ); + if attempt < 3 { + tokio::time::sleep(Duration::from_secs(2)).await; + } + } + } + } + if !peripheral.is_connected().await.unwrap_or(false) { + return Err(format!("Connect failed after 3 attempts: {last_err}")); + } + + // Discover services + peripheral + .discover_services() + .await + .map_err(|e| format!("Service discovery: {e}"))?; + let chars = peripheral.characteristics(); + tracing::info!( + target: "ble_trace", + step = "peer.services_discovered", + address = %peer.ble_address, + char_count = chars.len(), + char_uuids = ?chars.iter().map(|c| c.uuid.to_string()).collect::>(), + "BLE mesh: GATT services discovered" + ); + + // Find characteristics — try Ratspeak UUIDs first, fall back to Columba + let (rx_uuid, tx_uuid, protocol) = if peer.protocol == PeerProtocol::Ratspeak { + (RATSPEAK_RX_UUID, RATSPEAK_TX_UUID, PeerProtocol::Ratspeak) + } else { + (COLUMBA_RX_UUID, COLUMBA_TX_UUID, PeerProtocol::Columba) + }; + + let rx_char = chars + .iter() + .find(|c| c.uuid == rx_uuid) + .ok_or_else(|| format!("RX characteristic not found for {:?}", protocol))? + .clone(); + let tx_char = chars + .iter() + .find(|c| c.uuid == tx_uuid) + .ok_or_else(|| format!("TX characteristic not found for {:?}", protocol))? + .clone(); + + // Subscribe to TX notifications (peer → us) + peripheral + .subscribe(&tx_char) + .await + .map_err(|e| format!("Subscribe TX: {e}"))?; + tracing::info!( + target: "ble_trace", + step = "peer.subscribed", + address = %peer.ble_address, + tx_char = %tx_uuid, + "BLE mesh: subscribed to peer TX notifications" + ); + + // btleplug doesn't expose negotiated MTU on the public Peripheral trait — + // CoreBluetooth/BlueZ both auto-negotiate. 244 is the safe ATT MTU 247 + // payload (247 - 3 ATT header) that essentially every BLE 4.2+ stack + // supports out of the box. Going higher risks btleplug truncating writes + // on platforms where the negotiated MTU is below 512. + let write_mtu = 244; + + tracing::info!( + target: "ble_trace", + step = "peer.connected", + address = %peer.ble_address, + protocol = ?protocol, + "BLE mesh peer connected" + ); + + Ok(MeshPeerConnection { + peripheral, + rx_char, + tx_char, + write_mtu, + ble_address: peer.ble_address.clone(), + }) +} + +/// Per-peer read loop: receive notifications, reassemble fragments, forward +/// to transport. Linux + Windows only — Apple's notify delegate pushes +/// directly into `apple_peripheral::INBOUND_TX` so the global per-peer +/// reassembler handles inbound without a per-connection task. +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +struct PeerReadLoopCtx { + interface_id: InterfaceId, + transport_tx: mpsc::Sender, + peer_online: Arc, + rxb: Arc, + peer_writers: Arc>>>, + peer_write_tx: mpsc::Sender, + recently_disconnected: RecentlyDisconnected, + anti_loop: AntiLoopMap, +} + +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) { + let PeerReadLoopCtx { + interface_id, + transport_tx, + peer_online, + rxb, + peer_writers, + peer_write_tx, + recently_disconnected, + anti_loop, + } = ctx; + let peer_address: String = conn.ble_address.clone(); + use btleplug::api::Peripheral as _; + use futures::StreamExt; + + let mut notification_stream = match conn.peripheral.notifications().await { + Ok(s) => s, + Err(e) => { + tracing::warn!(error = %e, "BLE mesh notification stream failed"); + peer_online.store(false, Ordering::SeqCst); + return; + } + }; + + // Fragment reassembly buffer: maps (total_count) → accumulated fragments + let mut reassembly: HashMap>, Instant)> = HashMap::new(); + let mut missed_keepalives: u32 = 0; + + loop { + // Global shutdown takes precedence over + // the per-peer `peer_online` flag. Flipping `peer_online` here as well + // lets the write-side and scan-side cleanup see the peer as dead on + // their next tick, matching the keepalive-timeout cleanup path below. + if !peer_online.load(Ordering::SeqCst) || !running_flag().load(Ordering::SeqCst) { + peer_online.store(false, Ordering::SeqCst); + break; + } + + let notification = tokio::select! { + n = notification_stream.next() => n, + _ = tokio::time::sleep(KEEPALIVE_INTERVAL) => { + // Send keepalive ping (1-byte 0x00) + if let Err(e) = conn.peripheral.write( + &conn.rx_char, &[0x00], + btleplug::api::WriteType::WithoutResponse + ).await { + missed_keepalives += 1; + tracing::warn!( + target: "ble_trace", + step = "keepalive.tx_fail", + peer = %conn.ble_address, + missed = missed_keepalives, + err = %e, + "keepalive write failed" + ); + if missed_keepalives >= KEEPALIVE_MAX_MISSES { + tracing::warn!( + target: "ble_trace", + step = "keepalive.timeout", + peer = %conn.ble_address, + missed = missed_keepalives, + "BLE mesh peer keepalive timeout, disconnecting" + ); + peer_online.store(false, Ordering::SeqCst); + break; + } + } else { + if missed_keepalives > 0 { + tracing::info!( + target: "ble_trace", + step = "keepalive.recovered", + peer = %conn.ble_address, + "keepalive recovered after misses" + ); + } + missed_keepalives = 0; + } + continue; + } + }; + + match notification { + Some(n) if n.uuid == conn.tx_char.uuid => { + let data = n.value; + if data.is_empty() { + continue; + } + missed_keepalives = 0; + + // Keepalive ping (1 byte) — just acknowledge, no transport forward + if data.len() == 1 && data[0] == 0x00 { + continue; + } + + // Check if this is a fragmented packet (has 5-byte header) + let first_byte = data[0]; + let complete_packet = if first_byte == FragmentType::Lone as u8 + || (first_byte > FragmentType::End as u8) + { + // LONE or no header — complete packet + Some(data) + } else if data.len() >= 5 { + let total = u16::from_be_bytes([data[3], data[4]]); + let entry = reassembly + .entry(total) + .or_insert_with(|| (Vec::new(), Instant::now())); + entry.0.push(data); + + if first_byte == FragmentType::End as u8 { + // All fragments received — reassemble. Invariant: the + // entry was just inserted via `or_insert_with` above. + let (frags, _) = reassembly + .remove(&total) + .expect("reassembly entry must exist: inserted above"); + reassemble_fragments(&frags) + } else { + None + } + } else { + Some(data) // Short data without valid header — treat as complete + }; + + // Forward complete packet to transport + if let Some(raw) = complete_packet { + rxb.fetch_add(raw.len() as u64, Ordering::Relaxed); + // Register the source so the fan-out anti-loop filter + // doesn't echo this exact payload back to the peer it + // came from. + anti_loop_record(&anti_loop, conn.ble_address.clone(), &raw); + let msg = TransportMessage::Inbound(rns_transport::messages::InboundPacket { + raw: Bytes::from(raw), + interface_id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + peer_online.store(false, Ordering::SeqCst); + break; + } + } + + // Clean up timed-out reassembly buffers + reassembly.retain(|_, (_, started)| started.elapsed() < FRAGMENT_TIMEOUT); + } + Some(_) => {} // Notification from other characteristic — ignore + None => { + tracing::info!("BLE mesh peer notification stream ended"); + peer_online.store(false, Ordering::SeqCst); + break; + } + } + } + + // Cleanup: disconnect and remove writer + let _ = conn.peripheral.disconnect().await; + let mut writers = peer_writers.write().await; + writers.retain(|w| !w.same_channel(&peer_write_tx)); + tracing::info!(address = %peer_address, "BLE mesh peer disconnected and cleaned up"); + + // Mark this peer as a wanted-reconnect target keyed by BLE address. + // The scan loop checks this map and uses SCAN_ACTIVE_INTERVAL until + // either we reconnect or the entry expires. Identity-keyed + // tracking is gone because the BLE link no longer exchanges identity. + record_disconnect(&recently_disconnected, &peer_address); +} + +/// Per-peer write loop: fragment and write outbound data to peer's RX +/// characteristic via btleplug. Linux + Windows only — Apple's outbound +/// path lives inline in the spawn body and calls +/// `ble_central_apple_connect::write_peer` per fragment. +#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))] +async fn peer_write_loop( + peripheral: btleplug::platform::Peripheral, + rx_char: btleplug::api::Characteristic, + write_mtu: usize, + mut rx: mpsc::Receiver, + peer_online: Arc, + peer_address: String, + anti_loop: AntiLoopMap, +) { + // Coarse announce-relay counter: every 5 successful writes we log enough + // detail to diagnose drop patterns without enabling verbose logging. + let mut tx_count: u64 = 0; + // Bounded sleep inside the recv select so the loop wakes even when no + // outbound data is flowing; without it, global shutdown would leave + // this task alive until the next packet or the peer's read-loop + // dropped the write_tx sender. 1s is short enough for teardown to feel + // immediate and long enough to add no measurable battery cost. + const SHUTDOWN_POLL: Duration = Duration::from_secs(1); + loop { + let data = tokio::select! { + v = rx.recv() => match v { + Some(d) => d, + None => break, + }, + _ = tokio::time::sleep(SHUTDOWN_POLL) => { + if !peer_online.load(Ordering::SeqCst) + || !running_flag().load(Ordering::SeqCst) + { + peer_online.store(false, Ordering::SeqCst); + break; + } + continue; + } + }; + if !peer_online.load(Ordering::SeqCst) || !running_flag().load(Ordering::SeqCst) { + peer_online.store(false, Ordering::SeqCst); + break; + } + + // Don't echo a packet back to the peer it just came from. + if !anti_loop_should_send(&anti_loop, &peer_address, &data) { + continue; + } + + let fragments = fragment_packet(&data, write_mtu); + for frag in &fragments { + if let Err(e) = + crate::ble_rnode::ble_write(&peripheral, &rx_char, frag, write_mtu).await + { + tracing::warn!( + target: "ble_trace", + step = "peer.write_fail", + peer = %peer_address, + tx_count = tx_count, + frag_len = frag.len(), + err = %e, + "BLE mesh peer write failed" + ); + peer_online.store(false, Ordering::SeqCst); + return; + } + } + tx_count += 1; + if tx_count.is_multiple_of(5) { + tracing::info!( + target: "ble_trace", + step = "peer.tx_progress", + peer = %peer_address, + tx_count = tx_count, + last_len = data.len(), + "BLE mesh outbound frames (rolling count)" + ); + } + } +} + +// --------------------------------------------------------------------------- +// Spawn +// --------------------------------------------------------------------------- + +/// Spawn a BLE Peer-to-Peer mesh interface. +/// +/// Starts both Central (scanning + GATT client) and Peripheral (advertising + +/// GATT server) roles simultaneously. Discovered peers are connected, +/// identities exchanged, and raw Reticulum packets flow bidirectionally +/// through the interface — enabling announces, LXMF messages, and all +/// protocol traffic over BLE. Compatible with Columba (Torlando) BLE mesh. +pub async fn spawn_ble_peer_interface( + config: BlePeerConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, + is_foreground: Arc, + foreground_wake: Arc, + seed_identities: Vec, +) -> Result { + let name = config.name.clone(); + + // Reset the process-wide running flag so a previous teardown doesn't + // make this fresh boot exit immediately. + mark_running(); + + // Start peripheral (GATT server + advertising) + if let Err(e) = start_peripheral(&config.identity_hash).await { + tracing::warn!(name = %name, error = %e, "BLE Peripheral start failed, running Central-only"); + } + + // Anti-loop / source filter: records which peer just delivered each + // payload so the fan-out skips echoing it back. Shared across the + // peripheral inbound consumer, the Central read loops, and the fan-out + // task on every platform. + let anti_loop = new_anti_loop_map(); + + // TX/RX byte counters. Declared up here so the peripheral inbound + // reassembly task spawned next can clone shared_rxb into its closure. + let shared_txb = Arc::new(AtomicU64::new(0)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + + // Spawn peripheral inbound consumer: receives data written by peers + // connecting to our GATT server (Peripheral role), reassembles fragments, + // and forwards complete packets to the transport actor. + { + let transport_periph = transport_tx.clone(); + let anti_loop_p = anti_loop.clone(); + // Apple (iOS+macOS) and Android peripheral modules expose a per-process + // inbound channel populated by their delegate / GATT-server callback. + // All platform peripheral modules surface a `(peer_id, data)` + // receiver via `take_inbound_rx`. The per-peer reassembler below + // drains it and feeds the transport. + let periph_rx = { + #[cfg(any(target_os = "ios", target_os = "macos"))] + { + apple_peripheral::take_inbound_rx() + } + #[cfg(target_os = "android")] + { + android_peripheral::take_inbound_rx() + } + #[cfg(target_os = "linux")] + { + linux_peripheral::take_inbound_rx() + } + #[cfg(target_os = "windows")] + { + windows_peripheral::take_inbound_rx() + } + #[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "android", + target_os = "linux", + target_os = "windows" + )))] + { + // No peripheral support on this platform (e.g. BSDs). + // Central-only mode continues to work; just no inbound + // channel for peripheral writes to consume. + None::)>> + } + }; + if let Some(mut rx) = periph_rx { + let rxb = shared_rxb.clone(); + tokio::spawn(async move { + // Per-peer reassembly: outer key is the source peer identifier + // (BluetoothDevice MAC on Android; CBCentral.identifier UUID + // string on Apple). Two peers writing fragments concurrently + // can no longer corrupt each other's reassembly buffers. + type PeerReassembly = HashMap>, Instant)>; + let mut reassembly: HashMap = HashMap::new(); + // Identity is learned from the first signed Reticulum announce. + // Emit once per peer address so callers can dedupe + // central/peripheral views of the same device. + let mut identity_announced: std::collections::HashSet = + std::collections::HashSet::new(); + while let Some((peer, data)) = rx.recv().await { + if !running_flag().load(Ordering::SeqCst) { + break; + } + tracing::debug!( + target: "ble_trace", + step = "reassembly.frame", + peer = %peer, + len = data.len(), + first_byte = data.first().copied().unwrap_or(0), + "BLE Peer reassembly: frame received" + ); + if data.is_empty() || (data.len() == 1 && data[0] == 0x00) { + continue; // Empty or keepalive + } + let first = data[0]; + let per_peer = reassembly.entry(peer.clone()).or_default(); + let complete = + if first == FragmentType::Lone as u8 || first > FragmentType::End as u8 { + Some(data) + } else if data.len() >= 5 { + let total = u16::from_be_bytes([data[3], data[4]]); + let entry = per_peer + .entry(total) + .or_insert_with(|| (Vec::new(), Instant::now())); + entry.0.push(data); + if first == FragmentType::End as u8 { + // Invariant: `or_insert_with` just inserted `total`. + let (frags, _) = per_peer + .remove(&total) + .expect("per-peer reassembly entry must exist: inserted above"); + reassemble_fragments(&frags) + } else { + None + } + } else { + Some(data) + }; + + if let Some(raw) = complete { + rxb.fetch_add(raw.len() as u64, Ordering::Relaxed); + let parse_result = rns_wire::packet::Packet::from_raw(&raw); + match &parse_result { + Ok(parsed) => tracing::debug!( + target: "ble_trace", + step = "reassembly.complete", + peer = %peer, + len = raw.len(), + packet_type = ?parsed.header.flags.packet_type, + "BLE Peer reassembly: complete packet" + ), + Err(e) => tracing::debug!( + target: "ble_trace", + step = "reassembly.complete", + peer = %peer, + len = raw.len(), + parse_err = %e, + "BLE Peer reassembly: complete packet (parse failed)" + ), + } + // Identity learning: peek at the packet header + // before we hand off to transport. If this is an + // announce and we haven't yet associated this peer + // address with an identity, emit IdentityResolved for + // caller-side deduplication. Cheap: parses header only, + // doesn't validate the announce + // signature (transport will do that). + if !identity_announced.contains(&peer) + && let Ok(parsed) = &parse_result + && parsed.header.flags.packet_type + == rns_wire::flags::PacketType::Announce + { + let id_hex = hex::encode(parsed.header.destination_hash); + identity_announced.insert(peer.clone()); + dispatch_event(BlePeerEvent::IdentityResolved { + address: peer.clone(), + identity_hash: id_hex, + }); + } + // Record this packet's source so the outbound + // fan-out can skip echoing it back to the same peer. + anti_loop_record(&anti_loop_p, peer.clone(), &raw); + let msg = + TransportMessage::Inbound(rns_transport::messages::InboundPacket { + raw: Bytes::from(raw), + interface_id: id, + rssi: None, + snr: None, + q: None, + }); + if transport_periph.send(msg).await.is_err() { + break; + } + } + + // Drop expired reassembly buffers (per peer, then per fragment-set). + for buf in reassembly.values_mut() { + buf.retain(|_, (_, t)| t.elapsed() < FRAGMENT_TIMEOUT); + } + reassembly.retain(|_, m| !m.is_empty()); + } + }); + } + } + + // Outbound channel (transport → interface → BLE peers) + let (tx, mut app_rx) = mpsc::channel::(64); + + // Shared peer write channels — populated as peers connect. + // Each connected peer gets a write channel; outbound data is broadcast to all. + let peer_writers: Arc>>> = + Arc::new(tokio::sync::RwLock::new(Vec::new())); + + // Write task: forward outbound packets to (a) every peer we connected to as + // Central via the per-peer write channels, AND (b) every peer that + // connected to us as Central — i.e. a subscriber on our peripheral TX + // characteristic — via the platform notify_tx broadcast. Without (b), + // the mesh is one-way for any pair where only one side initiated as + // Central, which is exactly half of the symmetric-mesh promise. + // + // Per-peer MTU is queried before fragmenting on Android; Apple + // platforms rely on CoreBluetooth's auto-negotiated min and a safe + // 182-byte cap (iOS default ATT MTU 185 minus 3 ATT header bytes). + let txb_w = shared_txb.clone(); + let writers_w = peer_writers.clone(); + let anti_loop_fan = anti_loop.clone(); + tokio::spawn(async move { + // Apple-side fallback (no per-central API exposed up to us yet). + // Gated to Apple because the only consumer is the Apple-cfg + // fragmentation block below — on Linux/Windows the const would + // be dead. + #[cfg(any(target_os = "ios", target_os = "macos"))] + const APPLE_NOTIFY_MTU: usize = 182; + + while let Some(payload) = app_rx.recv().await { + if !running_flag().load(Ordering::SeqCst) { + break; + } + txb_w.fetch_add(payload.len() as u64, Ordering::Relaxed); + + // (a) Centrals we initiated to — peer_write_loop fragments inside + // and runs its own per-peer anti-loop check before writing. + let readers = writers_w.read().await; + for peer_tx in readers.iter() { + let _ = peer_tx.send(payload.clone()).await; + } + drop(readers); + + // (b) Subscribers on our peripheral TX. Fragment here so each + // NOTIFY frame fits the per-peer (Android) or conservative + // (Apple) ATT MTU. Enumerate subscribed centrals and skip + // any whose address is recorded as the source of this exact + // payload (anti-loop). + #[cfg(any(target_os = "ios", target_os = "macos"))] + { + let rats_subs = apple_peripheral::subscribed_centrals_for_char(RATSPEAK_TX_UUID); + let col_subs = apple_peripheral::subscribed_centrals_for_char(COLUMBA_TX_UUID); + let frags = fragment_packet(&payload, APPLE_NOTIFY_MTU); + tracing::info!( + rats_subs = rats_subs.len(), + col_subs = col_subs.len(), + payload_bytes = payload.len(), + frags = frags.len(), + "Apple BLE peripheral fan-out: writing outbound" + ); + for (char_uuid, subs, label) in [ + (RATSPEAK_TX_UUID, &rats_subs, "ratspeak"), + (COLUMBA_TX_UUID, &col_subs, "columba"), + ] { + for addr in subs { + if !anti_loop_should_send(&anti_loop_fan, addr, &payload) { + tracing::info!(peer = %addr, char = label, "Apple BLE fan-out: anti-loop skip"); + continue; + } + let mut ok_frags = 0usize; + for frag in &frags { + if apple_peripheral::notify_tx(Some(addr), char_uuid, frag) { + ok_frags += 1; + } + } + tracing::info!( + peer = %addr, + total_frags = frags.len(), + ok_frags, + char = label, + "Apple BLE fan-out: notify_tx results" + ); + } + } + } + #[cfg(target_os = "linux")] + { + // Linux bluer notifier doesn't expose per-central addresses up + // to us yet — the Notifier is keyed by char only. Apply the + // anti-loop filter against a synthetic broadcast key so a + // packet recently received from any peripheral subscriber is + // skipped on the same characteristic. This is a coarser + // filter than apple/android but still prevents the + // most-common 2-node echo loop. A linux-specific per-device + // notifier table can refine this later. + const LINUX_NOTIFY_MTU: usize = 244; + let frags = fragment_packet(&payload, LINUX_NOTIFY_MTU); + for frag in &frags { + let _ = linux_peripheral::notify_tx(RATSPEAK_TX_UUID, frag); + let _ = linux_peripheral::notify_tx(COLUMBA_TX_UUID, frag); + } + let _ = &anti_loop_fan; // silence unused-warning on linux-only path + } + #[cfg(target_os = "windows")] + { + // WinRT GattLocalCharacteristic.NotifyValueAsync broadcasts to + // every subscribed client on the characteristic — Windows + // doesn't expose a per-subscriber addressable notify. Same + // coarse anti-loop story as Linux: filter against a + // per-characteristic "broadcast" key. Per-client routing can + // be added later by keying on the GattSubscribedClient's + // device id seen during SubscribedClientsChanged. + const WINDOWS_NOTIFY_MTU: usize = 244; + let frags = fragment_packet(&payload, WINDOWS_NOTIFY_MTU); + for frag in &frags { + let _ = windows_peripheral::notify_tx(RATSPEAK_TX_UUID, frag); + let _ = windows_peripheral::notify_tx(COLUMBA_TX_UUID, frag); + } + let _ = &anti_loop_fan; + } + #[cfg(target_os = "android")] + { + // Query the min subscribed payload per characteristic so the + // chunk size adapts to the lowest-capacity central, alongside + // the per-characteristic subscriber list for anti-loop + // addressing. + let (rats_mtu, col_mtu, rats_subs, col_subs) = tokio::task::spawn_blocking(|| { + ( + android_peripheral::min_subscribed_payload(RATSPEAK_TX_UUID), + android_peripheral::min_subscribed_payload(COLUMBA_TX_UUID), + android_peripheral::subscribed_addresses_for(RATSPEAK_TX_UUID), + android_peripheral::subscribed_addresses_for(COLUMBA_TX_UUID), + ) + }) + .await + .unwrap_or((182, 182, Vec::new(), Vec::new())); + let rats_frags = fragment_packet(&payload, rats_mtu); + for addr in &rats_subs { + if !anti_loop_should_send(&anti_loop_fan, addr, &payload) { + continue; + } + let addr_owned = addr.clone(); + let frags_owned = rats_frags.clone(); + let _ = tokio::task::spawn_blocking(move || { + for frag in &frags_owned { + let _ = + android_peripheral::notify_tx(&addr_owned, RATSPEAK_TX_UUID, frag); + } + }) + .await; + } + let col_frags = fragment_packet(&payload, col_mtu); + for addr in &col_subs { + if !anti_loop_should_send(&anti_loop_fan, addr, &payload) { + continue; + } + let addr_owned = addr.clone(); + let frags_owned = col_frags.clone(); + let _ = tokio::task::spawn_blocking(move || { + for frag in &frags_owned { + let _ = + android_peripheral::notify_tx(&addr_owned, COLUMBA_TX_UUID, frag); + } + }) + .await; + } + } + } + }); + + // Shared "recently disconnected" registry. Lets the scan loop + // prioritize reconnecting to peers we know about, and applies an + // exponential-backoff window after repeated failures. + // + // Seeded from persisted recently-disconnected identities so a fresh process + // launch immediately prefers peers from the previous session, instead of + // waiting to observe a disconnect first. + let recently_disconnected = new_recently_disconnected(); + seed_recently_disconnected(&recently_disconnected, seed_identities); + + // Main mesh management task — scan, discover, connect, manage peers. + // + // Three implementations: + // * Linux + Windows: btleplug (BlueZ / WinRT) — the cross-platform + // crate works fine on those platforms. + // * Apple (iOS + macOS): bypass btleplug entirely. Scan goes through + // `ble_central_apple` (custom CBCentralManager for AllowDuplicates) + // and connect through `ble_central_apple_connect` (objc2 native + // CBPeripheral lifecycle). This mirrors Android's all-native pipeline + // and exists because btleplug allocates its own CBCentralManager — + // two managers in one process don't share peripheral caches on macOS, + // so every connect attempt resolved to "Peer X no longer visible". + // * Android: native Kotlin RatspeakBlePeerClient via JNI (btleplug's + // Android backend is broken on 14+, same issue as RNode). + #[cfg(all( + feature = "ble", + not(target_os = "android"), + not(any(target_os = "ios", target_os = "macos")) + ))] + let read_task = { + let rxb = shared_rxb.clone(); + let transport = transport_tx.clone(); + let recently_disc = recently_disconnected.clone(); + let mesh_name = name.clone(); + let writers = peer_writers.clone(); + let anti_loop = anti_loop.clone(); + let wake = foreground_wake.clone(); + + tokio::spawn(async move { + // Connected peers keyed by BLE address. Identity-keyed dedupe + // lives at the transport layer once signed announces arrive. + let mut connected_addrs: HashMap> = HashMap::new(); + let mut scan_interval = SCAN_ACTIVE_INTERVAL; + + // Get adapter once, reuse for all scans. + let adapter = match crate::ble_rnode::get_adapter().await { + Ok(a) => a, + Err(e) => { + tracing::error!(error = %e, "BLE mesh: failed to get adapter, Central role disabled"); + // Keep running (Peripheral role may still work) + loop { + tokio::time::sleep(Duration::from_secs(60)).await; + } + } + }; + + loop { + if !running_flag().load(Ordering::SeqCst) { + tracing::info!("BLE mesh Central scan loop: shutdown signal, exiting"); + break; + } + + // Clean up disconnected peers + connected_addrs.retain(|addr, online| { + let alive = online.load(Ordering::SeqCst); + if !alive { + tracing::info!( + target: "ble_trace", + step = "peer.lost", + address = %addr, + "BLE mesh peer connection ended \u{2014} dropping from connected set" + ); + } + alive + }); + + // Drop "recently disconnected" entries that have aged out. + prune_recently_disconnected(&recently_disc); + // Drop anti-loop dedupe entries past their 30s TTL. + anti_loop_prune(&anti_loop); + + // Scan for mesh peers. Pass the central loop's adapter so the + // peripheral registry stays consistent between scan and connect + // -- using a freshly-created adapter inside scan_mesh_peers + // would split caches and produce "Peer X no longer visible" on + // the connect attempt. Same root cause class as the macOS + // bypass at the central scan loop above. + match scan_mesh_peers_shared(&adapter, 3).await { + Ok(peers) => { + // Active scan if we either saw new peers OR have a + // wanted-reconnect entry that's not in backoff. + let next_interval = + if !peers.is_empty() || has_wanted_reconnects(&recently_disc) { + SCAN_ACTIVE_INTERVAL + } else { + SCAN_IDLE_INTERVAL + }; + if next_interval != scan_interval { + tracing::info!( + target: "ble_trace", + step = "scan.interval_changed", + prev_ms = scan_interval.as_millis() as u64, + next_ms = next_interval.as_millis() as u64, + scanned_peer_count = peers.len(), + wanted_reconnects = has_wanted_reconnects(&recently_disc), + connected_count = connected_addrs.len(), + "scan interval transition" + ); + } + scan_interval = next_interval; + + for peer in &peers { + // Skip if already connected + if connected_addrs.contains_key(&peer.ble_address) { + continue; + } + + // Enforce MAX_PEERS limit + if connected_addrs.len() >= MAX_PEERS { + tracing::debug!( + "BLE mesh: MAX_PEERS ({MAX_PEERS}) reached, skipping" + ); + break; + } + + // Skip peers in reconnect backoff. + if reconnect_in_backoff(&recently_disc, &peer.ble_address) { + tracing::debug!( + address = %peer.ble_address, + "BLE mesh: peer in reconnect backoff, skipping" + ); + continue; + } + + tracing::info!( + target: "ble_trace", + step = "peer.discovered", + name = %mesh_name, + address = %peer.ble_address, + rssi = peer.rssi, + protocol = ?peer.protocol, + connected_count = connected_addrs.len(), + "BLE mesh peer discovered, connecting..." + ); + + // Connect, subscribe, set up data flow. + // No BLE-level identity exchange — identity is + // learned later from the first signed Reticulum + // announce that flows over the link. + match connect_mesh_peer(&adapter, peer).await { + Ok(conn) => { + // Drop the wanted-reconnect entry now + // that we've reconnected. + record_reconnect_success(&recently_disc, &peer.ble_address); + + let peer_online = Arc::new(AtomicBool::new(true)); + + // Per-peer write channel + let (peer_write_tx, peer_write_rx) = mpsc::channel::(64); + writers.write().await.push(peer_write_tx.clone()); + + // Track this peer + connected_addrs + .insert(peer.ble_address.clone(), peer_online.clone()); + + // Spawn per-peer write loop + let p_write = conn.peripheral.clone(); + let rx_c = conn.rx_char.clone(); + let mtu = conn.write_mtu; + let online_w = peer_online.clone(); + let addr_w = peer.ble_address.clone(); + let anti_loop_w = anti_loop.clone(); + tokio::spawn(async move { + peer_write_loop( + p_write, + rx_c, + mtu, + peer_write_rx, + online_w, + addr_w, + anti_loop_w, + ) + .await; + }); + + // Spawn per-peer read loop + let transport_r = transport.clone(); + let online_r = peer_online.clone(); + let rxb_r = rxb.clone(); + let writers_r = writers.clone(); + let recently_r = recently_disc.clone(); + let anti_loop_r = anti_loop.clone(); + let proto_evt = peer.protocol; + let addr_evt = peer.ble_address.clone(); + tokio::spawn(async move { + peer_read_loop( + conn, + PeerReadLoopCtx { + interface_id: id, + transport_tx: transport_r, + peer_online: online_r, + rxb: rxb_r, + peer_writers: writers_r, + peer_write_tx, + recently_disconnected: recently_r, + anti_loop: anti_loop_r, + }, + ) + .await; + }); + dispatch_event(BlePeerEvent::Connected { + address: addr_evt.clone(), + identity_hash: String::new(), + protocol: proto_evt, + }); + // Kick-announce: now that we're subscribed + // to the peer's TX, ask the embedding UI to + // fire an immediate Reticulum announce so + // identity exchange happens on first contact. + dispatch_event(BlePeerEvent::SubscribeReady { + address: addr_evt, + }); + } + Err(e) => { + tracing::warn!( + address = %peer.ble_address, + error = %e, + "BLE mesh peer connection failed" + ); + record_reconnect_failure(&recently_disc, &peer.ble_address); + } + } + } + } + Err(e) => { + tracing::debug!(error = %e, "BLE mesh scan cycle failed"); + } + } + + // Override scan interval when backgrounded for battery savings + // (mobile only — desktop scans at the foreground interval always). + #[cfg(feature = "mobile-throttle")] + let was_foreground = is_foreground.load(Ordering::Relaxed); + #[cfg(feature = "mobile-throttle")] + let effective_interval = if was_foreground { + scan_interval + } else { + SCAN_BACKGROUND_INTERVAL + }; + #[cfg(not(feature = "mobile-throttle"))] + let was_foreground = true; + #[cfg(not(feature = "mobile-throttle"))] + let effective_interval = scan_interval; + scan_sleep(effective_interval, &is_foreground, was_foreground, &wake).await; + } + }) + }; + + // Apple (iOS + macOS) central task — objc2-native scan + connect + per-peer + // write loops. Inbound bytes flow through the existing INBOUND_TX channel + // (apple_peripheral::try_push_inbound) which the per-peer reassembly task + // above already drains; per-peer read loops are not needed because the + // ble_central_apple_connect module's notify delegate pushes directly into + // that channel. Disconnect propagation: ble_central_apple's didDisconnect + // delegate calls on_did_disconnect, which flips the per-peer online flag + // and dispatches BlePeerEvent::Disconnected. + #[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] + let read_task = { + let mesh_name = name.clone(); + let writers = peer_writers.clone(); + let recently_disc = recently_disconnected.clone(); + let anti_loop = anti_loop.clone(); + let wake = foreground_wake.clone(); + + tokio::spawn(async move { + let mut connected_addrs: HashMap> = HashMap::new(); + let mut scan_interval = SCAN_ACTIVE_INTERVAL; + + loop { + if !running_flag().load(Ordering::SeqCst) { + tracing::info!("Apple BLE mesh Central scan loop: shutdown signal, exiting"); + crate::ble_central_apple_connect::disconnect_all(); + break; + } + + // Drop peers whose disconnect delegate flipped their flag. + // Consult the disconnect reason stashed by `on_did_disconnect` + // (one-shot via `take_last_disconnect_reason`) to choose + // between rotation-aware reconnect (zero-out backoff so the + // peer comes back fast on next scan) and genuine-failure + // accumulation (existing 3-strike path). + connected_addrs.retain(|addr, online| { + let alive = online.load(Ordering::SeqCst); + if !alive { + let reason = + crate::ble_central_apple_connect::take_last_disconnect_reason(addr); + match reason { + Some(crate::ble_central_apple_connect::DisconnectReason::Rotation) => { + tracing::info!( + target: "ble_trace", + step = "apple_connect.rotation_drop", + address = %addr, + "Apple BLE mesh peer dropped via RPA rotation \u{2014} fast reconnect path" + ); + record_rotation_disconnect(&recently_disc, addr); + } + _ => { + tracing::info!( + target: "ble_trace", + step = "peer.lost", + address = %addr, + reason = ?reason, + "Apple BLE mesh peer connection ended \u{2014} dropping from connected set" + ); + record_disconnect(&recently_disc, addr); + } + } + } + alive + }); + + prune_recently_disconnected(&recently_disc); + anti_loop_prune(&anti_loop); + crate::ble_central_apple_connect::prune_discovered(); + + match scan_mesh_peers(3).await { + Ok(peers) => { + let next_interval = + if !peers.is_empty() || has_wanted_reconnects(&recently_disc) { + SCAN_ACTIVE_INTERVAL + } else { + SCAN_IDLE_INTERVAL + }; + if next_interval != scan_interval { + tracing::info!( + target: "ble_trace", + step = "scan.interval_changed", + prev_ms = scan_interval.as_millis() as u64, + next_ms = next_interval.as_millis() as u64, + scanned_peer_count = peers.len(), + wanted_reconnects = has_wanted_reconnects(&recently_disc), + connected_count = connected_addrs.len(), + "Apple scan interval transition" + ); + } + scan_interval = next_interval; + + for peer in &peers { + if connected_addrs.contains_key(&peer.ble_address) { + continue; + } + if connected_addrs.len() >= MAX_PEERS { + tracing::debug!( + "Apple BLE mesh: MAX_PEERS ({MAX_PEERS}) reached, skipping" + ); + break; + } + if reconnect_in_backoff(&recently_disc, &peer.ble_address) { + tracing::debug!( + address = %peer.ble_address, + "Apple BLE mesh: peer in reconnect backoff, skipping" + ); + continue; + } + + tracing::info!( + target: "ble_trace", + step = "peer.discovered", + name = %mesh_name, + address = %peer.ble_address, + rssi = peer.rssi, + protocol = ?peer.protocol, + connected_count = connected_addrs.len(), + "Apple BLE mesh peer discovered, connecting..." + ); + + match crate::ble_central_apple_connect::connect_peer( + peer.ble_address.clone(), + peer.protocol, + ) + .await + { + Ok(cp) => { + record_reconnect_success(&recently_disc, &peer.ble_address); + let online = cp.online.clone(); + + let (peer_write_tx, mut peer_write_rx) = + mpsc::channel::(64); + writers.write().await.push(peer_write_tx.clone()); + connected_addrs + .insert(peer.ble_address.clone(), online.clone()); + + // Per-peer write loop. Inbound is handled + // by the global INBOUND_TX reassembler; + // there's no equivalent peer_read_loop on + // Apple because the connect module's + // notify delegate already pushes there. + let online_w = online.clone(); + let addr_w = peer.ble_address.clone(); + let anti_loop_w = anti_loop.clone(); + let mtu = cp.write_mtu; + tokio::spawn(async move { + const SHUTDOWN_POLL: Duration = Duration::from_secs(1); + let mut tx_count: u64 = 0; + loop { + let data = tokio::select! { + v = peer_write_rx.recv() => match v { + Some(d) => d, + None => break, + }, + _ = tokio::time::sleep(SHUTDOWN_POLL) => { + if !online_w.load(Ordering::SeqCst) + || !running_flag().load(Ordering::SeqCst) + { + online_w.store(false, Ordering::SeqCst); + break; + } + continue; + } + }; + if !online_w.load(Ordering::SeqCst) + || !running_flag().load(Ordering::SeqCst) + { + online_w.store(false, Ordering::SeqCst); + break; + } + if !anti_loop_should_send(&anti_loop_w, &addr_w, &data) + { + continue; + } + let frags = fragment_packet(&data, mtu); + let mut all_ok = true; + for frag in &frags { + if let Err(e) = + crate::ble_central_apple_connect::write_peer( + &addr_w, frag, + ) + { + tracing::warn!( + target: "ble_trace", + step = "peer.write_fail", + peer = %addr_w, + tx_count = tx_count, + frag_len = frag.len(), + err = %e, + "Apple BLE mesh peer write failed" + ); + online_w.store(false, Ordering::SeqCst); + all_ok = false; + break; + } + } + if !all_ok { + break; + } + tx_count += 1; + if tx_count.is_multiple_of(5) { + tracing::info!( + target: "ble_trace", + step = "peer.tx_progress", + peer = %addr_w, + tx_count = tx_count, + last_len = data.len(), + "Apple BLE mesh outbound frames (rolling count)" + ); + } + } + }); + + dispatch_event(BlePeerEvent::Connected { + address: peer.ble_address.clone(), + identity_hash: String::new(), + protocol: peer.protocol, + }); + dispatch_event(BlePeerEvent::SubscribeReady { + address: peer.ble_address.clone(), + }); + } + Err(e) => { + tracing::warn!( + address = %peer.ble_address, + error = %e, + "Apple BLE mesh peer connection failed" + ); + // Distinguish ghost-identifier timeouts from + // genuine peer failures. CoreBluetooth's + // `connectPeripheral:` doesn't self-time-out + // when the underlying advertised address has + // moved (RPA rotation), so our 5s connect + // timeout is the only way to detect a ghost. + // Mark ghost identifiers with one-strike + // backoff so they don't recur in the next 5 + // minutes; everything else accumulates the + // 3-strike retry budget like before. + let err_str = e.to_string(); + if err_str.contains("connect: timed out") { + record_connect_timeout_ghost( + &recently_disc, + &peer.ble_address, + ); + tracing::info!( + target: "ble_trace", + step = "apple_connect.ghost_backoff", + address = %peer.ble_address, + "Apple BLE mesh: ghost identifier flagged for full backoff" + ); + } else { + record_reconnect_failure(&recently_disc, &peer.ble_address); + } + } + } + } + } + Err(e) => { + tracing::debug!(error = %e, "Apple BLE mesh scan cycle failed"); + } + } + + #[cfg(feature = "mobile-throttle")] + let was_foreground = is_foreground.load(Ordering::Relaxed); + #[cfg(feature = "mobile-throttle")] + let effective_interval = if was_foreground { + scan_interval + } else { + SCAN_BACKGROUND_INTERVAL + }; + #[cfg(not(feature = "mobile-throttle"))] + let was_foreground = true; + #[cfg(not(feature = "mobile-throttle"))] + let effective_interval = scan_interval; + scan_sleep(effective_interval, &is_foreground, was_foreground, &wake).await; + } + }) + }; + + // Android central task — JNI-driven scan + connect + per-peer write loops. + // Inbound bytes are wired through the same INBOUND_TX channel the GATT + // server uses (RatspeakBlePeerClient.nativePeerClientDataReceived calls + // android_peripheral::on_gatt_data_received), so the existing per-peer + // reassembly consumer above handles both Central- and Peripheral-side + // traffic without any additional plumbing. + #[cfg(target_os = "android")] + let read_task = { + let mesh_name = name.clone(); + let writers = peer_writers.clone(); + let foreground = is_foreground.clone(); + let recently_disc = recently_disconnected.clone(); + let anti_loop = anti_loop.clone(); + let wake = foreground_wake.clone(); + + tokio::spawn(async move { + // Scan timeout per cycle — short enough to feel responsive when a + // new peer powers on, long enough to catch low-duty-cycle adverts. + const SCAN_TIMEOUT_MS: i64 = 3000; + let mut connected_addrs: HashMap> = HashMap::new(); + let mut scan_interval = SCAN_ACTIVE_INTERVAL; + + loop { + if !running_flag().load(Ordering::SeqCst) { + tracing::info!( + "BLE mesh (Android) Central scan loop: shutdown signal, exiting" + ); + break; + } + + prune_recently_disconnected(&recently_disc); + // Drop anti-loop dedupe entries past their 30s TTL. + anti_loop_prune(&anti_loop); + + // Drop peers whose JNI disconnect callback flipped their flag. + // unregister cleans the static registry that backs that callback. + connected_addrs.retain(|addr, online| { + let alive = online.load(Ordering::SeqCst); + if !alive { + tracing::info!(address = %addr, "BLE mesh (Android) peer connection ended"); + // Mark this address as a wanted-reconnect target. + // Identity-keyed tracking is gone because the BLE link + // no longer exchanges identity. + record_disconnect(&recently_disc, addr); + android_peripheral::unregister_peer_online(addr); + android_peripheral::peer_client_disconnect(addr); + } + alive + }); + + // Native scan via BluetoothLeScanner with a service-UUID + // filter (battery-efficient — radio firmware filters + // adverts before waking the host). + let scan_results = tokio::task::spawn_blocking(move || { + android_peripheral::peer_scan_mesh(SCAN_TIMEOUT_MS) + }) + .await + .unwrap_or_default(); + + scan_interval = if !scan_results.is_empty() || has_wanted_reconnects(&recently_disc) + { + SCAN_ACTIVE_INTERVAL + } else { + SCAN_IDLE_INTERVAL + }; + + for (addr, rssi, protocol) in &scan_results { + if connected_addrs.contains_key(addr) { + continue; + } + if connected_addrs.len() >= MAX_PEERS { + tracing::debug!( + "BLE mesh (Android): MAX_PEERS ({MAX_PEERS}) reached, skipping" + ); + break; + } + if *rssi < MIN_RSSI { + continue; + } + if reconnect_in_backoff(&recently_disc, addr) { + tracing::debug!( + address = %addr, + "BLE mesh (Android): peer in reconnect backoff, skipping" + ); + continue; + } + + tracing::info!( + name = %mesh_name, + address = %addr, + rssi = *rssi, + protocol = ?protocol, + "BLE mesh (Android) peer discovered, connecting..." + ); + + // Blocking connect call — Kotlin uses CountDownLatches that + // would deadlock on the GATT callback thread. + let addr_clone = addr.clone(); + let connect_result = tokio::task::spawn_blocking(move || { + android_peripheral::peer_client_connect(&addr_clone) + }) + .await + .unwrap_or_else(|e| Err(format!("spawn_blocking: {e}"))); + + match connect_result { + Ok(()) => { + let peer_online = Arc::new(AtomicBool::new(true)); + android_peripheral::register_peer_online( + addr.clone(), + peer_online.clone(), + ); + + let (peer_write_tx, mut peer_write_rx) = mpsc::channel::(64); + writers.write().await.push(peer_write_tx.clone()); + connected_addrs.insert(addr.clone(), peer_online.clone()); + + // Per-peer write loop: bytes from the fan-out task + // come through `peer_write_rx`, get fragmented, + // and each fragment is pushed to Kotlin via JNI. + let online_w = peer_online.clone(); + let addr_w = addr.clone(); + let anti_loop_w = anti_loop.clone(); + tokio::spawn(async move { + // Bounded recv wake so global shutdown + // tears this task down within ~1s even when + // there's no outbound traffic. Without it the + // task would live until the scan loop's + // cleanup-on-next-tick dropped the write_tx. + const SHUTDOWN_POLL: Duration = Duration::from_secs(1); + loop { + let data = tokio::select! { + v = peer_write_rx.recv() => match v { + Some(d) => d, + None => break, + }, + _ = tokio::time::sleep(SHUTDOWN_POLL) => { + if !online_w.load(Ordering::SeqCst) + || !running_flag().load(Ordering::SeqCst) + { + online_w.store(false, Ordering::SeqCst); + break; + } + continue; + } + }; + if !online_w.load(Ordering::SeqCst) + || !running_flag().load(Ordering::SeqCst) + { + online_w.store(false, Ordering::SeqCst); + break; + } + // Don't echo a packet back to its source. + if !anti_loop_should_send(&anti_loop_w, &addr_w, &data) { + continue; + } + // Query the per-peer negotiated MTU each + // iteration so we pick up post-connect MTU + // exchange results. + let addr_mtu = addr_w.clone(); + let mtu = tokio::task::spawn_blocking(move || { + android_peripheral::peer_client_mtu(&addr_mtu) + }) + .await + .unwrap_or(244); + let frags = fragment_packet(&data, mtu); + let addr_w2 = addr_w.clone(); + let send_ok = tokio::task::spawn_blocking(move || { + for frag in &frags { + if !android_peripheral::peer_client_write( + &addr_w2, frag, + ) { + return false; + } + } + true + }) + .await + .unwrap_or(false); + if !send_ok { + tracing::warn!( + peer = %addr_w, + "Android peer client write failed, marking offline" + ); + online_w.store(false, Ordering::SeqCst); + break; + } + } + }); + + // Drop any wanted-reconnect entry for this peer. + record_reconnect_success(&recently_disc, addr); + tracing::info!( + address = %addr, + protocol = ?protocol, + "BLE mesh (Android) peer connected" + ); + dispatch_event(BlePeerEvent::Connected { + address: addr.clone(), + identity_hash: String::new(), + protocol: *protocol, + }); + // Kick-announce — see iOS Central path. + dispatch_event(BlePeerEvent::SubscribeReady { + address: addr.clone(), + }); + } + Err(e) => { + tracing::warn!( + address = %addr, + error = %e, + "BLE mesh (Android) peer connection failed" + ); + record_reconnect_failure(&recently_disc, addr); + } + } + } + + #[cfg(feature = "mobile-throttle")] + let was_foreground = foreground.load(Ordering::Relaxed); + #[cfg(feature = "mobile-throttle")] + let effective_interval = if was_foreground { + scan_interval + } else { + SCAN_BACKGROUND_INTERVAL + }; + #[cfg(not(feature = "mobile-throttle"))] + let was_foreground = true; + #[cfg(not(feature = "mobile-throttle"))] + let effective_interval = scan_interval; + scan_sleep(effective_interval, &foreground, was_foreground, &wake).await; + } + }) + }; + + #[cfg(all(not(feature = "ble"), not(target_os = "android")))] + let read_task = tokio::spawn(async move { + loop { + tokio::time::sleep(Duration::from_secs(60)).await; + } + }); + + Ok(InterfaceHandle { + id, + name, + mode: config.mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: true, + repeat: false, + }, + bitrate: 250_000, // BLE 1M PHY effective throughput + mtu: 500, + online: Arc::new(AtomicBool::new(true)), + txb: Some(shared_txb), + rxb: Some(shared_rxb), + tx, + read_task, + }) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + // ── Fragmentation ── + + #[test] + fn test_fragmentation_lone() { + let data = vec![1, 2, 3, 4, 5]; + let frags = fragment_packet(&data, 100); + assert_eq!(frags.len(), 1); + assert_eq!(frags[0], data); + } + + #[test] + fn test_fragmentation_multi() { + let data = vec![0u8; 200]; + let frags = fragment_packet(&data, 50); + assert!(frags.len() > 1); + for frag in &frags { + assert!(frag.len() <= 50); + assert!(frag.len() >= 5); + } + let reassembled = reassemble_fragments(&frags).unwrap(); + assert_eq!(reassembled, data); + } + + #[test] + fn test_fragment_types() { + let data = vec![0u8; 200]; + let frags = fragment_packet(&data, 50); + assert_eq!(frags[0][0], FragmentType::Start as u8); + for frag in &frags[1..frags.len() - 1] { + assert_eq!(frag[0], FragmentType::Continue as u8); + } + assert_eq!(frags.last().unwrap()[0], FragmentType::End as u8); + } + + #[test] + fn test_fragmentation_exact_mtu() { + // Data that exactly fills one LONE frame (no header needed) + let data = vec![0xAA; 50]; + let frags = fragment_packet(&data, 53); // 53 - 3 = 50 LONE threshold + assert_eq!(frags.len(), 1); + assert_eq!(frags[0], data); // No header prefix + } + + #[test] + fn test_fragmentation_one_byte_over() { + // Data one byte over the LONE threshold triggers multi-fragment + let mtu: usize = 50; + let lone_max = mtu.saturating_sub(3); + let data = vec![0xBB; lone_max + 1]; + let frags = fragment_packet(&data, mtu); + assert!(frags.len() > 1); + let reassembled = reassemble_fragments(&frags).unwrap(); + assert_eq!(reassembled, data); + } + + #[test] + fn test_fragmentation_large_packet() { + let data = vec![0xCC; 2048]; + let frags = fragment_packet(&data, 100); + assert!(frags.len() > 20); + let reassembled = reassemble_fragments(&frags).unwrap(); + assert_eq!(reassembled, data); + } + + #[test] + fn test_fragmentation_tiny_mtu() { + // MTU of 8: 5-byte header + 3 bytes payload per fragment + let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; + let frags = fragment_packet(&data, 8); + assert!(frags.len() >= 3); + let reassembled = reassemble_fragments(&frags).unwrap(); + assert_eq!(reassembled, data); + } + + #[test] + fn test_fragmentation_mtu_too_small() { + // MTU <= 5 means payload_mtu = 0, should produce LONE frame + let data = vec![1, 2, 3]; + let frags = fragment_packet(&data, 5); + assert_eq!(frags.len(), 1); + assert_eq!(frags[0], data); + } + + #[test] + fn test_fragmentation_empty_data() { + let frags = fragment_packet(&[], 100); + assert_eq!(frags.len(), 1); + assert!(frags[0].is_empty()); + } + + #[test] + fn test_fragmentation_single_byte() { + let frags = fragment_packet(&[0xFF], 100); + assert_eq!(frags.len(), 1); + assert_eq!(frags[0], vec![0xFF]); + } + + #[test] + fn test_fragment_header_structure() { + let data = vec![0u8; 100]; + let frags = fragment_packet(&data, 30); + // Check header: [type:1][seq:2-BE][total:2-BE] + let first = &frags[0]; + assert_eq!(first[0], FragmentType::Start as u8); + let seq = u16::from_be_bytes([first[1], first[2]]); + assert_eq!(seq, 0); + let total = u16::from_be_bytes([first[3], first[4]]); + assert_eq!(total as usize, frags.len()); + } + + #[test] + fn test_fragment_sequence_numbers() { + let data = vec![0u8; 200]; + let frags = fragment_packet(&data, 30); + for (i, frag) in frags.iter().enumerate() { + let seq = u16::from_be_bytes([frag[1], frag[2]]); + assert_eq!(seq as usize, i); + } + } + + // ── Reassembly ── + + #[test] + fn test_reassemble_empty() { + assert!(reassemble_fragments(&[]).is_none()); + } + + #[test] + fn test_reassemble_malformed_short() { + // Fragments shorter than 5 bytes should be rejected + let bad = vec![vec![0x01, 0x00]]; + assert!(reassemble_fragments(&bad).is_none()); + } + + #[test] + fn test_reassemble_header_only() { + // Fragment with only a 5-byte header (no payload) + let frag = vec![FragmentType::Start as u8, 0, 0, 0, 1]; + let result = reassemble_fragments(&[frag]); + assert_eq!(result, Some(vec![])); + } + + // ── Service UUIDs ── + + #[test] + fn test_service_uuids() { + assert_ne!(RATSPEAK_SERVICE_UUID, COLUMBA_SERVICE_UUID); + assert_ne!(RATSPEAK_RX_UUID, COLUMBA_RX_UUID); + assert_ne!(RATSPEAK_TX_UUID, COLUMBA_TX_UUID); + } + + #[test] + fn test_ratspeak_uuids_distinct_from_each_other() { + let uuids = [ + RATSPEAK_SERVICE_UUID, + RATSPEAK_RX_UUID, + RATSPEAK_TX_UUID, + RATSPEAK_ID_UUID, + ]; + for i in 0..uuids.len() { + for j in (i + 1)..uuids.len() { + assert_ne!(uuids[i], uuids[j]); + } + } + } + + #[test] + fn test_columba_uuids_distinct_from_each_other() { + let uuids = [ + COLUMBA_SERVICE_UUID, + COLUMBA_RX_UUID, + COLUMBA_TX_UUID, + COLUMBA_ID_UUID, + ]; + for i in 0..uuids.len() { + for j in (i + 1)..uuids.len() { + assert_ne!(uuids[i], uuids[j]); + } + } + } + + // ── Config ── + + #[test] + fn test_ble_peer_config_defaults() { + let cfg = BlePeerConfig::new("mesh0", vec![0u8; 16]); + assert_eq!(cfg.name, "mesh0"); + assert_eq!(cfg.identity_hash.len(), 16); + assert_eq!(cfg.mode, InterfaceMode::Full); + } + + // ── BlePeer struct serialization ── + + #[test] + fn test_ble_peer_serialization() { + let peer = BlePeer { + identity_hash: "abcdef0123456789".into(), + ble_address: "AA:BB:CC:DD:EE:FF".into(), + rssi: -65, + protocol: PeerProtocol::Ratspeak, + connected: true, + }; + let json = serde_json::to_string(&peer).unwrap(); + assert!(json.contains("\"protocol\":\"Ratspeak\"")); + assert!(json.contains("\"connected\":true")); + assert!(json.contains("\"rssi\":-65")); + } + + #[test] + fn test_ble_peer_roundtrip() { + let peer = BlePeer { + identity_hash: "0011223344556677".into(), + ble_address: "11:22:33:44:55:66".into(), + rssi: -80, + protocol: PeerProtocol::Columba, + connected: false, + }; + let json = serde_json::to_string(&peer).unwrap(); + let deserialized: BlePeer = serde_json::from_str(&json).unwrap(); + assert_eq!(deserialized.identity_hash, peer.identity_hash); + assert_eq!(deserialized.ble_address, peer.ble_address); + assert_eq!(deserialized.rssi, peer.rssi); + assert_eq!(deserialized.protocol, PeerProtocol::Columba); + assert!(!deserialized.connected); + } + + #[test] + fn test_peer_protocol_serialization() { + let r = serde_json::to_string(&PeerProtocol::Ratspeak).unwrap(); + assert_eq!(r, "\"Ratspeak\""); + let c = serde_json::to_string(&PeerProtocol::Columba).unwrap(); + assert_eq!(c, "\"Columba\""); + } + + // ── Constants ── + + #[test] + fn test_protocol_constants() { + assert_eq!(MAX_PEERS, 7); + assert_eq!(KEEPALIVE_INTERVAL.as_secs(), 15); + assert_eq!(KEEPALIVE_MAX_MISSES, 3); + assert_eq!(FRAGMENT_TIMEOUT.as_secs(), 30); + assert_eq!(MIN_RSSI, -85); + assert_eq!(SCAN_ACTIVE_INTERVAL.as_secs(), 5); + assert_eq!(SCAN_IDLE_INTERVAL.as_secs(), 30); + assert_eq!(SCAN_BACKGROUND_INTERVAL.as_secs(), 60); + assert_eq!(TARGET_MTU, 517); + } + + #[test] + fn test_fragment_type_values() { + assert_eq!(FragmentType::Lone as u8, 0x00); + assert_eq!(FragmentType::Start as u8, 0x01); + assert_eq!(FragmentType::Continue as u8, 0x02); + assert_eq!(FragmentType::End as u8, 0x03); + } +} diff --git a/crates/rns-interface/src/ble_peer_lifecycle.rs b/crates/rns-interface/src/ble_peer_lifecycle.rs new file mode 100644 index 0000000..4696041 --- /dev/null +++ b/crates/rns-interface/src/ble_peer_lifecycle.rs @@ -0,0 +1,675 @@ +//! BLE peripheral lifecycle state machine. Platform adapters (Apple +//! `CBPeripheralManager`, Linux `bluer`, Android `BluetoothGattServer`, +//! Windows `GattServiceProvider`) drive it via [`PeripheralLifecycle::apply`]. +//! +//! Two invariants this encodes that are easy to violate by hand: +//! +//! 1. **Teardown waits for platform confirmation.** iOS has no +//! `peripheralManagerDidStopAdvertising:` callback; the only reliable +//! "stopped" signal is polling `CBPeripheralManager.isAdvertising` until +//! `NO`. Calling `removeAllServices` while still advertising leaves +//! CoreBluetooth in a dirty state that breaks subsequent enables. +//! +//! 2. **Mid-session platform transitions rewind.** A `Resetting` → +//! `PoweredOff` → `PoweredOn` cycle (user toggling Bluetooth, OS stack +//! crash recovery) must drop back to `StartingWaitingPlatform` so the +//! next `PlatformReady` re-registers. +//! +//! Invalid transitions return an error; adapters log and continue rather +//! than panic — BLE backends occasionally deliver out-of-order or redundant +//! callbacks. + +use std::sync::{Mutex, MutexGuard, PoisonError}; + +/// Sub-states for `Starting` and `Stopping` are explicit so each can reject +/// events that don't belong to its phase. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PeripheralState { + Idle, + /// Awaiting `CBManagerState == PoweredOn` / `bluer` `Adapter.powered`. + StartingWaitingPlatform, + /// Registering GATT services; awaiting per-service add confirmation. + StartingRegisteringServices, + /// `startAdvertising` issued; awaiting platform confirmation. + StartingAdvertising, + Advertising, + /// `stopAdvertising` issued; awaiting confirmation. iOS lacks a delegate + /// callback for this — the adapter polls `isAdvertising`. + StoppingAdvertisement, + /// `removeAllServices` issued; awaiting confirmation. + StoppingRemovingServices, + /// Cleanly torn down. Distinct from `Idle` for telemetry. + Stopped, + /// Unrecoverable. Requires explicit [`LifecycleEvent::Reset`]. + Failed, +} + +impl PeripheralState { + /// True when the peripheral holds platform resources needing release on teardown. + pub fn is_active(self) -> bool { + !matches!(self, Self::Idle | Self::Stopped | Self::Failed) + } + + pub fn is_starting(self) -> bool { + matches!( + self, + Self::StartingWaitingPlatform + | Self::StartingRegisteringServices + | Self::StartingAdvertising + ) + } + + pub fn is_stopping(self) -> bool { + matches!( + self, + Self::StoppingAdvertisement | Self::StoppingRemovingServices + ) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LifecycleEvent { + StartRequested, + /// Platform ready for service registration + advertising. + PlatformReady, + /// Platform blocked (BT off, permission denied, adapter resetting). + /// Rewinds active states to `StartingWaitingPlatform` to preserve user + /// intent across recovery. + PlatformUnavailable { + reason: String, + }, + ServicesAdded, + AdvertiseStarted, + StopRequested, + /// `stopAdvertising` completed. On iOS this comes from polling + /// `isAdvertising` since no delegate callback exists. Skipping this and + /// going straight to `removeAllServices` was the root cause of the + /// "disable doesn't fully tear down" bug. + AdvertiseStopped, + ServicesRemoved, + FatalError { + reason: String, + }, + Reset, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TransitionError { + pub from: PeripheralState, + pub event: LifecycleEvent, +} + +impl std::fmt::Display for TransitionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "invalid BLE peripheral lifecycle transition: event {:?} is not valid from state {:?}", + self.event, self.from + ) + } +} + +impl std::error::Error for TransitionError {} + +/// Caller performs the side-effect (calling `stopAdvertising` etc.) on the +/// returned next state. Idempotent re-requests return `Ok` with state +/// unchanged; genuine violations return [`TransitionError`]. +pub fn transition( + state: PeripheralState, + event: &LifecycleEvent, +) -> Result { + use LifecycleEvent::*; + use PeripheralState::*; + + if let FatalError { .. } = event { + return Ok(Failed); + } + + let next = match (state, event) { + // ---- Start path ---- + (Idle, StartRequested) => StartingWaitingPlatform, + (Stopped, StartRequested) => StartingWaitingPlatform, + (StartingWaitingPlatform, PlatformReady) => StartingRegisteringServices, + (StartingRegisteringServices, ServicesAdded) => StartingAdvertising, + (StartingAdvertising, AdvertiseStarted) => Advertising, + + // ---- Stop path ---- + (Advertising, StopRequested) => StoppingAdvertisement, + // Stop while starting: skip ahead to the appropriate Stopping + // sub-state so the in-flight platform calls unwind cleanly. + (StartingAdvertising, StopRequested) => StoppingAdvertisement, + (StartingRegisteringServices, StopRequested) => StoppingRemovingServices, + (StartingWaitingPlatform, StopRequested) => Stopped, // nothing registered yet + + (StoppingAdvertisement, AdvertiseStopped) => StoppingRemovingServices, + (StoppingRemovingServices, ServicesRemoved) => Stopped, + (Stopped, Reset) => Idle, + + // Platform-unavailable from any active state rewinds to + // WaitingPlatform so the next PlatformReady resumes automatically. + (Advertising, PlatformUnavailable { .. }) => StartingWaitingPlatform, + (StartingAdvertising, PlatformUnavailable { .. }) => StartingWaitingPlatform, + (StartingRegisteringServices, PlatformUnavailable { .. }) => StartingWaitingPlatform, + (StartingWaitingPlatform, PlatformUnavailable { .. }) => StartingWaitingPlatform, + + (Failed, Reset) => Idle, + + // ---- Idempotent no-ops ---- + ( + StartingWaitingPlatform + | StartingRegisteringServices + | StartingAdvertising + | Advertising, + StartRequested, + ) => state, + (Idle | Stopped | StoppingAdvertisement | StoppingRemovingServices, StopRequested) => state, + (Idle, Reset) => Idle, + + _ => { + return Err(TransitionError { + from: state, + event: event.clone(), + }); + } + }; + + Ok(next) +} + +/// Mutex is held only across the transition itself; side-effects run after +/// `apply` returns. +pub struct PeripheralLifecycle { + state: Mutex, +} + +impl PeripheralLifecycle { + pub fn new() -> Self { + Self { + state: Mutex::new(PeripheralState::Idle), + } + } + + pub fn current(&self) -> PeripheralState { + *self.lock().expect("poisoned") + } + + pub fn apply(&self, event: LifecycleEvent) -> Result { + let mut guard = self.lock().expect("poisoned"); + let next = transition(*guard, &event)?; + *guard = next; + Ok(next) + } + + pub fn is_advertising(&self) -> bool { + matches!(self.current(), PeripheralState::Advertising) + } + + fn lock( + &self, + ) -> Result, PoisonError>> { + self.state.lock() + } +} + +impl Default for PeripheralLifecycle { + fn default() -> Self { + Self::new() + } +} + +impl std::fmt::Debug for PeripheralLifecycle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PeripheralLifecycle") + .field("state", &self.current()) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn err(reason: &str) -> LifecycleEvent { + LifecycleEvent::PlatformUnavailable { + reason: reason.into(), + } + } + + fn fatal(reason: &str) -> LifecycleEvent { + LifecycleEvent::FatalError { + reason: reason.into(), + } + } + + fn drive(start: PeripheralState, events: &[LifecycleEvent]) -> PeripheralState { + let lc = PeripheralLifecycle { + state: Mutex::new(start), + }; + for e in events { + lc.apply(e.clone()) + .unwrap_or_else(|err| panic!("transition failed: {err}")); + } + lc.current() + } + + // ---- Happy-path transitions ---- + + #[test] + fn full_start_cycle_reaches_advertising() { + let final_state = drive( + PeripheralState::Idle, + &[ + LifecycleEvent::StartRequested, + LifecycleEvent::PlatformReady, + LifecycleEvent::ServicesAdded, + LifecycleEvent::AdvertiseStarted, + ], + ); + assert_eq!(final_state, PeripheralState::Advertising); + } + + #[test] + fn full_stop_cycle_reaches_stopped() { + let final_state = drive( + PeripheralState::Advertising, + &[ + LifecycleEvent::StopRequested, + LifecycleEvent::AdvertiseStopped, + LifecycleEvent::ServicesRemoved, + ], + ); + assert_eq!(final_state, PeripheralState::Stopped); + } + + #[test] + fn stopped_can_start_again() { + let final_state = drive( + PeripheralState::Stopped, + &[ + LifecycleEvent::Reset, + LifecycleEvent::StartRequested, + LifecycleEvent::PlatformReady, + LifecycleEvent::ServicesAdded, + LifecycleEvent::AdvertiseStarted, + ], + ); + assert_eq!(final_state, PeripheralState::Advertising); + } + + // ---- Teardown requires confirmation (the bug we are fixing) ---- + + #[test] + fn stop_request_alone_does_not_reach_stopped() { + // Calling `stopAdvertising` without waiting for confirmation left + // CoreBluetooth dirty in the previous implementation. The machine + // must NOT allow StoppingAdvertisement → Stopped without + // AdvertiseStopped first. + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement); + + // Jumping straight to ServicesRemoved is invalid — we have not yet + // seen AdvertiseStopped. + let err = lc + .apply(LifecycleEvent::ServicesRemoved) + .expect_err("ServicesRemoved should be rejected in StoppingAdvertisement"); + assert_eq!(err.from, PeripheralState::StoppingAdvertisement); + assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement); + } + + #[test] + fn advertise_stopped_then_services_removed_reaches_stopped() { + let final_state = drive( + PeripheralState::StoppingAdvertisement, + &[ + LifecycleEvent::AdvertiseStopped, + LifecycleEvent::ServicesRemoved, + ], + ); + assert_eq!(final_state, PeripheralState::Stopped); + } + + // ---- Platform availability transitions ---- + + #[test] + fn bluetooth_off_mid_advertising_rewinds_to_waiting_platform() { + let final_state = drive(PeripheralState::Advertising, &[err("bluetooth off")]); + assert_eq!(final_state, PeripheralState::StartingWaitingPlatform); + } + + #[test] + fn bluetooth_recovery_cycle_returns_to_advertising() { + let final_state = drive( + PeripheralState::Advertising, + &[ + err("bluetooth off"), + LifecycleEvent::PlatformReady, + LifecycleEvent::ServicesAdded, + LifecycleEvent::AdvertiseStarted, + ], + ); + assert_eq!(final_state, PeripheralState::Advertising); + } + + #[test] + fn platform_unavailable_while_waiting_platform_is_idempotent() { + // iOS sometimes emits Resetting twice before PoweredOn. + let final_state = drive( + PeripheralState::StartingWaitingPlatform, + &[err("resetting"), err("resetting")], + ); + assert_eq!(final_state, PeripheralState::StartingWaitingPlatform); + } + + // ---- Stop while starting ---- + + #[test] + fn stop_before_platform_ready_reaches_stopped_immediately() { + // Nothing registered yet, nothing to tear down. + let final_state = drive( + PeripheralState::StartingWaitingPlatform, + &[LifecycleEvent::StopRequested], + ); + assert_eq!(final_state, PeripheralState::Stopped); + } + + #[test] + fn stop_mid_service_registration_skips_to_removing_services() { + // Services need removing but there's no advertising to stop yet. + let final_state = drive( + PeripheralState::StartingRegisteringServices, + &[LifecycleEvent::StopRequested], + ); + assert_eq!(final_state, PeripheralState::StoppingRemovingServices); + } + + #[test] + fn stop_mid_advertise_enters_stopping_advertisement() { + let final_state = drive( + PeripheralState::StartingAdvertising, + &[LifecycleEvent::StopRequested], + ); + assert_eq!(final_state, PeripheralState::StoppingAdvertisement); + } + + // ---- Idempotent events ---- + + #[test] + fn double_start_is_noop() { + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + assert_eq!(lc.current(), PeripheralState::Advertising); + + lc.apply(LifecycleEvent::StartRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::Advertising); + } + + #[test] + fn double_stop_is_noop() { + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::Idle); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::Idle); + } + + #[test] + fn reset_from_idle_is_noop() { + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::Reset).unwrap(); + assert_eq!(lc.current(), PeripheralState::Idle); + } + + // ---- Fatal and recovery ---- + + #[test] + fn fatal_error_from_any_state_reaches_failed() { + for from in [ + PeripheralState::Idle, + PeripheralState::StartingWaitingPlatform, + PeripheralState::StartingRegisteringServices, + PeripheralState::StartingAdvertising, + PeripheralState::Advertising, + PeripheralState::StoppingAdvertisement, + PeripheralState::StoppingRemovingServices, + PeripheralState::Stopped, + ] { + let final_state = drive(from, &[fatal("oom")]); + assert_eq!(final_state, PeripheralState::Failed, "from {from:?}"); + } + } + + #[test] + fn reset_from_failed_returns_to_idle() { + let final_state = drive(PeripheralState::Failed, &[LifecycleEvent::Reset]); + assert_eq!(final_state, PeripheralState::Idle); + } + + #[test] + fn failed_requires_reset_to_restart() { + let lc = PeripheralLifecycle { + state: Mutex::new(PeripheralState::Failed), + }; + let err = lc + .apply(LifecycleEvent::StartRequested) + .expect_err("StartRequested from Failed should be rejected"); + assert_eq!(err.from, PeripheralState::Failed); + } + + // ---- Invalid transitions ---- + + #[test] + fn advertise_started_from_idle_is_rejected() { + let lc = PeripheralLifecycle::new(); + let err = lc + .apply(LifecycleEvent::AdvertiseStarted) + .expect_err("AdvertiseStarted from Idle should be rejected"); + assert_eq!(err.from, PeripheralState::Idle); + assert_eq!(lc.current(), PeripheralState::Idle); + } + + #[test] + fn services_added_from_advertising_is_rejected() { + let lc = PeripheralLifecycle { + state: Mutex::new(PeripheralState::Advertising), + }; + let err = lc + .apply(LifecycleEvent::ServicesAdded) + .expect_err("ServicesAdded from Advertising should be rejected"); + assert_eq!(err.from, PeripheralState::Advertising); + assert_eq!(lc.current(), PeripheralState::Advertising); + } + + #[test] + fn advertise_stopped_from_idle_is_rejected() { + let lc = PeripheralLifecycle::new(); + assert!(lc.apply(LifecycleEvent::AdvertiseStopped).is_err()); + } + + #[test] + fn is_active_matches_intuition() { + assert!(!PeripheralState::Idle.is_active()); + assert!(!PeripheralState::Stopped.is_active()); + assert!(!PeripheralState::Failed.is_active()); + assert!(PeripheralState::StartingWaitingPlatform.is_active()); + assert!(PeripheralState::StartingRegisteringServices.is_active()); + assert!(PeripheralState::StartingAdvertising.is_active()); + assert!(PeripheralState::Advertising.is_active()); + assert!(PeripheralState::StoppingAdvertisement.is_active()); + assert!(PeripheralState::StoppingRemovingServices.is_active()); + } + + #[test] + fn is_starting_covers_all_starting_substates() { + assert!(PeripheralState::StartingWaitingPlatform.is_starting()); + assert!(PeripheralState::StartingRegisteringServices.is_starting()); + assert!(PeripheralState::StartingAdvertising.is_starting()); + assert!(!PeripheralState::Advertising.is_starting()); + assert!(!PeripheralState::StoppingAdvertisement.is_starting()); + } + + #[test] + fn is_stopping_covers_all_stopping_substates() { + assert!(PeripheralState::StoppingAdvertisement.is_stopping()); + assert!(PeripheralState::StoppingRemovingServices.is_stopping()); + assert!(!PeripheralState::Advertising.is_stopping()); + assert!(!PeripheralState::StartingAdvertising.is_stopping()); + } + + #[test] + fn is_advertising_helper_matches_current() { + let lc = PeripheralLifecycle::new(); + assert!(!lc.is_advertising()); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + assert!(!lc.is_advertising()); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + assert!(lc.is_advertising()); + } + + // ---- End-to-end scenarios exercised by the iOS / macOS adapter ---- + // + // Locks in the toggle paths that are hard to hit reliably on a dev + // machine (e.g. "disable fires before PoweredOn lands" races). + + #[test] + fn full_enable_disable_enable_cycle_ends_idle_ready_to_advertise() { + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + assert_eq!(lc.current(), PeripheralState::Advertising); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStopped).unwrap(); + lc.apply(LifecycleEvent::ServicesRemoved).unwrap(); + lc.apply(LifecycleEvent::Reset).unwrap(); + assert_eq!(lc.current(), PeripheralState::Idle); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + assert_eq!(lc.current(), PeripheralState::Advertising); + } + + #[test] + fn quick_toggle_disable_before_platform_ready_ends_idle() { + // User mashed Enable/Disable while CBManagerState was still Unknown. + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::Stopped); + lc.apply(LifecycleEvent::Reset).unwrap(); + assert_eq!(lc.current(), PeripheralState::Idle); + } + + #[test] + fn stop_mid_service_registration_requires_services_removed_not_advertise_stopped() { + // No advertising has started yet — the adapter must skip + // `stopAdvertising` and go straight to `removeAllServices`. + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + // Stop in the middle of registering, before either + // `peripheralManagerDidAddService:error:` callback lands. + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::StoppingRemovingServices); + // `AdvertiseStopped` is nonsense here — reject it. + let err = lc + .apply(LifecycleEvent::AdvertiseStopped) + .expect_err("AdvertiseStopped from StoppingRemovingServices should be rejected"); + assert_eq!(err.from, PeripheralState::StoppingRemovingServices); + // `ServicesRemoved` is the correct continuation. + lc.apply(LifecycleEvent::ServicesRemoved).unwrap(); + lc.apply(LifecycleEvent::Reset).unwrap(); + assert_eq!(lc.current(), PeripheralState::Idle); + } + + #[test] + fn redundant_services_added_after_advertise_start_is_ignored_not_fatal() { + // Late `ServicesAdded` after AdvertiseStarted (radio bounce) must + // be rejected without poisoning the machine — state unchanged. + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + let err = lc.apply(LifecycleEvent::ServicesAdded); + assert!(err.is_err()); + assert_eq!(lc.current(), PeripheralState::Advertising); + } + + #[test] + fn platform_unavailable_during_advertising_rewinds_and_recovers_automatically() { + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + assert_eq!(lc.current(), PeripheralState::Advertising); + + lc.apply(LifecycleEvent::PlatformUnavailable { + reason: "bluetooth off".into(), + }) + .unwrap(); + assert_eq!(lc.current(), PeripheralState::StartingWaitingPlatform); + + // iOS sometimes emits Resetting twice — idempotent. + lc.apply(LifecycleEvent::PlatformUnavailable { + reason: "resetting".into(), + }) + .unwrap(); + assert_eq!(lc.current(), PeripheralState::StartingWaitingPlatform); + + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + assert_eq!(lc.current(), PeripheralState::Advertising); + } + + #[test] + fn stop_after_advertise_error_starts_from_waiting_platform_returns_to_idle() { + // `peripheralManagerDidStartAdvertising:error:` with a non-nil error + // surfaces as `PlatformUnavailable`; a stop from that rewound state + // must still tear down cleanly. + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::PlatformUnavailable { + reason: "advertising failed".into(), + }) + .unwrap(); + assert_eq!(lc.current(), PeripheralState::StartingWaitingPlatform); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::Stopped); + lc.apply(LifecycleEvent::Reset).unwrap(); + assert_eq!(lc.current(), PeripheralState::Idle); + } + + #[test] + fn concurrent_stop_requests_are_idempotent() { + // BLE Mesh disable and app shutdown can race; a second + // StopRequested from any Stopping* state must be a no-op. + let lc = PeripheralLifecycle::new(); + lc.apply(LifecycleEvent::StartRequested).unwrap(); + lc.apply(LifecycleEvent::PlatformReady).unwrap(); + lc.apply(LifecycleEvent::ServicesAdded).unwrap(); + lc.apply(LifecycleEvent::AdvertiseStarted).unwrap(); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement); + lc.apply(LifecycleEvent::StopRequested).unwrap(); + assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement); + lc.apply(LifecycleEvent::AdvertiseStopped).unwrap(); + lc.apply(LifecycleEvent::ServicesRemoved).unwrap(); + assert_eq!(lc.current(), PeripheralState::Stopped); + } +} diff --git a/crates/rns-interface/src/ble_rnode.rs b/crates/rns-interface/src/ble_rnode.rs new file mode 100644 index 0000000..dae5603 --- /dev/null +++ b/crates/rns-interface/src/ble_rnode.rs @@ -0,0 +1,2259 @@ +//! RNode over BLE via the Nordic UART Service. Same KISS command set as +//! serial RNode, tunnelled through GATT notify/write. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use btleplug::api::{Central, Manager as _, Peripheral as _, ScanFilter, WriteType}; +use btleplug::platform::{Adapter, Manager, Peripheral}; +use bytes::Bytes; +use futures::StreamExt; +use tokio::sync::mpsc; +use uuid::Uuid; + +#[cfg(target_os = "android")] +static BTLEPLUG_INITIALIZED: AtomicBool = AtomicBool::new(false); + +/// Set from `JNI_OnLoad` after `btleplug::platform::init()` succeeds. +/// Without it, btleplug has no JVM reference and every call panics. +#[cfg(target_os = "android")] +pub fn mark_btleplug_initialized() { + BTLEPLUG_INITIALIZED.store(true, Ordering::SeqCst); +} + +#[cfg(target_os = "android")] +pub fn is_btleplug_initialized() -> bool { + BTLEPLUG_INITIALIZED.load(Ordering::SeqCst) +} + +use crate::kiss; +use crate::rnode::{self, RNodeResponse}; +use crate::traits::{ + InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode, +}; +use rns_transport::messages::TransportMessage; + +pub const NUS_SERVICE_UUID: Uuid = Uuid::from_u128(0x6E400001_B5A3_F393_E0A9_E50E24DCCA9E); +/// Host writes RNode commands here. +pub const NUS_RX_CHAR_UUID: Uuid = Uuid::from_u128(0x6E400002_B5A3_F393_E0A9_E50E24DCCA9E); +/// Device notifies the host here. +pub const NUS_TX_CHAR_UUID: Uuid = Uuid::from_u128(0x6E400003_B5A3_F393_E0A9_E50E24DCCA9E); + +const RECONNECT_WAIT: u64 = 5; +/// Capped below TCP's 300s — a BLE radio is either in range or not. +const RECONNECT_WAIT_MAX: u64 = 120; +/// `None` retries forever; teardown goes via `stop_ble_rnode_interface`. +const MAX_RECONNECT_TRIES: Option = None; +const SCAN_TIMEOUT: u64 = 3; +const CONNECT_TIMEOUT: u64 = 5; +/// Bounds disable-while-offline teardown latency to ~1s. +const RUNNING_POLL: Duration = Duration::from_secs(1); + +/// `stop_ble_rnode_interface` flips false; the read_task removes the entry +/// on its way out. +static RNODE_RUNNING: std::sync::OnceLock< + std::sync::Mutex>>, +> = std::sync::OnceLock::new(); + +fn running_map() +-> &'static std::sync::Mutex>> { + RNODE_RUNNING.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new())) +} + +fn register_running(id: InterfaceId) -> Arc { + let flag = Arc::new(AtomicBool::new(true)); + if let Ok(mut map) = running_map().lock() { + map.insert(id, flag.clone()); + } + flag +} + +fn unregister_running(id: InterfaceId) { + if let Ok(mut map) = running_map().lock() { + map.remove(&id); + } +} + +/// Idempotent. Safe to call before or after deregistering from the +/// transport actor. +pub fn stop_ble_rnode_interface(id: InterfaceId) { + if let Ok(map) = running_map().lock() + && let Some(flag) = map.get(&id) + { + flag.store(false, Ordering::SeqCst); + tracing::info!(id, "BLE RNode: stop signal sent"); + ble_diag(format!("[ble] stop_ble_rnode_interface({id})")); + } +} + +fn reconnect_try_exhausted(tries: &mut usize) -> bool { + if let Some(max_tries) = MAX_RECONNECT_TRIES { + *tries += 1; + *tries >= max_tries + } else { + false + } +} + +#[cfg(test)] +pub(crate) fn is_registered(id: InterfaceId) -> bool { + running_map() + .lock() + .map(|m| m.contains_key(&id)) + .unwrap_or(false) +} + +/// Returns `true` if shutdown was signalled during the wait. +async fn wait_or_shutdown(total: Duration, flag: &AtomicBool) -> bool { + let deadline = std::time::Instant::now() + total; + while std::time::Instant::now() < deadline { + if !flag.load(Ordering::SeqCst) { + return true; + } + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + tokio::time::sleep(remaining.min(RUNNING_POLL)).await; + } + !flag.load(Ordering::SeqCst) +} + +/// RNode can pack multiple frames in one read, so use the raw deframer for +/// full-command extended KISS framing. +async fn wait_for_rnode_handshake( + tcp_read: &mut tokio::net::tcp::OwnedReadHalf, + timeout: Duration, + running_task: &AtomicBool, +) -> bool { + use tokio::io::AsyncReadExt; + let mut deframer = kiss::RawKissDeframer::new(); + let mut buf = [0u8; 1024]; + let deadline = std::time::Instant::now() + timeout; + while std::time::Instant::now() < deadline { + if !running_task.load(Ordering::SeqCst) { + return false; + } + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + let read = tokio::time::timeout(remaining.min(RUNNING_POLL), tcp_read.read(&mut buf)).await; + let n = match read { + Ok(Ok(0)) => return false, + Ok(Ok(n)) => n, + Ok(Err(_)) => return false, + Err(_) => continue, + }; + for (cmd, frame) in deframer.feed(&buf[..n]) { + if cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP) { + return true; + } + if cmd == rnode::CMD_FW_VERSION && !frame.is_empty() { + return true; + } + } + } + false +} + +// iOS drops sandboxed-app stdout/stderr; embedding UIs can surface this +// broadcast in their diagnostics view. +static BLE_DIAG_TX: std::sync::OnceLock> = + std::sync::OnceLock::new(); + +fn ble_diag_sender() -> &'static tokio::sync::broadcast::Sender { + BLE_DIAG_TX.get_or_init(|| tokio::sync::broadcast::channel::(256).0) +} + +pub fn subscribe_ble_diag() -> tokio::sync::broadcast::Receiver { + ble_diag_sender().subscribe() +} + +pub(crate) fn ble_diag(msg: impl Into) { + let msg = msg.into(); + tracing::info!(target: "ble_diag", "{msg}"); + let _ = ble_diag_sender().send(msg); +} + +// Linux SMP pairing prompt plumbing. BlueZ does not auto-prompt from an +// encrypted-characteristic read, so we initiate `Device::pair()` explicitly +// and register one process-lifetime Agent to proxy the passkey prompt. +// +// The typed state is intentional: BlueZ may retry `request_passkey` after a +// cancel or timeout, and a bare dropped oneshot lets stale prompts leak back +// to subscribers. `aborted` short-circuits the agent before it broadcasts. + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct LinuxPairingPrompt { + pub device: String, + /// Pair attempt id used to dedupe and dismiss stale prompts. + #[serde(default)] + pub attempt_id: u64, +} + +/// Emitted when a pairing attempt ends so the UI can clear its modal. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct LinuxPairingFinished { + pub attempt_id: u64, + /// "ok", "cancelled", "timed_out", or a short BlueZ error string. + pub status: String, +} + +#[cfg(target_os = "linux")] +static LINUX_PAIRING_PROMPT_TX: std::sync::OnceLock< + tokio::sync::broadcast::Sender, +> = std::sync::OnceLock::new(); + +#[cfg(target_os = "linux")] +fn linux_pairing_prompt_sender() -> &'static tokio::sync::broadcast::Sender { + LINUX_PAIRING_PROMPT_TX.get_or_init(|| tokio::sync::broadcast::channel(8).0) +} + +#[cfg(target_os = "linux")] +static LINUX_PAIRING_FINISHED_TX: std::sync::OnceLock< + tokio::sync::broadcast::Sender, +> = std::sync::OnceLock::new(); + +#[cfg(target_os = "linux")] +fn linux_pairing_finished_sender() -> &'static tokio::sync::broadcast::Sender +{ + LINUX_PAIRING_FINISHED_TX.get_or_init(|| tokio::sync::broadcast::channel(8).0) +} + +/// Subscribe to passkey prompts so the UI can render the user-facing modal. +/// Linux only; on Apple/Windows the OS owns the dialog. +#[cfg(target_os = "linux")] +pub fn subscribe_linux_pairing_prompts() -> tokio::sync::broadcast::Receiver { + linux_pairing_prompt_sender().subscribe() +} + +/// Subscribe to `linux_trigger_pairing` completion events so the UI can clear +/// any modal still associated with the just-finished attempt. +#[cfg(target_os = "linux")] +pub fn subscribe_linux_pairing_finished() -> tokio::sync::broadcast::Receiver +{ + linux_pairing_finished_sender().subscribe() +} + +#[cfg(target_os = "linux")] +struct LinuxPairingState { + attempt_id: u64, + aborted: bool, + passkey_tx: Option>, + /// Notify the in-flight `linux_trigger_pairing` task to drop its + /// `device.pair()` future, which bluer turns into a BlueZ + /// `CancelPairing` call. + cancel_notify: std::sync::Arc, +} + +#[cfg(target_os = "linux")] +static LINUX_PAIRING_STATE: std::sync::Mutex> = + std::sync::Mutex::new(None); + +#[cfg(target_os = "linux")] +static LINUX_PAIRING_ATTEMPT_COUNTER: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + +/// Hand a user-entered passkey back to a waiting agent callback. Returns +/// `false` if no pairing is in flight or the attempt was aborted. +#[cfg(target_os = "linux")] +pub fn linux_submit_passkey(passkey: u32) -> bool { + if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() + && let Some(state) = guard.as_mut() + { + if state.aborted { + return false; + } + if let Some(tx) = state.passkey_tx.take() { + return tx.send(passkey).is_ok(); + } + } + false +} + +/// Tear down the in-flight pair attempt: +/// 1. Flip `aborted` so any subsequent `request_passkey` rejects without +/// broadcasting a fresh prompt. +/// 2. Drop the oneshot so the current `request_passkey` (if any) resolves +/// with `Canceled`. +/// 3. Notify the task running `linux_trigger_pairing` to drop its +/// `device.pair()` future — bluer translates that drop into a BlueZ +/// `CancelPairing` D-Bus call so the daemon stops retrying SMP. +/// 4. Drain any prompts queued in the broadcast channel so a relay that +/// hasn't run since cancel can't surface a stale prompt. +#[cfg(target_os = "linux")] +pub fn linux_cancel_pairing() { + let cancel_notify = if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() { + match guard.as_mut() { + Some(state) => { + state.aborted = true; + let _ = state.passkey_tx.take(); + Some(state.cancel_notify.clone()) + } + None => None, + } + } else { + None + }; + if let Some(notify) = cancel_notify { + notify.notify_waiters(); + } + ble_diag("[pair][linux] cancel requested"); +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum BleDeviceType { + /// Advertises the Nordic UART Service. + RNode, + Unknown, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct BleDevice { + pub name: String, + pub address: String, + pub rssi: Option, + pub device_type: BleDeviceType, + /// True if the OS already has a bond with this device. + /// + /// Reliability by platform: + /// - Android: ground truth (Kotlin reads `BluetoothDevice.bondState`). + /// - Linux: ground truth (bluer's `device.is_paired()` queried in + /// `scan_ble_devices`). + /// - Apple (iOS / macOS) and Windows: always `false` — neither + /// CoreBluetooth nor btleplug's WinRT backend exposes bond state. + /// Embedding UIs should hide bonded-state badges on these platforms. + pub bonded: bool, +} + +#[derive(Debug, Clone)] +pub struct BleRNodeConfig { + pub name: String, + /// The `ble://` URI: address, name, or empty for any RNode. + pub ble_uri: String, + pub frequency: u32, + pub bandwidth: u32, + pub spreading_factor: u8, + pub coding_rate: u8, + pub tx_power: u8, + pub mode: InterfaceMode, + pub flow_control: bool, + pub st_alock: Option, + pub lt_alock: Option, +} + +impl BleRNodeConfig { + pub fn new(name: &str, ble_uri: &str) -> Self { + Self { + name: name.to_string(), + ble_uri: ble_uri.to_string(), + frequency: 868_000_000, + bandwidth: 125_000, + spreading_factor: 7, + coding_rate: 5, + tx_power: 14, + mode: InterfaceMode::Full, + flow_control: true, + st_alock: None, + lt_alock: None, + } + } +} + +pub(crate) async fn get_adapter() -> Result { + // btleplug's Android global_adapter() panics without init; under + // panic=abort that kills the app. Fail loudly so the UI can prompt. + #[cfg(target_os = "android")] + if !BTLEPLUG_INITIALIZED.load(Ordering::SeqCst) { + return Err(InterfaceError::SendFailed( + "BLE not initialized on Android — grant Bluetooth permissions and restart".into(), + )); + } + + let manager = Manager::new() + .await + .map_err(|e| InterfaceError::SendFailed(format!("BLE manager init: {e}")))?; + let adapters = manager + .adapters() + .await + .map_err(|e| InterfaceError::SendFailed(format!("No BLE adapters: {e}")))?; + adapters + .into_iter() + .next() + .ok_or_else(|| InterfaceError::SendFailed("No BLE adapter found".into())) +} + +/// Cheap "is there a BLE adapter?" probe with no `start_scan` side effect. +/// Use this for startup-time availability checks instead of `scan_ble_devices(0)`, +/// which actually starts (and immediately stops) a scan and noisily logs an +/// `[BLE scan] adapter acquired` line per call. +pub async fn ble_adapter_present() -> Result { + match get_adapter().await { + Ok(_) => Ok(true), + Err(e) => Err(format!("{e}")), + } +} + +/// Tags anything advertising the Nordic UART Service as `RNode`, the rest +/// as `Unknown`. +/// +/// `bonded` semantics by platform: +/// - **Linux**: queried directly from BlueZ via bluer's `device.is_paired()`. +/// Ground truth. +/// - **Android**: not used here — the Android frontend bypasses this +/// function entirely and reads `BluetoothDevice.bondState` natively in +/// Kotlin. +/// - **Apple (iOS / macOS) and Windows**: always `false`. CoreBluetooth +/// (by design, for privacy) and btleplug's WinRT backend don't expose +/// bond state to apps. Embedding UIs should hide bonded-state badges on +/// these platforms. +/// +/// Apple bonded-state detection would require an objc2 bridge to +/// `CBCentralManager.retrievePeripheralsWithIdentifiers(_:)` or a local cache. +/// +/// Windows bonded-state detection would require a WinRT +/// `BluetoothLEDevice.DeviceInformation.Pairing.IsPaired` binding. +pub async fn scan_ble_devices(timeout_secs: u64) -> Result, String> { + let adapter = get_adapter().await.map_err(|e| format!("{e}"))?; + + tracing::info!("[BLE scan] adapter acquired, starting scan (timeout={timeout_secs}s)"); + if let Err(e) = adapter.start_scan(ScanFilter::default()).await { + tracing::error!("[BLE scan] start_scan failed: {e:?}"); + return Err(format!("Scan start failed: {e}")); + } + + tokio::time::sleep(Duration::from_secs(timeout_secs)).await; + + let peripherals = adapter + .peripherals() + .await + .map_err(|e| format!("Peripheral list failed: {e}"))?; + + // On Linux, get a bluer adapter handle once so we can query bond state + // per peripheral without paying the D-Bus session setup repeatedly. + #[cfg(target_os = "linux")] + let bluer_adapter = match linux_bluer_session().await { + Ok(session) => match session.default_adapter().await { + Ok(a) => Some(a), + Err(e) => { + tracing::warn!( + "[BLE scan] bluer adapter unavailable, bonded flags will read false: {e}" + ); + None + } + }, + Err(e) => { + tracing::warn!( + "[BLE scan] bluer session unavailable, bonded flags will read false: {e}" + ); + None + } + }; + + let mut devices = Vec::new(); + for p in peripherals { + if let Ok(Some(props)) = p.properties().await { + let name = props.local_name.clone().unwrap_or_default(); + if name.is_empty() { + continue; + } + + let service_uuids = &props.services; + // NUS UUID + "RNode" name prefix keeps generic Nordic-UART + // devices (Bangle.js, Adafruit demos) out of the picker. The + // name-only fallback covers iOS scan-response quirks where + // service UUIDs are missing from the initial advert. + let has_nus = service_uuids.contains(&NUS_SERVICE_UUID); + let name_match = name.starts_with("RNode"); + let is_rnode = name_match && (has_nus || service_uuids.is_empty()); + if !is_rnode { + continue; + } + + let address = p.id().to_string(); + + #[cfg(target_os = "linux")] + let bonded = match (&bluer_adapter, parse_linux_ble_address(&address).ok()) { + (Some(adapter), Some(addr)) => match adapter.device(addr) { + Ok(device) => device.is_paired().await.unwrap_or(false), + Err(_) => false, + }, + _ => false, + }; + #[cfg(not(target_os = "linux"))] + let bonded = false; + + devices.push(BleDevice { + name, + address, + rssi: props.rssi, + device_type: BleDeviceType::RNode, + bonded, + }); + } + } + + adapter.stop_scan().await.ok(); + Ok(devices) +} + +/// Accepts: +/// `ble://`, `ble://`, or bare `ble://` (first RNode found). +async fn resolve_ble_target( + adapter: &Adapter, + ble_uri: &str, +) -> Result { + let target = ble_uri.strip_prefix("ble://").unwrap_or(ble_uri); + ble_diag(format!("[ble] resolve_ble_target target='{target}'")); + + adapter + .start_scan(ScanFilter::default()) + .await + .map_err(|e| { + ble_diag(format!("[ble] start_scan err: {e}")); + InterfaceError::SendFailed(format!("BLE scan: {e}")) + })?; + tokio::time::sleep(Duration::from_secs(SCAN_TIMEOUT)).await; + adapter.stop_scan().await.ok(); + + let peripherals = adapter + .peripherals() + .await + .map_err(|e| InterfaceError::SendFailed(format!("Peripheral list: {e}")))?; + ble_diag(format!( + "[ble] scan found {} peripherals", + peripherals.len() + )); + + if target.is_empty() { + for p in &peripherals { + if let Ok(Some(props)) = p.properties().await { + if props.services.contains(&NUS_SERVICE_UUID) { + return Ok(p.clone()); + } + // A populated list without NUS means a different device; + // only fall back to the name on empty service lists. + if props.services.is_empty() + && let Some(ref name) = props.local_name + && name.starts_with("RNode ") + { + return Ok(p.clone()); + } + } + } + return Err(InterfaceError::SendFailed( + "No RNode BLE device found".into(), + )); + } + + // `peripheral.id().to_string()` is MAC on Linux/Android, CB UUID on + // iOS/macOS — same string the scanner exposes. + for p in &peripherals { + let addr = p.id().to_string(); + if addr.eq_ignore_ascii_case(target) { + ble_diag(format!("[ble] resolve matched by address: {addr}")); + return Ok(p.clone()); + } + } + + // Fallback for UIs that pass a friendly name instead of platform id. + for p in &peripherals { + if let Ok(Some(props)) = p.properties().await + && let Some(ref name) = props.local_name + && name == target + { + ble_diag(format!("[ble] resolve matched by name: {name}")); + return Ok(p.clone()); + } + } + + ble_diag(format!( + "[ble] resolve failed: no peripheral matches '{target}'" + )); + Err(InterfaceError::SendFailed(format!( + "BLE device not found: {target}. Ensure it is powered on and paired." + ))) +} + +struct BleRNodeConnection { + peripheral: Peripheral, + rx_char: btleplug::api::Characteristic, + // Retained so the resolved write characteristic remains part of the + // connection state even though writes currently go through `peripheral`. + #[allow(dead_code)] + tx_char: btleplug::api::Characteristic, + write_mtu: usize, +} + +async fn connect_rnode( + adapter: &Adapter, + ble_uri: &str, +) -> Result { + ble_diag(format!("[ble] connect_rnode start uri={ble_uri}")); + let peripheral = resolve_ble_target(adapter, ble_uri).await?; + ble_diag(format!("[ble] resolved peripheral id={}", peripheral.id())); + + let mut last_err = String::new(); + for attempt in 1..=3 { + match peripheral.connect().await { + Ok(()) => { + tracing::info!(address = %peripheral.id(), attempt, "BLE RNode connected"); + ble_diag(format!( + "[ble] peripheral.connect() ok on attempt {attempt}" + )); + break; + } + Err(e) => { + last_err = format!("{e}"); + tracing::warn!(attempt, error = %e, "BLE RNode connect attempt failed"); + ble_diag(format!( + "[ble] peripheral.connect() err on attempt {attempt}: {e}" + )); + if attempt < 3 { + tokio::time::sleep(Duration::from_secs(2)).await; + } + } + } + } + + if !peripheral.is_connected().await.unwrap_or(false) { + ble_diag(format!( + "[ble] is_connected=false after retries: {last_err}" + )); + return Err(InterfaceError::SendFailed(format!( + "BLE connect failed after 3 attempts: {last_err}" + ))); + } + + ble_diag("[ble] discover_services start"); + peripheral.discover_services().await.map_err(|e| { + ble_diag(format!("[ble] discover_services err: {e}")); + InterfaceError::SendFailed(format!("Service discovery: {e}")) + })?; + ble_diag("[ble] discover_services ok"); + + let chars = peripheral.characteristics(); + ble_diag(format!("[ble] characteristics count={}", chars.len())); + let rx_char = chars + .iter() + .find(|c| c.uuid == NUS_RX_CHAR_UUID) + .ok_or_else(|| { + ble_diag("[ble] NUS RX char not found"); + InterfaceError::SendFailed("NUS RX characteristic not found. Is this an RNode?".into()) + })? + .clone(); + let tx_char = chars + .iter() + .find(|c| c.uuid == NUS_TX_CHAR_UUID) + .ok_or_else(|| { + ble_diag("[ble] NUS TX char not found"); + InterfaceError::SendFailed("NUS TX characteristic not found. Is this an RNode?".into()) + })? + .clone(); + ble_diag(format!( + "[ble] RX/TX chars found; RX props={:?} TX props={:?}", + rx_char.properties, tx_char.properties + )); + + // SMP must run BEFORE subscribe on desktop / Apple platforms — reading + // the encrypted TX char kicks off SMP and drops L2CAP, which kills any + // pending subscribe. iOS/macOS share CoreBluetooth; Windows uses WinRT + // GATT (auto-prompt on encrypted-char reads). Same trigger shape works + // for all three. Linux uses bluer's explicit `Device::pair()` instead — + // BlueZ does not auto-prompt SMP from an encrypted-char read. + #[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))] + desktop_trigger_pairing(&peripheral, &tx_char).await?; + #[cfg(target_os = "linux")] + { + // peripheral.address() returns a BDAddr → MAC string; the helper + // also accepts BlueZ D-Bus paths for callers that pass `id()`. + let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?; + linux_trigger_pairing(bluer_addr).await?; + } + + ble_diag("[ble] subscribe TX start"); + peripheral.subscribe(&tx_char).await.map_err(|e| { + ble_diag(format!("[ble] subscribe TX err: {e}")); + InterfaceError::SendFailed(format!("BLE subscribe TX: {e}")) + })?; + ble_diag("[ble] subscribe TX ok"); + + // 244 = ATT MTU 247 - 3-byte header. Larger writes silently drop on + // peripherals with smaller negotiated MTU; 512 (GATT ceiling) isn't + // usable OTA on most stacks. + // btleplug does not currently expose the negotiated MTU; use the largest + // payload that is broadly safe for ATT MTU 247. + let write_mtu: usize = 244; + tracing::info!(write_mtu, "BLE RNode write chunk size"); + + Ok(BleRNodeConnection { + peripheral, + rx_char, + tx_char, + write_mtu, + }) +} + +/// Desktop / Apple quirk: `WithoutResponse` writes never surface ATT auth +/// errors, so the OS won't prompt for pairing on its own. Reading the +/// encrypted TX char forces SMP; the system shows its passkey dialog +/// (code on the RNode OLED) and briefly drops L2CAP. Caller MUST NOT +/// recover in-place — on Apple the post-SMP CBPeripheral enters a zombie +/// state where `connect()` / `is_connected()` hang; on Windows btleplug +/// returns the read error and we bubble it so the reconnect loop +/// re-resolves with a fresh handle. +/// +/// Works on iOS + macOS (CoreBluetooth) and Windows 10/11 (WinRT GATT — +/// `GattCharacteristic::ReadValueAsync` triggers Windows' built-in +/// pairing flow when the characteristic requires authentication). Linux +/// uses `linux_trigger_pairing` instead — BlueZ requires an explicit +/// `Device::pair()` plus a registered Agent for the passkey callback. +#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))] +async fn desktop_trigger_pairing( + peripheral: &Peripheral, + tx_char: &btleplug::api::Characteristic, +) -> Result<(), InterfaceError> { + ble_diag(format!( + "[pair] reading TX char — triggers SMP if unbonded: props={:?}", + tx_char.properties + )); + + // 60s budget for the user to read the OLED passkey and type it. + match tokio::time::timeout(Duration::from_secs(60), peripheral.read(tx_char)).await { + Ok(Ok(bytes)) => { + ble_diag(format!( + "[pair] TX read ok ({} bytes) — bonded", + bytes.len() + )); + Ok(()) + } + Ok(Err(e)) => { + // SMP just ran or is in progress — outer loop must retry with + // a fresh peripheral. + ble_diag(format!( + "[pair] TX read err ({e}) — surfacing to reconnect loop" + )); + Err(InterfaceError::SendFailed(format!( + "BLE pairing in progress: {e}" + ))) + } + Err(_) => { + ble_diag("[pair] TX read timed out after 60s — passkey not entered?"); + Err(InterfaceError::SendFailed( + "BLE pairing timed out. Did you enter the 6-digit passkey shown on the RNode when the system prompted?".into(), + )) + } + } +} + +/// One-time global handle for the bluer Agent. BlueZ keeps the agent alive +/// only as long as this `AgentHandle` exists, so we park it in a OnceCell +/// for the lifetime of the process. +#[cfg(target_os = "linux")] +static LINUX_PAIRING_AGENT: tokio::sync::OnceCell = + tokio::sync::OnceCell::const_new(); + +/// Reuse the same bluer D-Bus session + adapter across pair attempts. Each +/// `Session::new()` is a fresh D-Bus connection (~1s to set up) so we cache +/// it for the process lifetime, mirroring how `LINUX_PAIRING_AGENT` is +/// kept alive. The bluer Session itself is `Clone` (Arc-backed) so we hand +/// out cheap copies. +#[cfg(target_os = "linux")] +static LINUX_BLUER_SESSION: tokio::sync::OnceCell = + tokio::sync::OnceCell::const_new(); + +#[cfg(target_os = "linux")] +async fn linux_bluer_session() -> Result<&'static bluer::Session, InterfaceError> { + LINUX_BLUER_SESSION + .get_or_try_init(|| async { + bluer::Session::new() + .await + .map_err(|e| InterfaceError::SendFailed(format!("bluer session: {e}"))) + }) + .await +} + +#[cfg(target_os = "linux")] +async fn ensure_linux_pairing_agent(session: &bluer::Session) -> Result<(), InterfaceError> { + LINUX_PAIRING_AGENT + .get_or_try_init(|| async { + let agent = bluer::agent::Agent { + request_default: false, + request_passkey: Some(Box::new(|req| { + Box::pin(async move { + let device = req.device.to_string(); + // Snapshot the current attempt and install a fresh + // oneshot under the same lock so we can't race a + // concurrent `linux_cancel_pairing`. + let (rx, attempt_id) = { + let mut guard = match LINUX_PAIRING_STATE.lock() { + Ok(g) => g, + Err(_) => return Err(bluer::agent::ReqError::Rejected), + }; + let state = match guard.as_mut() { + Some(s) if !s.aborted => s, + _ => { + ble_diag(format!( + "[pair][linux] request_passkey rejected (no active attempt) device={device}" + )); + return Err(bluer::agent::ReqError::Canceled); + } + }; + let (tx, rx) = tokio::sync::oneshot::channel::(); + state.passkey_tx = Some(tx); + (rx, state.attempt_id) + }; + ble_diag(format!( + "[pair][linux] request_passkey attempt={attempt_id} device={device}" + )); + let _ = linux_pairing_prompt_sender().send(LinuxPairingPrompt { + device, + attempt_id, + }); + match tokio::time::timeout(Duration::from_secs(60), rx).await { + Ok(Ok(passkey)) => { + // Verify the attempt is still current and + // not aborted before handing the passkey + // to BlueZ — guards against the user + // submitting and immediately cancelling. + let still_active = LINUX_PAIRING_STATE + .lock() + .ok() + .and_then(|g| { + g.as_ref().map(|s| { + !s.aborted && s.attempt_id == attempt_id + }) + }) + .unwrap_or(false); + if !still_active { + ble_diag("[pair][linux] passkey arrived after abort"); + return Err(bluer::agent::ReqError::Canceled); + } + ble_diag("[pair][linux] passkey received from user"); + Ok(passkey) + } + Ok(Err(_)) => { + ble_diag("[pair][linux] passkey channel cancelled"); + Err(bluer::agent::ReqError::Canceled) + } + Err(_) => { + ble_diag("[pair][linux] passkey timeout after 60s"); + Err(bluer::agent::ReqError::Canceled) + } + } + }) + })), + ..Default::default() + }; + session.register_agent(agent).await.map_err(|e| { + InterfaceError::SendFailed(format!("bluer register_agent: {e}")) + }) + }) + .await?; + Ok(()) +} + +/// Parse a BLE address string into a `bluer::Address`, accepting either +/// a plain MAC (`AA:BB:CC:DD:EE:FF`) or a btleplug-Linux peripheral id +/// (BlueZ D-Bus path like `hci0/dev_AA_BB_CC_DD_EE_FF`). +/// +/// btleplug's `Peripheral::id().to_string()` returns the D-Bus path on +/// Linux, and that's what `scan_ble_devices` ships to the frontend in the +/// `BleDevice.address` field. The wizard echoes it back via +/// `add_lora_interface` → `spawn_ble_rnode_interface` → `connect_rnode` +/// → `linux_trigger_pairing`, so this helper has to accept both forms. +#[cfg(target_os = "linux")] +fn parse_linux_ble_address(addr: &str) -> Result { + if let Ok(parsed) = addr.parse::() { + return Ok(parsed); + } + if let Some(tail) = addr.rsplit('/').next() + && let Some(mac_part) = tail.strip_prefix("dev_") + { + let mac = mac_part.replace('_', ":"); + return mac.parse::().map_err(|e| { + InterfaceError::SendFailed(format!( + "invalid BLE address (BlueZ path '{addr}' → '{mac}'): {e}" + )) + }); + } + Err(InterfaceError::SendFailed(format!( + "invalid BLE address {addr}: not a MAC nor a BlueZ D-Bus path" + ))) +} + +/// Linux SMP trigger via bluer. BlueZ does not auto-prompt SMP from an +/// encrypted-char read (unlike CoreBluetooth/WinRT) — pairing must be +/// initiated explicitly. Skips if already bonded; otherwise registers the +/// process-wide passkey Agent (idempotent) and drives `Device::pair()` +/// under a 60s budget. The agent's `request_passkey` proxies the prompt +/// to subscribers via the broadcast + oneshot pair declared above. +/// +/// Single-flight: any prior attempt's state is aborted before installing +/// the new one. The pair() future is selected against a cancel `Notify` +/// so a user-driven cancel actually drops the future — bluer's +/// `Device::pair()` translates "future dropped" into a BlueZ +/// `CancelPairing` D-Bus call (see bluer 0.17 device.rs:256), so the +/// daemon stops retrying SMP instead of re-invoking `request_passkey` +/// every ~60s. +#[cfg(target_os = "linux")] +async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), InterfaceError> { + let overall_start = std::time::Instant::now(); + + // Reuse the cached session so the second-and-subsequent attempts skip + // the ~1s D-Bus setup. Build the agent and adapter once; reuse them. + let t_session = std::time::Instant::now(); + let session = linux_bluer_session().await?; + ble_diag(format!( + "[pair][linux] session ready in {:.2}s", + t_session.elapsed().as_secs_f32() + )); + + let t_adapter = std::time::Instant::now(); + let adapter = session + .default_adapter() + .await + .map_err(|e| InterfaceError::SendFailed(format!("bluer default adapter: {e}")))?; + let device = adapter + .device(bluer_addr) + .map_err(|e| InterfaceError::SendFailed(format!("bluer device({bluer_addr}): {e}")))?; + ble_diag(format!( + "[pair][linux] adapter+device handles in {:.2}s", + t_adapter.elapsed().as_secs_f32() + )); + + let t_paired = std::time::Instant::now(); + if device.is_paired().await.unwrap_or(false) { + ble_diag(format!( + "[pair][linux] already bonded with {bluer_addr} (is_paired check {:.2}s)", + t_paired.elapsed().as_secs_f32() + )); + return Ok(()); + } + ble_diag(format!( + "[pair][linux] is_paired=false in {:.2}s", + t_paired.elapsed().as_secs_f32() + )); + + let t_agent = std::time::Instant::now(); + ensure_linux_pairing_agent(session).await?; + ble_diag(format!( + "[pair][linux] agent ready in {:.2}s", + t_agent.elapsed().as_secs_f32() + )); + + // We deliberately do NOT call `device.connect()` here. bluer's + // `device.pair()` (issued below) translates to a `Pair Device` MGMT + // command that BlueZ runs as: `Set Bondable / Set IO Capability / + // Pair Device` BEFORE any L2CAP traffic, then opens the LL connection + // and runs SMP atomically. Pre-connecting opens an unencrypted link + // first; the RNode firmware then sends an `SMP: Security Request` + // (auth_req=0x0d, Bonding+MITM+SC) before BlueZ has Bondable enabled, + // and BlueZ replies `Pairing not supported (0x05)`. RNode marks the + // pair attempt failed and ignores the subsequent retry, leaving + // `device.pair()` to time out 30s later with `Authentication Canceled`. + // For the connect_rnode call site (post-btleplug-connect path), the + // device is expected to be already bonded and the early-return above + // short-circuits. + + let attempt_id = + LINUX_PAIRING_ATTEMPT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + let cancel_notify = std::sync::Arc::new(tokio::sync::Notify::new()); + ble_diag(format!( + "[pair][linux] preflight total {:.2}s before device.pair()", + overall_start.elapsed().as_secs_f32() + )); + + // Tear down any prior attempt's state and install a fresh one. The + // previous attempt's task (if any) is signalled via the captured + // notify before we replace it; its select! arm wakes and drops its + // pair() future, which propagates to BlueZ as CancelPairing. + { + let prior_notify = if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() { + let prior = guard.take().map(|mut prior| { + prior.aborted = true; + let _ = prior.passkey_tx.take(); + prior.cancel_notify.clone() + }); + *guard = Some(LinuxPairingState { + attempt_id, + aborted: false, + passkey_tx: None, + cancel_notify: cancel_notify.clone(), + }); + prior + } else { + None + }; + if let Some(notify) = prior_notify { + notify.notify_waiters(); + } + } + + let t_pair = std::time::Instant::now(); + ble_diag(format!( + "[pair][linux] device.pair() start attempt={attempt_id} addr={bluer_addr}" + )); + // tokio::select drops the losing arm's future. When cancel_notify wins, + // the timeout(...) future drops, which drops the inner device.pair() + // future, which fires bluer's CancelPairing on BlueZ (per + // bluer-0.17/src/device.rs:256). + let outcome: Result<(), InterfaceError> = tokio::select! { + biased; + _ = cancel_notify.notified() => { + ble_diag(format!( + "[pair][linux] pair cancelled by user attempt={attempt_id} after {:.2}s", + t_pair.elapsed().as_secs_f32() + )); + Err(InterfaceError::SendFailed("BLE pairing cancelled".into())) + } + res = tokio::time::timeout(Duration::from_secs(60), device.pair()) => match res { + Ok(Ok(())) => { + ble_diag(format!( + "[pair][linux] paired ok attempt={attempt_id} with {bluer_addr} in {:.2}s", + t_pair.elapsed().as_secs_f32() + )); + Ok(()) + } + Ok(Err(e)) => { + ble_diag(format!( + "[pair][linux] pair err attempt={attempt_id} after {:.2}s: {e}", + t_pair.elapsed().as_secs_f32() + )); + Err(InterfaceError::SendFailed(format!( + "BLE pairing failed: {e}" + ))) + } + Err(_) => { + ble_diag(format!( + "[pair][linux] pair timed out after 60s attempt={attempt_id}" + )); + Err(InterfaceError::SendFailed( + "BLE pairing timed out. Did you enter the 6-digit passkey shown on the RNode when the system prompted?".into(), + )) + } + } + }; + + // Clear our state slot if it still owns this attempt (a concurrent + // newer attempt would have already overwritten it; respect that). + let status = match &outcome { + Ok(()) => "ok".to_string(), + Err(e) => format!("{e}"), + }; + if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() + && let Some(state) = guard.as_ref() + && state.attempt_id == attempt_id + { + *guard = None; + } + let _ = linux_pairing_finished_sender().send(LinuxPairingFinished { attempt_id, status }); + outcome +} + +/// WithoutResponse is fire-and-forget at the ATT layer; the radio still +/// flow-controls underneath. +pub(crate) async fn ble_write( + peripheral: &Peripheral, + rx_char: &btleplug::api::Characteristic, + data: &[u8], + mtu: usize, +) -> Result<(), InterfaceError> { + for chunk in data.chunks(mtu) { + peripheral + .write(rx_char, chunk, WriteType::WithoutResponse) + .await + .map_err(|e| InterfaceError::SendFailed(format!("BLE write: {e}")))?; + } + Ok(()) +} + +/// Auto-reconnect across drops; resolve_ble_target re-runs every retry so +/// iOS RPA rotation heals automatically. +pub async fn spawn_ble_rnode_interface( + config: BleRNodeConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let online = Arc::new(AtomicBool::new(false)); + let online_handle = online.clone(); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let task_rxb = shared_rxb.clone(); + let task_txb = shared_txb.clone(); + let (tx, rx) = mpsc::channel::(256); + let rx = Arc::new(tokio::sync::Mutex::new(rx)); + let running = register_running(id); + + let bitrate = rnode::calculate_bitrate( + config.spreading_factor, + config.coding_rate, + config.bandwidth, + ); + + let rnode_cfg = rnode::RNodeConfig { + name: config.name.clone(), + port: config.ble_uri.clone(), + baud_rate: 0, + frequency: config.frequency, + bandwidth: config.bandwidth, + spreading_factor: config.spreading_factor, + coding_rate: config.coding_rate, + tx_power: config.tx_power, + mode: config.mode, + flow_control: config.flow_control, + st_alock: config.st_alock, + lt_alock: config.lt_alock, + }; + + let name = config.name.clone(); + let mode = config.mode; + let flow_control = config.flow_control; + let ble_uri = config.ble_uri.clone(); + let log_name = name.clone(); + let running_task = running.clone(); + + let read_task = tokio::spawn(async move { + let mut tries: usize = 0; + let mut backoff = RECONNECT_WAIT; + + // Drop guard: every early return must clear the running-flag map + // entry, or stale entries confuse later spawns reusing the id. + struct Cleanup(InterfaceId); + impl Drop for Cleanup { + fn drop(&mut self) { + unregister_running(self.0); + } + } + let _cleanup = Cleanup(id); + + loop { + if !running_task.load(Ordering::SeqCst) { + ble_diag("[ble] read_task exiting — running flag cleared"); + return; + } + // Re-acquire each iteration so mid-session permission grants or + // adapter toggles heal automatically. + let adapter = match get_adapter().await { + Ok(a) => a, + Err(e) => { + tracing::warn!(name = %log_name, error = %e, "BLE adapter acquisition failed"); + if reconnect_try_exhausted(&mut tries) { + tracing::warn!(name = %log_name, "BLE RNode: max reconnect tries reached"); + return; + } + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + let conn = match connect_rnode(&adapter, &ble_uri).await { + Ok(c) => c, + Err(e) => { + tracing::warn!(name = %log_name, error = %e, "BLE RNode connect failed"); + ble_diag(format!( + "[ble] connect_rnode err: {e} — retrying in {backoff}s (attempt {})", + tries + 1 + )); + if reconnect_try_exhausted(&mut tries) { + tracing::warn!(name = %log_name, "BLE RNode: max reconnect tries reached"); + ble_diag("[ble] max reconnect tries reached — giving up"); + return; + } + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + ble_diag("[ble] sending detect sequence"); + let detect_seq = rnode::build_detect_sequence(); + if let Err(e) = + ble_write(&conn.peripheral, &conn.rx_char, &detect_seq, conn.write_mtu).await + { + tracing::warn!(error = %e, "BLE RNode detect write failed"); + ble_diag(format!("[ble] detect write failed: {e}")); + let _ = tokio::time::timeout(Duration::from_secs(3), conn.peripheral.disconnect()) + .await; + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + ble_diag("[ble] detect sent ok"); + + ble_diag("[ble] sending init + airtime sequence"); + let mut init_seq = rnode::build_init_sequence(&rnode_cfg); + init_seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg)); + if let Err(e) = + ble_write(&conn.peripheral, &conn.rx_char, &init_seq, conn.write_mtu).await + { + tracing::warn!(error = %e, "BLE RNode init write failed"); + ble_diag(format!("[ble] init write failed: {e}")); + let _ = tokio::time::timeout(Duration::from_secs(3), conn.peripheral.disconnect()) + .await; + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + ble_diag("[ble] init sent ok — marking online"); + + tracing::info!( + name = %log_name, + ble_uri = %ble_uri, + bitrate_bps = bitrate, + "BLE RNode connection established" + ); + + online_handle.store(true, Ordering::SeqCst); + tries = 0; + backoff = RECONNECT_WAIT; + + let ready = Arc::new(AtomicBool::new(true)); + + let peripheral_write = conn.peripheral.clone(); + let rx_char_write = conn.rx_char.clone(); + let write_mtu = conn.write_mtu; + let (conn_tx, mut conn_rx) = mpsc::channel::(256); + + let online_w = online_handle.clone(); + let ready_w = ready.clone(); + let txb_w = task_txb.clone(); + let write_handle = tokio::spawn(async move { + while let Some(data) = conn_rx.recv().await { + txb_w.fetch_add(data.len() as u64, Ordering::Relaxed); + if flow_control { + while !ready_w.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + if !online_w.load(Ordering::SeqCst) { + return; + } + } + } + let framed = kiss::frame(&data); + if let Err(e) = + ble_write(&peripheral_write, &rx_char_write, &framed, write_mtu).await + { + tracing::warn!(error = %e, "BLE RNode write error"); + online_w.store(false, Ordering::SeqCst); + return; + } + } + }); + + let rx_ref = rx.clone(); + let fwd_handle = tokio::spawn(async move { + let mut guard = rx_ref.lock().await; + while let Some(data) = guard.recv().await { + if conn_tx.send(data).await.is_err() { + break; + } + } + }); + + let mut notification_stream = match conn.peripheral.notifications().await { + Ok(s) => s, + Err(e) => { + tracing::warn!(error = %e, "BLE RNode notification stream failed"); + online_handle.store(false, Ordering::SeqCst); + fwd_handle.abort(); + let _ = fwd_handle.await; + write_handle.abort(); + let _ = write_handle.await; + let _ = + tokio::time::timeout(Duration::from_secs(3), conn.peripheral.disconnect()) + .await; + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + let mut deframer = kiss::RawKissDeframer::new(); + let mut last_rssi: Option = None; + let mut last_snr: Option = None; + let mut transport_closed = false; + + 'read: loop { + if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) { + break 'read; + } + + let notification = tokio::select! { + n = notification_stream.next() => n, + _ = tokio::time::sleep(Duration::from_secs(CONNECT_TIMEOUT)) => { + // Polling slice — bounds disable-while-connected + // teardown latency. + if !running_task.load(Ordering::SeqCst) { + break 'read; + } + if conn.peripheral.is_connected().await.unwrap_or(false) { + continue; + } + tracing::warn!("BLE RNode connection lost (notification timeout)"); + break 'read; + } + }; + + match notification { + Some(n) if n.uuid == NUS_TX_CHAR_UUID => { + for (cmd, frame) in deframer.feed(&n.value) { + match rnode::process_rnode_response( + cmd, + &frame, + id, + &mut last_rssi, + &mut last_snr, + ) { + RNodeResponse::Packet(msg) => { + task_rxb.fetch_add(frame.len() as u64, Ordering::Relaxed); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + transport_closed = true; + break 'read; + } + } + RNodeResponse::Ready(is_ready) => { + ready.store(is_ready, Ordering::SeqCst); + } + RNodeResponse::None => {} + } + } + } + Some(_) => {} + None => { + tracing::warn!("BLE RNode notification stream ended"); + break 'read; + } + } + } + + online_handle.store(false, Ordering::SeqCst); + fwd_handle.abort(); + let _ = fwd_handle.await; + write_handle.abort(); + let _ = write_handle.await; + let _ = + tokio::time::timeout(Duration::from_secs(3), conn.peripheral.disconnect()).await; + + if transport_closed { + return; + } + if !running_task.load(Ordering::SeqCst) { + return; + } + + if reconnect_try_exhausted(&mut tries) { + tracing::warn!(name = %log_name, "BLE RNode: max reconnect tries reached"); + return; + } + tracing::info!(name = %log_name, seconds = backoff, "BLE RNode reconnecting"); + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate, + mtu: 508, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +/// Android-only TCP-bridge variant. btleplug's deprecated JNI breaks on +/// Android 14+, so Kotlin (`RatspeakBleGatt.kt`) owns the GATT lifecycle +/// and forwards NUS bytes over `tcp_port`. +pub async fn spawn_ble_rnode_interface_native( + config: BleRNodeConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, + tcp_port: u16, +) -> Result { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let online = Arc::new(AtomicBool::new(false)); + let online_handle = online.clone(); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let task_rxb = shared_rxb.clone(); + let task_txb = shared_txb.clone(); + let (tx, rx) = mpsc::channel::(256); + let rx = Arc::new(tokio::sync::Mutex::new(rx)); + + let bitrate = rnode::calculate_bitrate( + config.spreading_factor, + config.coding_rate, + config.bandwidth, + ); + + let rnode_cfg = rnode::RNodeConfig { + name: config.name.clone(), + port: config.ble_uri.clone(), + baud_rate: 0, + frequency: config.frequency, + bandwidth: config.bandwidth, + spreading_factor: config.spreading_factor, + coding_rate: config.coding_rate, + tx_power: config.tx_power, + mode: config.mode, + flow_control: config.flow_control, + st_alock: config.st_alock, + lt_alock: config.lt_alock, + }; + + let name = config.name.clone(); + let mode = config.mode; + let flow_control = config.flow_control; + let ble_uri = config.ble_uri.clone(); + let log_name = name.clone(); + let running = register_running(id); + let running_task = running.clone(); + + let read_task = tokio::spawn(async move { + let mut tries: usize = 0; + let mut backoff = RECONNECT_WAIT; + + struct Cleanup(InterfaceId); + impl Drop for Cleanup { + fn drop(&mut self) { + unregister_running(self.0); + } + } + let _cleanup = Cleanup(id); + + loop { + if !running_task.load(Ordering::SeqCst) { + ble_diag("[ble-native] read_task exiting — running flag cleared"); + return; + } + let stream = match tokio::net::TcpStream::connect(format!("127.0.0.1:{tcp_port}")).await + { + Ok(s) => s, + Err(e) => { + tracing::warn!(name = %log_name, tcp_port, error = %e, "TCP bridge connect failed"); + if reconnect_try_exhausted(&mut tries) { + tracing::warn!(name = %log_name, "BLE RNode native: max reconnect tries reached"); + return; + } + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + let (mut tcp_read, mut tcp_write) = stream.into_split(); + + let detect_seq = rnode::build_detect_sequence(); + if let Err(e) = tcp_write.write_all(&detect_seq).await { + tracing::warn!(error = %e, "BLE RNode native detect write failed"); + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + + // Without gating on DETECT_RESP + firmware version we'd flag + // "online" while the radio is asleep or the BLE-NUS bridge + // dropped a frame. + let detected = + wait_for_rnode_handshake(&mut tcp_read, Duration::from_secs(5), &running_task) + .await; + if !detected { + tracing::warn!( + name = %log_name, + "BLE RNode handshake timed out — RNode did not respond to detect, retrying" + ); + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + + let mut init_seq = rnode::build_init_sequence(&rnode_cfg); + init_seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg)); + if let Err(e) = tcp_write.write_all(&init_seq).await { + tracing::warn!(error = %e, "BLE RNode native init write failed"); + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + + tracing::info!( + name = %log_name, + ble_uri = %ble_uri, + tcp_port, + bitrate_bps = bitrate, + "BLE RNode native bridge established (handshake confirmed)" + ); + + online_handle.store(true, Ordering::SeqCst); + tries = 0; + backoff = RECONNECT_WAIT; + + let ready = Arc::new(AtomicBool::new(true)); + + let (conn_tx, mut conn_rx) = mpsc::channel::(256); + let online_w = online_handle.clone(); + let ready_w = ready.clone(); + let txb_w = task_txb.clone(); + let write_handle = tokio::spawn(async move { + while let Some(data) = conn_rx.recv().await { + txb_w.fetch_add(data.len() as u64, Ordering::Relaxed); + if flow_control { + while !ready_w.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + if !online_w.load(Ordering::SeqCst) { + return; + } + } + } + let framed = kiss::frame(&data); + if let Err(e) = tcp_write.write_all(&framed).await { + tracing::warn!(error = %e, "BLE RNode native write error"); + online_w.store(false, Ordering::SeqCst); + return; + } + } + }); + + // Outer rx is persistent across reconnects; conn_tx is rebuilt + // each cycle. + let rx_ref = rx.clone(); + let fwd_handle = tokio::spawn(async move { + let mut guard = rx_ref.lock().await; + while let Some(data) = guard.recv().await { + if conn_tx.send(data).await.is_err() { + break; + } + } + }); + + let mut deframer = kiss::RawKissDeframer::new(); + let mut last_rssi: Option = None; + let mut last_snr: Option = None; + let mut buf = [0u8; 4096]; + let mut transport_closed = false; + + 'read: loop { + if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) { + break 'read; + } + + let n = tokio::select! { + result = tcp_read.read(&mut buf) => { + match result { + Ok(0) => { + tracing::warn!("BLE RNode native bridge closed (EOF)"); + break 'read; + } + Ok(n) => n, + Err(e) => { + tracing::warn!(error = %e, "BLE RNode native read error"); + break 'read; + } + } + } + _ = tokio::time::sleep(RUNNING_POLL) => { + // Idle LoRa silence is normal — only break if + // shutdown flag cleared. + if !running_task.load(Ordering::SeqCst) { + break 'read; + } + continue; + } + }; + + let data = &buf[..n]; + for (cmd, frame) in deframer.feed(data) { + match rnode::process_rnode_response( + cmd, + &frame, + id, + &mut last_rssi, + &mut last_snr, + ) { + RNodeResponse::Packet(msg) => { + task_rxb.fetch_add(frame.len() as u64, Ordering::Relaxed); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + transport_closed = true; + break 'read; + } + } + RNodeResponse::Ready(is_ready) => { + ready.store(is_ready, Ordering::SeqCst); + } + RNodeResponse::None => {} + } + } + } + + online_handle.store(false, Ordering::SeqCst); + fwd_handle.abort(); + let _ = fwd_handle.await; + write_handle.abort(); + let _ = write_handle.await; + + if transport_closed { + return; + } + + if !running_task.load(Ordering::SeqCst) { + return; + } + + if reconnect_try_exhausted(&mut tries) { + tracing::warn!(name = %log_name, "BLE RNode native: max reconnect tries reached"); + return; + } + tracing::info!(name = %log_name, seconds = backoff, "BLE RNode native reconnecting"); + if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await { + return; + } + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate, + mtu: 508, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::kiss; + use crate::rnode; + + #[test] + fn test_ble_rnode_config_defaults() { + let cfg = BleRNodeConfig::new("ble-rnode", "ble://RNode 3B87"); + assert_eq!(cfg.name, "ble-rnode"); + assert_eq!(cfg.ble_uri, "ble://RNode 3B87"); + assert_eq!(cfg.frequency, 868_000_000); + assert_eq!(cfg.bandwidth, 125_000); + assert_eq!(cfg.spreading_factor, 7); + assert_eq!(cfg.coding_rate, 5); + assert_eq!(cfg.tx_power, 14); + assert!(cfg.flow_control); + assert!(cfg.st_alock.is_none()); + assert!(cfg.lt_alock.is_none()); + } + + #[test] + fn test_ble_rnode_config_custom_params() { + let mut cfg = BleRNodeConfig::new("custom", "ble://F4:12:73:29:4E:89"); + cfg.frequency = 915_000_000; + cfg.bandwidth = 250_000; + cfg.spreading_factor = 12; + cfg.coding_rate = 8; + cfg.tx_power = 22; + cfg.mode = InterfaceMode::AccessPoint; + cfg.flow_control = false; + cfg.st_alock = Some(50.0); + cfg.lt_alock = Some(75.0); + + assert_eq!(cfg.frequency, 915_000_000); + assert_eq!(cfg.bandwidth, 250_000); + assert_eq!(cfg.spreading_factor, 12); + assert_eq!(cfg.coding_rate, 8); + assert_eq!(cfg.tx_power, 22); + assert_eq!(cfg.mode, InterfaceMode::AccessPoint); + assert!(!cfg.flow_control); + assert_eq!(cfg.st_alock, Some(50.0)); + assert_eq!(cfg.lt_alock, Some(75.0)); + } + + #[test] + fn test_ble_rnode_config_empty_uri() { + let cfg = BleRNodeConfig::new("any-rnode", "ble://"); + assert_eq!(cfg.ble_uri, "ble://"); + } + + #[test] + fn test_ble_rnode_config_address_uri() { + let cfg = BleRNodeConfig::new("addr-rnode", "ble://F4:12:73:29:4E:89"); + assert_eq!(cfg.ble_uri, "ble://F4:12:73:29:4E:89"); + } + + #[test] + fn test_ble_rnode_config_name_uri() { + let cfg = BleRNodeConfig::new("named-rnode", "ble://RNode 3B87"); + assert_eq!(cfg.ble_uri, "ble://RNode 3B87"); + } + + #[test] + fn test_nus_uuids() { + assert_eq!( + NUS_SERVICE_UUID.to_string().to_uppercase(), + "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" + ); + assert_eq!( + NUS_RX_CHAR_UUID.to_string().to_uppercase(), + "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" + ); + assert_eq!( + NUS_TX_CHAR_UUID.to_string().to_uppercase(), + "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" + ); + } + + #[test] + fn test_nus_service_uuid_distinct() { + assert_ne!(NUS_SERVICE_UUID, NUS_RX_CHAR_UUID); + assert_ne!(NUS_SERVICE_UUID, NUS_TX_CHAR_UUID); + assert_ne!(NUS_RX_CHAR_UUID, NUS_TX_CHAR_UUID); + } + + // ── Shutdown / running-flag tests ── + + #[test] + fn test_register_unregister_running() { + let id: InterfaceId = 0xDEAD_BEEF_0000_0001; + assert!(!is_registered(id)); + let flag = register_running(id); + assert!(is_registered(id)); + assert!(flag.load(Ordering::SeqCst)); + unregister_running(id); + assert!(!is_registered(id)); + } + + #[test] + fn test_stop_ble_rnode_interface_sets_flag() { + let id: InterfaceId = 0xDEAD_BEEF_0000_0002; + let flag = register_running(id); + assert!(flag.load(Ordering::SeqCst)); + stop_ble_rnode_interface(id); + assert!(!flag.load(Ordering::SeqCst)); + // Map entry survives until the owning task's Drop runs; clean up. + unregister_running(id); + } + + #[test] + fn test_stop_ble_rnode_interface_unknown_id_is_noop() { + let id: InterfaceId = 0xDEAD_BEEF_0000_0003; + assert!(!is_registered(id)); + stop_ble_rnode_interface(id); + assert!(!is_registered(id)); + } + + #[tokio::test] + async fn test_wait_or_shutdown_returns_false_when_flag_stays_set() { + // Short real-time wait; flag stays true → full duration elapses. + let flag = AtomicBool::new(true); + let started = std::time::Instant::now(); + let cleared = wait_or_shutdown(Duration::from_millis(120), &flag).await; + assert!(!cleared, "should return false when flag stayed set"); + assert!( + started.elapsed() >= Duration::from_millis(100), + "should have waited roughly the full deadline" + ); + } + + #[tokio::test] + async fn test_wait_or_shutdown_returns_true_when_flag_already_cleared() { + // Fast path: flag is false on entry, helper should return true + // without consuming the full deadline. + let flag = AtomicBool::new(false); + let started = std::time::Instant::now(); + let cleared = wait_or_shutdown(Duration::from_secs(5), &flag).await; + assert!(cleared, "should return true immediately when flag is clear"); + assert!( + started.elapsed() < Duration::from_secs(1), + "should not have waited the full deadline" + ); + } + + #[tokio::test] + async fn test_wait_or_shutdown_returns_true_when_flag_cleared_mid_wait() { + // Background task clears the flag partway through; helper wakes + // at its next RUNNING_POLL tick (≤ 1 s) and bails before the + // 3 s overall deadline. + let flag = Arc::new(AtomicBool::new(true)); + let flag_bg = flag.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(50)).await; + flag_bg.store(false, Ordering::SeqCst); + }); + let started = std::time::Instant::now(); + let cleared = wait_or_shutdown(Duration::from_secs(3), &flag).await; + assert!(cleared, "should return true once flag cleared during wait"); + assert!( + started.elapsed() < Duration::from_secs(2), + "should have woken at next poll tick, not slept the full deadline" + ); + } + + // ── Device type tests ── + + #[test] + fn test_device_type_rnode_serialization() { + let dev = BleDevice { + name: "RNode 3B87".into(), + address: "F4:12:73:29:4E:89".into(), + rssi: Some(-65), + device_type: BleDeviceType::RNode, + bonded: false, + }; + let json = serde_json::to_string(&dev).unwrap(); + assert!(json.contains("\"device_type\":\"rnode\"")); + assert!(json.contains("\"rssi\":-65")); + assert!(json.contains("\"bonded\":false")); + } + + #[test] + fn test_device_type_unknown_serialization() { + let dev = BleDevice { + name: "Unknown Device".into(), + address: "11:22:33:44:55:66".into(), + rssi: None, + device_type: BleDeviceType::Unknown, + bonded: false, + }; + let json = serde_json::to_string(&dev).unwrap(); + assert!(json.contains("\"device_type\":\"unknown\"")); + } + + #[test] + fn test_device_type_equality() { + assert_eq!(BleDeviceType::RNode, BleDeviceType::RNode); + assert_eq!(BleDeviceType::Unknown, BleDeviceType::Unknown); + assert_ne!(BleDeviceType::RNode, BleDeviceType::Unknown); + } + + #[test] + fn test_ble_device_no_rssi() { + let dev = BleDevice { + name: "RNode 1234".into(), + address: "AA:BB:CC:DD:EE:FF".into(), + rssi: None, + device_type: BleDeviceType::RNode, + bonded: false, + }; + let json = serde_json::to_string(&dev).unwrap(); + assert!(json.contains("\"rssi\":null")); + } + + #[test] + fn test_ble_device_full_roundtrip() { + let dev = BleDevice { + name: "RNode 3B87".into(), + address: "F4:12:73:29:4E:89".into(), + rssi: Some(-42), + device_type: BleDeviceType::RNode, + bonded: false, + }; + let json = serde_json::to_string(&dev).unwrap(); + let deserialized: BleDevice = serde_json::from_str(&json).unwrap(); + assert_eq!(deserialized.name, "RNode 3B87"); + assert_eq!(deserialized.address, "F4:12:73:29:4E:89"); + assert_eq!(deserialized.rssi, Some(-42)); + assert_eq!(deserialized.device_type, BleDeviceType::RNode); + assert!(!deserialized.bonded); + } + + // ── KISS framing over BLE ── + + #[test] + fn test_kiss_frame_fits_single_ble_chunk() { + let payload = vec![0x42; 100]; + let framed = kiss::frame(&payload); + assert!(framed.len() <= 512); + let chunks: Vec<&[u8]> = framed.chunks(512).collect(); + assert_eq!(chunks.len(), 1); + } + + #[test] + fn test_kiss_frame_requires_chunking() { + let payload = vec![0x42; 500]; + let framed = kiss::frame(&payload); + assert_eq!(framed.len(), 503); // 500 + FEND + CMD + FEND + let chunks: Vec<&[u8]> = framed.chunks(256).collect(); + assert_eq!(chunks.len(), 2); + } + + #[test] + fn test_kiss_frame_with_many_special_bytes() { + // All FEND bytes → each doubles due to escaping + let payload = vec![kiss::FEND; 100]; + let framed = kiss::frame(&payload); + assert_eq!(framed.len(), 200 + 3); // 2 bytes per FEND + overhead + } + + #[test] + fn test_kiss_deframe_from_ble_notification_chunks() { + let payload = b"hello from rnode over ble"; + let framed = kiss::frame(payload); + + let mut deframer = kiss::RawKissDeframer::new(); + let mut frames_received = Vec::new(); + for chunk in framed.chunks(10) { + frames_received.extend(deframer.feed(chunk)); + } + assert_eq!(frames_received.len(), 1); + assert_eq!(frames_received[0].0, kiss::CMD_DATA); + assert_eq!(frames_received[0].1, payload); + } + + #[test] + fn test_kiss_deframe_multiple_frames_in_one_notification() { + let f1 = kiss::frame(b"first"); + let f2 = kiss::frame(b"second"); + let mut combined = f1; + combined.extend_from_slice(&f2); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&combined); + assert_eq!(frames.len(), 2); + assert_eq!(frames[0].1, b"first"); + assert_eq!(frames[1].1, b"second"); + } + + #[test] + fn test_kiss_deframe_split_across_notifications() { + let framed = kiss::frame(b"split test data"); + let mid = framed.len() / 2; + + let mut deframer = kiss::RawKissDeframer::new(); + let first = deframer.feed(&framed[..mid]); + assert!(first.is_empty()); + + let second = deframer.feed(&framed[mid..]); + assert_eq!(second.len(), 1); + assert_eq!(second[0].1, b"split test data"); + } + + // ── Init sequence tests ── + + #[test] + fn test_ble_init_sequence_uses_rnode_helpers() { + let ble_cfg = BleRNodeConfig::new("ble0", "ble://RNode 1234"); + let rnode_cfg = rnode::RNodeConfig { + name: ble_cfg.name.clone(), + port: ble_cfg.ble_uri.clone(), + baud_rate: 0, + frequency: ble_cfg.frequency, + bandwidth: ble_cfg.bandwidth, + spreading_factor: ble_cfg.spreading_factor, + coding_rate: ble_cfg.coding_rate, + tx_power: ble_cfg.tx_power, + mode: ble_cfg.mode, + flow_control: ble_cfg.flow_control, + st_alock: ble_cfg.st_alock, + lt_alock: ble_cfg.lt_alock, + }; + let seq = rnode::build_init_sequence(&rnode_cfg); + assert!(!seq.is_empty()); + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&seq); + assert_eq!(frames.len(), 6); + } + + #[test] + fn test_ble_detect_sequence_parseable() { + let seq = rnode::build_detect_sequence(); + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&seq); + assert_eq!(frames.len(), 4); + } + + #[test] + fn test_ble_full_init_with_airtime() { + let mut rnode_cfg = rnode::RNodeConfig::new("test", "ble://"); + rnode_cfg.st_alock = Some(25.0); + rnode_cfg.lt_alock = Some(50.0); + let mut seq = rnode::build_init_sequence(&rnode_cfg); + seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg)); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&seq); + assert_eq!(frames.len(), 8); // 6 init + 2 airtime + } + + // ── process_rnode_response tests ── + + #[test] + fn test_response_data_packet() { + let data = vec![0x01, 0x02, 0x03]; + let mut rssi = Some(-65.0_f32); + let mut snr = Some(8.0_f32); + match rnode::process_rnode_response(kiss::CMD_DATA, &data, 42, &mut rssi, &mut snr) { + rnode::RNodeResponse::Packet(msg) => { + if let rns_transport::messages::TransportMessage::Inbound(pkt) = msg { + assert_eq!(pkt.raw, data); + assert_eq!(pkt.interface_id, 42); + assert_eq!(pkt.rssi, Some(-65.0)); + assert_eq!(pkt.snr, Some(8.0)); + } else { + panic!("Expected Inbound packet"); + } + } + _ => panic!("Expected Packet response"), + } + assert!(rssi.is_none()); + assert!(snr.is_none()); + } + + #[test] + fn test_response_empty_data_ignored() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response(kiss::CMD_DATA, &[], 1, &mut rssi, &mut snr) { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None for empty data"), + } + } + + #[test] + fn test_response_rssi_updates() { + let mut rssi = None; + let mut snr = None; + rnode::process_rnode_response(rnode::CMD_STAT_RSSI, &[0xBF], 1, &mut rssi, &mut snr); + assert_eq!(rssi, Some(-65.0)); + } + + #[test] + fn test_response_snr_updates() { + let mut rssi = None; + let mut snr = None; + rnode::process_rnode_response(rnode::CMD_STAT_SNR, &[32], 1, &mut rssi, &mut snr); + assert_eq!(snr, Some(8.0)); + } + + #[test] + fn test_response_rssi_snr_reset_after_data() { + let mut rssi = Some(-70.0_f32); + let mut snr = Some(6.0_f32); + rnode::process_rnode_response(kiss::CMD_DATA, &[0xFF], 1, &mut rssi, &mut snr); + assert!(rssi.is_none()); + assert!(snr.is_none()); + } + + #[test] + fn test_response_ready_true() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response(rnode::CMD_READY, &[0x01], 1, &mut rssi, &mut snr) { + rnode::RNodeResponse::Ready(true) => {} + _ => panic!("Expected Ready(true)"), + } + } + + #[test] + fn test_response_ready_false() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response(rnode::CMD_READY, &[0x00], 1, &mut rssi, &mut snr) { + rnode::RNodeResponse::Ready(false) => {} + _ => panic!("Expected Ready(false)"), + } + } + + #[test] + fn test_response_detect() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response( + rnode::CMD_DETECT, + &[rnode::DETECT_RESP], + 1, + &mut rssi, + &mut snr, + ) { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None"), + } + } + + #[test] + fn test_response_radio_state_on() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response( + rnode::CMD_RADIO_STATE, + &[rnode::RADIO_STATE_ON], + 1, + &mut rssi, + &mut snr, + ) { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None"), + } + } + + #[test] + fn test_response_firmware_version() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response(rnode::CMD_FW_VERSION, &[2, 10], 1, &mut rssi, &mut snr) + { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None"), + } + } + + #[test] + fn test_response_battery_status() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response( + rnode::CMD_STAT_BAT, + &[0x0E, 0x74], + 1, + &mut rssi, + &mut snr, + ) { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None"), + } + } + + #[test] + fn test_response_temperature() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response(rnode::CMD_STAT_TEMP, &[25], 1, &mut rssi, &mut snr) { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None"), + } + } + + #[test] + fn test_response_error() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response(rnode::CMD_ERROR, &[0x01], 1, &mut rssi, &mut snr) { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None"), + } + } + + #[test] + fn test_response_unknown_command() { + let mut rssi = None; + let mut snr = None; + match rnode::process_rnode_response(0xFE, &[0x01, 0x02], 1, &mut rssi, &mut snr) { + rnode::RNodeResponse::None => {} + _ => panic!("Expected None for unknown command"), + } + } + + // ── Write chunking tests ── + + #[test] + fn test_data_chunking_512() { + let data = vec![0u8; 1024]; + let chunks: Vec<&[u8]> = data.chunks(512).collect(); + assert_eq!(chunks.len(), 2); + assert_eq!(chunks[0].len(), 512); + assert_eq!(chunks[1].len(), 512); + } + + #[test] + fn test_data_chunking_exact_boundary() { + let data = vec![0u8; 512]; + let chunks: Vec<&[u8]> = data.chunks(512).collect(); + assert_eq!(chunks.len(), 1); + } + + #[test] + fn test_data_chunking_small() { + let data = [0u8; 20]; + let chunks: Vec<&[u8]> = data.chunks(512).collect(); + assert_eq!(chunks.len(), 1); + } + + #[test] + fn test_data_no_chunking_needed() { + let data = [0u8; 100]; + let chunks: Vec<&[u8]> = data.chunks(512).collect(); + assert_eq!(chunks.len(), 1); + assert_eq!(chunks[0].len(), 100); + } + + // ── Hardware-dependent tests (require BLE adapter + paired RNode) ── + + #[tokio::test] + #[ignore] + async fn test_ble_scan_finds_devices() { + let devices = scan_ble_devices(3).await.expect("BLE scan failed"); + println!("Found {} BLE devices:", devices.len()); + for d in &devices { + println!( + " {} ({}) RSSI:{:?} Type:{:?}", + d.name, d.address, d.rssi, d.device_type + ); + } + } + + #[tokio::test] + #[ignore] + async fn test_ble_connect_to_rnode() { + let adapter = get_adapter().await.expect("No BLE adapter"); + let conn = connect_rnode(&adapter, "ble://") + .await + .expect("No RNode found. Pair an RNode first."); + assert!(conn.peripheral.is_connected().await.unwrap_or(false)); + conn.peripheral.disconnect().await.ok(); + } + + #[tokio::test] + #[ignore] + async fn test_ble_rnode_full_lifecycle() { + let (transport_tx, mut _transport_rx) = mpsc::channel(64); + let config = BleRNodeConfig::new("test-rnode", "ble://"); + let handle = spawn_ble_rnode_interface(config, 99, transport_tx) + .await + .expect("Failed to spawn BLE RNode interface"); + + assert!(handle.online.load(Ordering::SeqCst)); + assert_eq!(handle.mtu, 508); + assert_eq!(handle.id, 99); + + tokio::time::sleep(Duration::from_secs(2)).await; + handle.online.store(false, Ordering::SeqCst); + } +} diff --git a/crates/rns-interface/src/hdlc.rs b/crates/rns-interface/src/hdlc.rs new file mode 100644 index 0000000..1340a7d --- /dev/null +++ b/crates/rns-interface/src/hdlc.rs @@ -0,0 +1,298 @@ +//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, Backbone. +//! Wire: `[FLAG][escaped_payload][FLAG]`. Encode ESC before FLAG; decode FLAG before ESC. + +/// HDLC frame delimiter. +pub const FLAG: u8 = 0x7E; + +/// HDLC escape byte. +pub const ESC: u8 = 0x7D; + +/// XOR mask applied to escaped bytes. +pub const ESC_MASK: u8 = 0x20; + +/// Upper bound on a single HDLC frame (sized for full resource transfers on TCP/Local MTUs). +const MAX_FRAME_SIZE: usize = 524288; + +/// Pre-allocated capacity for the deframer accumulator. Covers typical HW_MTUs +/// with headroom; larger frames grow the Vec normally. +const DEFRAME_BUF_CAPACITY: usize = 2048; + +/// Append the escape-encoded form of `data` to `out`. No allocation if `out` has capacity. +pub fn escape_into(data: &[u8], out: &mut Vec) { + let mut i = 0; + while i < data.len() { + match data[i..].iter().position(|&b| b == ESC || b == FLAG) { + Some(rel) => { + let hit = i + rel; + out.extend_from_slice(&data[i..hit]); + out.push(ESC); + out.push(data[hit] ^ ESC_MASK); + i = hit + 1; + } + None => { + out.extend_from_slice(&data[i..]); + return; + } + } + } +} + +/// Append the unescaped form of `data` to `out`. Unknown escape sequences and a +/// trailing lone ESC byte are passed through unchanged — matching the previous +/// implementation so any consumer relying on length/CRC rejection still sees +/// the same bytes. +pub fn unescape_into(data: &[u8], out: &mut Vec) { + let mut i = 0; + while i < data.len() { + match data[i..].iter().position(|&b| b == ESC) { + Some(rel) => { + let hit = i + rel; + out.extend_from_slice(&data[i..hit]); + if hit + 1 < data.len() { + let next = data[hit + 1]; + if next == (FLAG ^ ESC_MASK) { + out.push(FLAG); + } else if next == (ESC ^ ESC_MASK) { + out.push(ESC); + } else { + out.push(ESC); + out.push(next); + } + i = hit + 2; + } else { + out.push(ESC); + return; + } + } + None => { + out.extend_from_slice(&data[i..]); + return; + } + } + } +} + +/// Append a complete HDLC frame for `data` to `out`. +pub fn frame_into(data: &[u8], out: &mut Vec) { + out.push(FLAG); + escape_into(data, out); + out.push(FLAG); +} + +pub fn escape(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + data.len() / 8); + escape_into(data, &mut out); + out +} + +pub fn unescape(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len()); + unescape_into(data, &mut out); + out +} + +pub fn frame(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + data.len() / 8 + 2); + frame_into(data, &mut out); + out +} + +pub struct HdlcDeframer { + buffer: Vec, + in_frame: bool, + /// Reusable scratch for unescape output to avoid per-frame allocation. + unescape_scratch: Vec, +} + +impl HdlcDeframer { + pub fn new() -> Self { + Self { + buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY), + in_frame: false, + unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY), + } + } + + pub fn feed(&mut self, data: &[u8]) -> Vec> { + let mut frames = Vec::new(); + let mut i = 0; + while i < data.len() { + match data[i..].iter().position(|&b| b == FLAG) { + Some(rel) => { + let hit = i + rel; + if self.in_frame { + self.append_in_frame(&data[i..hit]); + if !self.buffer.is_empty() { + self.unescape_scratch.clear(); + unescape_into(&self.buffer, &mut self.unescape_scratch); + if !self.unescape_scratch.is_empty() { + frames.push(std::mem::take(&mut self.unescape_scratch)); + // Restore capacity for the next frame. + self.unescape_scratch = Vec::with_capacity(DEFRAME_BUF_CAPACITY); + } + } + self.buffer.clear(); + } + self.in_frame = true; + i = hit + 1; + } + None => { + if self.in_frame { + self.append_in_frame(&data[i..]); + } + return frames; + } + } + } + frames + } + + /// Append `chunk` to `self.buffer` while enforcing `MAX_FRAME_SIZE`. On + /// overflow the in-progress frame is dropped and we wait for the next FLAG + /// to resync — matching the previous byte-loop behavior. + fn append_in_frame(&mut self, chunk: &[u8]) { + if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE { + self.buffer.clear(); + self.in_frame = false; + return; + } + self.buffer.extend_from_slice(chunk); + } + + pub fn reset(&mut self) { + self.buffer.clear(); + self.in_frame = false; + } +} + +impl Default for HdlcDeframer { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_escape_unescape_roundtrip() { + let data = vec![0x00, FLAG, ESC, 0xFF, FLAG, ESC, 0x42]; + let escaped = escape(&data); + let unescaped = unescape(&escaped); + assert_eq!(unescaped, data); + } + + #[test] + fn test_escape_no_special_bytes() { + let data = b"hello world"; + let escaped = escape(data); + assert_eq!(escaped, data); + } + + #[test] + fn test_escape_flag_byte() { + let data = vec![FLAG]; + let escaped = escape(&data); + assert_eq!(escaped, vec![ESC, FLAG ^ ESC_MASK]); + } + + #[test] + fn test_escape_esc_byte() { + let data = vec![ESC]; + let escaped = escape(&data); + assert_eq!(escaped, vec![ESC, ESC ^ ESC_MASK]); + } + + #[test] + fn test_frame_and_deframe() { + let data = b"test packet data"; + let framed = frame(data); + + let mut deframer = HdlcDeframer::new(); + let frames = deframer.feed(&framed); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0], data); + } + + #[test] + fn test_deframer_multiple_frames() { + let f1 = frame(b"first"); + let f2 = frame(b"second"); + + let mut combined = f1; + combined.extend_from_slice(&f2); + + let mut deframer = HdlcDeframer::new(); + let frames = deframer.feed(&combined); + assert_eq!(frames.len(), 2); + assert_eq!(frames[0], b"first"); + assert_eq!(frames[1], b"second"); + } + + #[test] + fn test_deframer_streaming() { + let framed = frame(b"streamed"); + + let mut deframer = HdlcDeframer::new(); + + let mid = framed.len() / 2; + let frames1 = deframer.feed(&framed[..mid]); + assert!(frames1.is_empty()); + + let frames2 = deframer.feed(&framed[mid..]); + assert_eq!(frames2.len(), 1); + assert_eq!(frames2[0], b"streamed"); + } + + #[test] + fn test_tricky_sequence() { + // ESC, FLAG^MASK must decode to a single FLAG byte. + let data = vec![ESC, 0x5E]; + let unescaped = unescape(&data); + assert_eq!(unescaped, vec![FLAG]); + } + + #[test] + fn test_into_variants_match_allocating() { + // The allocating wrappers must produce byte-identical output. + let inputs: &[&[u8]] = &[ + b"", + b"plain", + &[FLAG, ESC, 0x00, 0xFF, FLAG], + &[ESC, ESC, ESC], + &[0x00; 1024], + ]; + for data in inputs { + let mut buf = Vec::new(); + escape_into(data, &mut buf); + assert_eq!(buf, escape(data)); + + let escaped = escape(data); + let mut buf2 = Vec::new(); + unescape_into(&escaped, &mut buf2); + assert_eq!(buf2, unescape(&escaped)); + + let mut buf3 = Vec::new(); + frame_into(data, &mut buf3); + assert_eq!(buf3, frame(data)); + } + } + + #[test] + fn test_deframer_oversized_drops_then_resyncs() { + // A frame body larger than MAX_FRAME_SIZE must drop and resync on the + // next FLAG, exactly like the per-byte implementation. + let mut deframer = HdlcDeframer::new(); + let mut oversized = vec![FLAG]; + oversized.extend(std::iter::repeat_n(0x55, MAX_FRAME_SIZE + 100)); + oversized.push(FLAG); + let frames = deframer.feed(&oversized); + assert!(frames.is_empty()); + + let small = frame(b"after-overflow"); + let frames = deframer.feed(&small); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0], b"after-overflow"); + } +} diff --git a/crates/rns-interface/src/i2p.rs b/crates/rns-interface/src/i2p.rs new file mode 100644 index 0000000..94eeee7 --- /dev/null +++ b/crates/rns-interface/src/i2p.rs @@ -0,0 +1,1058 @@ +//! Reticulum-over-I2P via SAM v3.1 bridge (default 127.0.0.1:7656). +//! Handshake: HELLO → SESSION CREATE → STREAM CONNECT/ACCEPT; +//! stream then carries HDLC-framed packets. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use bytes::Bytes; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpStream; +use tokio::sync::mpsc; + +use crate::hdlc; +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const DEFAULT_SAM_ADDRESS: &str = "127.0.0.1"; +pub const DEFAULT_SAM_PORT: u16 = 7656; + +pub const BITRATE_GUESS: u64 = 256_000; +pub const HW_MTU: u32 = 1064; + +pub const I2P_TCP_USER_TIMEOUT: u32 = 45; +pub const I2P_PROBE_AFTER: u64 = 10; +pub const I2P_PROBE_INTERVAL: u64 = 9; +pub const I2P_PROBES: u64 = 5; + +/// 2× full probe cycle for safety margin. +pub const I2P_READ_TIMEOUT: u64 = (I2P_PROBE_INTERVAL * I2P_PROBES + I2P_PROBE_AFTER) * 2; + +pub const TUNNEL_KEEPALIVE: u64 = 300; +pub const RECONNECT_WAIT: u64 = 15; +pub const RECONNECT_WAIT_MAX: u64 = 300; + +pub const SAM_VERSION: &str = "3.1"; + +#[derive(Debug, thiserror::Error)] +pub enum SamError { + #[error("SAM I/O error: {0}")] + Io(#[from] std::io::Error), + #[error("SAM handshake failed: {0}")] + HandshakeFailed(String), + #[error("SAM session creation failed: {0}")] + SessionFailed(String), + #[error("SAM stream connect failed: {0}")] + StreamFailed(String), + #[error("SAM stream accept failed: {0}")] + AcceptFailed(String), + #[error("unexpected SAM reply: {0}")] + UnexpectedReply(String), +} + +/// Parse SAM reply; bare tokens (no `=`) get empty value. +pub fn parse_sam_reply(line: &str) -> Vec<(String, String)> { + let mut pairs = Vec::new(); + for token in line.split_whitespace() { + if let Some(eq_pos) = token.find('=') { + let key = token[..eq_pos].to_string(); + let value = token[eq_pos + 1..].to_string(); + pairs.push((key, value)); + } else { + pairs.push((token.to_string(), String::new())); + } + } + pairs +} + +pub fn sam_reply_get<'a>(pairs: &'a [(String, String)], key: &str) -> Option<&'a str> { + pairs + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.as_str()) +} + +pub fn sam_reply_has_token(pairs: &[(String, String)], token: &str) -> bool { + pairs.iter().any(|(k, v)| k == token && v.is_empty()) +} + +async fn read_sam_reply( + reader: &mut BufReader, +) -> Result { + let mut line = String::new(); + let n = reader.read_line(&mut line).await?; + if n == 0 { + return Err(SamError::Io(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "SAM connection closed during handshake", + ))); + } + Ok(line.trim_end().to_string()) +} + +async fn sam_hello( + writer: &mut tokio::net::tcp::OwnedWriteHalf, + reader: &mut BufReader, +) -> Result<(), SamError> { + let hello_msg = format!("HELLO VERSION MIN={} MAX={}\n", SAM_VERSION, SAM_VERSION); + writer.write_all(hello_msg.as_bytes()).await?; + writer.flush().await?; + + let reply = read_sam_reply(reader).await?; + let pairs = parse_sam_reply(&reply); + + if !sam_reply_has_token(&pairs, "HELLO") || !sam_reply_has_token(&pairs, "REPLY") { + return Err(SamError::HandshakeFailed(format!( + "expected HELLO REPLY, got: {}", + reply + ))); + } + + match sam_reply_get(&pairs, "RESULT") { + Some("OK") => Ok(()), + Some(other) => Err(SamError::HandshakeFailed(format!( + "HELLO RESULT={}, expected OK", + other + ))), + None => Err(SamError::HandshakeFailed(format!( + "no RESULT in HELLO reply: {}", + reply + ))), + } +} + +/// Returns the destination (base64). `private_key=None` = transient. +async fn sam_session_create( + writer: &mut tokio::net::tcp::OwnedWriteHalf, + reader: &mut BufReader, + session_id: &str, + private_key: Option<&str>, +) -> Result { + let dest_param = match private_key { + Some(key) => key.to_string(), + None => "TRANSIENT".to_string(), + }; + let create_msg = format!( + "SESSION CREATE STYLE=STREAM ID={} DESTINATION={}\n", + session_id, dest_param + ); + writer.write_all(create_msg.as_bytes()).await?; + writer.flush().await?; + + let reply = read_sam_reply(reader).await?; + let pairs = parse_sam_reply(&reply); + + if !sam_reply_has_token(&pairs, "SESSION") || !sam_reply_has_token(&pairs, "STATUS") { + return Err(SamError::SessionFailed(format!( + "expected SESSION STATUS, got: {}", + reply + ))); + } + + match sam_reply_get(&pairs, "RESULT") { + Some("OK") => {} + Some(other) => { + let msg_detail = sam_reply_get(&pairs, "MESSAGE").unwrap_or("no details"); + return Err(SamError::SessionFailed(format!( + "SESSION RESULT={}: {}", + other, msg_detail + ))); + } + None => { + return Err(SamError::SessionFailed(format!( + "no RESULT in SESSION STATUS: {}", + reply + ))); + } + } + + match sam_reply_get(&pairs, "DESTINATION") { + Some(dest) => Ok(dest.to_string()), + None => Err(SamError::SessionFailed( + "SESSION STATUS OK but no DESTINATION returned".to_string(), + )), + } +} + +/// SAM STREAM CONNECT — needs its own TCP connection (SAM forbids sharing +/// the session control socket). On OK the socket becomes the data stream. +async fn sam_stream_connect( + writer: &mut tokio::net::tcp::OwnedWriteHalf, + reader: &mut BufReader, + session_id: &str, + peer_destination: &str, +) -> Result<(), SamError> { + let connect_msg = format!( + "STREAM CONNECT ID={} DESTINATION={} SILENT=false\n", + session_id, peer_destination + ); + writer.write_all(connect_msg.as_bytes()).await?; + writer.flush().await?; + + let reply = read_sam_reply(reader).await?; + let pairs = parse_sam_reply(&reply); + + if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") { + return Err(SamError::StreamFailed(format!( + "expected STREAM STATUS, got: {}", + reply + ))); + } + + match sam_reply_get(&pairs, "RESULT") { + Some("OK") => Ok(()), + Some(other) => { + let msg_detail = sam_reply_get(&pairs, "MESSAGE").unwrap_or("no details"); + Err(SamError::StreamFailed(format!( + "STREAM CONNECT RESULT={}: {}", + other, msg_detail + ))) + } + None => Err(SamError::StreamFailed(format!( + "no RESULT in STREAM STATUS: {}", + reply + ))), + } +} + +/// SAM STREAM ACCEPT (separate socket; same requirement as connect). +/// Returns the remote peer's destination after the status line. +async fn sam_stream_accept( + writer: &mut tokio::net::tcp::OwnedWriteHalf, + reader: &mut BufReader, + session_id: &str, +) -> Result { + let accept_msg = format!("STREAM ACCEPT ID={} SILENT=false\n", session_id); + writer.write_all(accept_msg.as_bytes()).await?; + writer.flush().await?; + + let reply = read_sam_reply(reader).await?; + let pairs = parse_sam_reply(&reply); + + if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") { + return Err(SamError::AcceptFailed(format!( + "expected STREAM STATUS, got: {}", + reply + ))); + } + + match sam_reply_get(&pairs, "RESULT") { + Some("OK") => {} + Some(other) => { + let msg_detail = sam_reply_get(&pairs, "MESSAGE").unwrap_or("no details"); + return Err(SamError::AcceptFailed(format!( + "STREAM ACCEPT RESULT={}: {}", + other, msg_detail + ))); + } + None => { + return Err(SamError::AcceptFailed(format!( + "no RESULT in STREAM STATUS: {}", + reply + ))); + } + } + + // SAM writes peer destination on its own line before raw data. + let dest_line = read_sam_reply(reader).await?; + Ok(dest_line.trim().to_string()) +} + +async fn connect_to_sam(sam_host: &str, sam_port: u16) -> Result { + let addr = format!("{}:{}", sam_host, sam_port); + let stream = TcpStream::connect(&addr).await.map_err(SamError::Io)?; + let _ = stream.set_nodelay(true); + Ok(stream) +} + +fn generate_session_id() -> String { + use rand::Rng; + let mut rng = rand::thread_rng(); + let id: u64 = rng.r#gen(); + format!("reticulum_{:016x}", id) +} + +#[derive(Debug, Clone)] +pub struct I2PServerConfig { + pub name: String, + pub sam_host: String, + pub sam_port: u16, + /// Base64 private key for a persistent destination; `None` = transient. + pub keyfile: Option, + pub reconnect_delay: u64, + pub mode: InterfaceMode, +} + +impl I2PServerConfig { + pub fn new(name: &str) -> Self { + Self { + name: name.to_string(), + sam_host: DEFAULT_SAM_ADDRESS.to_string(), + sam_port: DEFAULT_SAM_PORT, + keyfile: None, + reconnect_delay: RECONNECT_WAIT, + mode: InterfaceMode::Full, + } + } +} + +#[derive(Debug, Clone)] +pub struct I2PClientConfig { + pub name: String, + pub sam_host: String, + pub sam_port: u16, + /// Peer I2P destination (base64). + pub peer_destination: String, + /// Reconnect attempt cap; `None` = unlimited. + pub max_reconnect_tries: Option, + pub reconnect_delay: u64, + pub mode: InterfaceMode, +} + +impl I2PClientConfig { + pub fn new(name: &str, peer_dest: &str) -> Self { + Self { + name: name.to_string(), + sam_host: DEFAULT_SAM_ADDRESS.to_string(), + sam_port: DEFAULT_SAM_PORT, + peer_destination: peer_dest.to_string(), + max_reconnect_tries: None, + reconnect_delay: RECONNECT_WAIT, + mode: InterfaceMode::Full, + } + } +} + +/// Connect via SAM streaming session, run HDLC-framed I/O; exponential reconnect. +pub async fn spawn_i2p_client( + config: I2PClientConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let online = Arc::new(AtomicBool::new(false)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let (tx, rx) = mpsc::channel::(256); + let name = config.name.clone(); + let mode = config.mode; + + // rx survives reconnects; per-connection writer leases it each cycle. + let rx = Arc::new(tokio::sync::Mutex::new(rx)); + + let online_task = online.clone(); + let task_rxb = shared_rxb.clone(); + let task_txb = shared_txb.clone(); + + let read_task = tokio::spawn(async move { + let mut tries: usize = 0; + let mut backoff = config.reconnect_delay; + + loop { + let session_id = generate_session_id(); + + let session_stream = match connect_to_sam(&config.sam_host, config.sam_port).await { + Ok(s) => s, + Err(e) => { + tracing::warn!( + name = %config.name, + error = %e, + "I2P client: failed to connect to SAM bridge" + ); + if check_max_tries(&config.max_reconnect_tries, &mut tries) { + tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached"); + return; + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + let (session_reader, mut session_writer) = session_stream.into_split(); + let mut session_buf_reader = BufReader::new(session_reader); + + if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await { + tracing::warn!( + name = %config.name, + error = %e, + "I2P client: SAM HELLO failed" + ); + if check_max_tries(&config.max_reconnect_tries, &mut tries) { + return; + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + + let _our_dest = match sam_session_create( + &mut session_writer, + &mut session_buf_reader, + &session_id, + None, + ) + .await + { + Ok(d) => { + tracing::info!( + name = %config.name, + session = %session_id, + "I2P client: session created" + ); + d + } + Err(e) => { + tracing::warn!( + name = %config.name, + error = %e, + "I2P client: SESSION CREATE failed" + ); + if check_max_tries(&config.max_reconnect_tries, &mut tries) { + return; + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + // SAM forbids running the data stream on the session socket. + let stream_conn = match connect_to_sam(&config.sam_host, config.sam_port).await { + Ok(s) => s, + Err(e) => { + tracing::warn!( + name = %config.name, + error = %e, + "I2P client: failed to open stream connection to SAM" + ); + if check_max_tries(&config.max_reconnect_tries, &mut tries) { + return; + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + let (stream_reader, mut stream_writer) = stream_conn.into_split(); + let mut stream_buf_reader = BufReader::new(stream_reader); + + if let Err(e) = sam_hello(&mut stream_writer, &mut stream_buf_reader).await { + tracing::warn!( + name = %config.name, + error = %e, + "I2P client: SAM HELLO on stream socket failed" + ); + if check_max_tries(&config.max_reconnect_tries, &mut tries) { + return; + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + + if let Err(e) = sam_stream_connect( + &mut stream_writer, + &mut stream_buf_reader, + &session_id, + &config.peer_destination, + ) + .await + { + tracing::warn!( + name = %config.name, + peer = %config.peer_destination, + error = %e, + "I2P client: STREAM CONNECT failed" + ); + if check_max_tries(&config.max_reconnect_tries, &mut tries) { + return; + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + + tracing::info!( + name = %config.name, + peer = %config.peer_destination, + "I2P client: stream connected" + ); + + online_task.store(true, Ordering::SeqCst); + tries = 0; + backoff = config.reconnect_delay; + + // BufReader may have prefetched past the handshake; flush its tail first. + let buffered = stream_buf_reader.buffer().to_vec(); + let raw_reader = stream_buf_reader.into_inner(); + + let (conn_tx, mut conn_rx) = mpsc::channel::(256); + let online_w = online_task.clone(); + let txb_w = task_txb.clone(); + let write_handle = tokio::spawn(async move { + while let Some(data) = conn_rx.recv().await { + if !online_w.load(Ordering::SeqCst) { + break; + } + let framed = hdlc::frame(&data); + txb_w.fetch_add(framed.len() as u64, Ordering::Relaxed); + if let Err(e) = stream_writer.write_all(&framed).await { + tracing::warn!(error = %e, "I2P client: write error"); + break; + } + } + online_w.store(false, Ordering::SeqCst); + }); + + let rx_ref = rx.clone(); + let fwd_handle = tokio::spawn(async move { + let mut guard = rx_ref.lock().await; + while let Some(data) = guard.recv().await { + if conn_tx.send(data).await.is_err() { + break; + } + } + }); + + let online_r = online_task.clone(); + let rxb_r = task_rxb.clone(); + i2p_read_loop(raw_reader, &buffered, id, &transport_tx, &online_r, &rxb_r).await; + + online_task.store(false, Ordering::SeqCst); + + fwd_handle.abort(); + let _ = fwd_handle.await; + 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; + } + } + tracing::info!( + name = %config.name, + delay = backoff, + "I2P client: reconnecting" + ); + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: BITRATE_GUESS, + mtu: HW_MTU, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +/// Accept SAM streams; each becomes a sub-interface via `handle_tx`. Session +/// is recreated if the control socket drops. +pub async fn spawn_i2p_server( + config: I2PServerConfig, + id_gen: Arc, + transport_tx: mpsc::Sender, + handle_tx: mpsc::Sender, +) -> Result { + let online = Arc::new(AtomicBool::new(false)); + let name = config.name.clone(); + let mode = config.mode; + + // Server handle tx is unused; per-peer handles carry traffic. + let (tx, _rx) = mpsc::channel::(1); + + let online_task = online.clone(); + + let read_task = tokio::spawn(async move { + loop { + let session_id = generate_session_id(); + + let session_stream = match connect_to_sam(&config.sam_host, config.sam_port).await { + Ok(s) => s, + Err(e) => { + tracing::warn!( + name = %config.name, + error = %e, + "I2P server: failed to connect to SAM bridge" + ); + tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)) + .await; + continue; + } + }; + + let (session_reader, mut session_writer) = session_stream.into_split(); + let mut session_buf_reader = BufReader::new(session_reader); + + if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await { + tracing::warn!(name = %config.name, error = %e, "I2P server: SAM HELLO failed"); + tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)).await; + continue; + } + + let private_key = config.keyfile.as_deref(); + let our_dest = match sam_session_create( + &mut session_writer, + &mut session_buf_reader, + &session_id, + private_key, + ) + .await + { + Ok(d) => d, + Err(e) => { + tracing::warn!( + name = %config.name, + error = %e, + "I2P server: SESSION CREATE failed" + ); + tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)) + .await; + continue; + } + }; + + tracing::info!( + name = %config.name, + session = %session_id, + dest_len = our_dest.len(), + "I2P server: session created, accepting streams" + ); + online_task.store(true, Ordering::SeqCst); + + // Each STREAM ACCEPT needs its own SAM TCP connection. + loop { + let accept_conn = match connect_to_sam(&config.sam_host, config.sam_port).await { + Ok(s) => s, + Err(e) => { + tracing::warn!( + name = %config.name, + error = %e, + "I2P server: failed to open accept connection" + ); + // Session likely died; break to recreate. + break; + } + }; + + let (accept_reader, mut accept_writer) = accept_conn.into_split(); + let mut accept_buf_reader = BufReader::new(accept_reader); + + if let Err(e) = sam_hello(&mut accept_writer, &mut accept_buf_reader).await { + tracing::warn!( + name = %config.name, + error = %e, + "I2P server: SAM HELLO on accept socket failed" + ); + break; + } + + let peer_dest = match sam_stream_accept( + &mut accept_writer, + &mut accept_buf_reader, + &session_id, + ) + .await + { + Ok(d) => d, + Err(e) => { + tracing::warn!( + name = %config.name, + error = %e, + "I2P server: STREAM ACCEPT failed" + ); + break; + } + }; + + let client_id = id_gen.fetch_add(1, Ordering::SeqCst); + let truncated_dest = if peer_dest.len() > 16 { + format!("{}...", &peer_dest[..16]) + } else { + peer_dest.clone() + }; + let client_name = format!("{}/peer_{}", config.name, truncated_dest); + + tracing::info!( + name = %client_name, + client_id, + "I2P server: accepted incoming stream" + ); + + let buffered = accept_buf_reader.buffer().to_vec(); + let raw_reader = accept_buf_reader.into_inner(); + + 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::(256); + + let c_online_w = c_online.clone(); + let c_txb_w = c_txb.clone(); + tokio::spawn(async move { + let mut rx = c_rx; + while let Some(data) = rx.recv().await { + let framed = hdlc::frame(&data); + c_txb_w.fetch_add(framed.len() as u64, Ordering::Relaxed); + if let Err(e) = accept_writer.write_all(&framed).await { + tracing::warn!(error = %e, "I2P server peer: write error"); + break; + } + } + c_online_w.store(false, Ordering::SeqCst); + }); + + let c_online_r = c_online.clone(); + let c_rxb_r = c_rxb.clone(); + let transport_tx2 = transport_tx.clone(); + let peer_name = client_name.clone(); + let c_read_task = tokio::spawn(async move { + i2p_read_loop( + raw_reader, + &buffered, + client_id, + &transport_tx2, + &c_online_r, + &c_rxb_r, + ) + .await; + tracing::info!(name = %peer_name, "I2P server: peer disconnected"); + }); + + let handle = InterfaceHandle { + id: client_id, + name: client_name, + mode: config.mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: BITRATE_GUESS, + mtu: HW_MTU, + online: c_online, + rxb: Some(c_rxb), + txb: Some(c_txb), + tx: c_tx, + read_task: c_read_task, + }; + + if handle_tx.send(handle).await.is_err() { + tracing::warn!("I2P server: handle registry channel closed"); + online_task.store(false, Ordering::SeqCst); + return; + } + } + + online_task.store(false, Ordering::SeqCst); + tracing::info!( + name = %config.name, + delay = config.reconnect_delay, + "I2P server: session lost, recreating" + ); + tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)).await; + } + }); + + Ok(InterfaceHandle { + id: 0, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: false, + forward: false, + repeat: false, + }, + bitrate: BITRATE_GUESS, + mtu: HW_MTU, + online, + rxb: Some(Arc::new(AtomicU64::new(0))), + txb: Some(Arc::new(AtomicU64::new(0))), + tx, + read_task, + }) +} + +/// HDLC read loop. +/// +/// `initial_data` seeds the deframer with bytes the `BufReader` prefetched +/// past the SAM handshake replies before the raw reader was taken. +async fn i2p_read_loop( + mut reader: tokio::net::tcp::OwnedReadHalf, + initial_data: &[u8], + interface_id: InterfaceId, + transport_tx: &mpsc::Sender, + online: &AtomicBool, + rxb: &AtomicU64, +) { + let mut deframer = hdlc::HdlcDeframer::new(); + let mut buf = [0u8; 4096]; + + if !initial_data.is_empty() { + rxb.fetch_add(initial_data.len() as u64, Ordering::Relaxed); + for frame in deframer.feed(initial_data) { + 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, "I2P: transport channel closed"); + online.store(false, Ordering::SeqCst); + return; + } + } + } + + loop { + match reader.read(&mut buf).await { + Ok(0) => { + tracing::info!(interface_id, "I2P read: EOF"); + break; + } + Ok(n) => { + rxb.fetch_add(n as u64, Ordering::Relaxed); + for frame in deframer.feed(&buf[..n]) { + if frame.is_empty() { + continue; + } + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(interface_id, "I2P: transport channel closed"); + online.store(false, Ordering::SeqCst); + return; + } + } + } + Err(e) => { + tracing::warn!(interface_id, error = %e, "I2P read error"); + break; + } + } + } + online.store(false, Ordering::SeqCst); +} + +/// Increments `tries` (when bounded) and returns `true` if the cap was hit. +fn check_max_tries(max: &Option, tries: &mut usize) -> bool { + if let Some(limit) = max { + *tries += 1; + *tries >= *limit + } else { + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_i2p_client_config() { + let cfg = I2PClientConfig::new("i2p0", "ABCDEF1234.b32.i2p"); + assert_eq!(cfg.sam_host, DEFAULT_SAM_ADDRESS); + assert_eq!(cfg.sam_port, DEFAULT_SAM_PORT); + assert_eq!(cfg.peer_destination, "ABCDEF1234.b32.i2p"); + assert_eq!(cfg.reconnect_delay, RECONNECT_WAIT); + assert!(cfg.max_reconnect_tries.is_none()); + } + + #[test] + fn test_i2p_server_config() { + let cfg = I2PServerConfig::new("i2p-server"); + assert_eq!(cfg.sam_port, DEFAULT_SAM_PORT); + assert!(cfg.keyfile.is_none()); + assert_eq!(cfg.reconnect_delay, RECONNECT_WAIT); + } + + #[test] + fn test_constants() { + assert_eq!(BITRATE_GUESS, 256_000); + assert_eq!(HW_MTU, 1064); + assert_eq!(I2P_TCP_USER_TIMEOUT, 45); + assert_eq!(I2P_PROBE_AFTER, 10); + assert_eq!(I2P_PROBE_INTERVAL, 9); + assert_eq!(I2P_PROBES, 5); + assert_eq!(I2P_READ_TIMEOUT, 110); + assert_eq!(RECONNECT_WAIT, 15); + } + + #[test] + fn test_parse_sam_hello_reply_ok() { + let reply = "HELLO REPLY RESULT=OK VERSION=3.1"; + let pairs = parse_sam_reply(reply); + + assert!(sam_reply_has_token(&pairs, "HELLO")); + assert!(sam_reply_has_token(&pairs, "REPLY")); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("OK")); + assert_eq!(sam_reply_get(&pairs, "VERSION"), Some("3.1")); + } + + #[test] + fn test_parse_sam_hello_reply_noversion() { + let reply = "HELLO REPLY RESULT=NOVERSION"; + let pairs = parse_sam_reply(reply); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("NOVERSION")); + } + + #[test] + fn test_parse_sam_session_reply() { + let dest = "AAAA1234BBBB5678=="; + let reply = format!("SESSION STATUS RESULT=OK DESTINATION={}", dest); + let pairs = parse_sam_reply(&reply); + + assert!(sam_reply_has_token(&pairs, "SESSION")); + assert!(sam_reply_has_token(&pairs, "STATUS")); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("OK")); + assert_eq!(sam_reply_get(&pairs, "DESTINATION"), Some(dest)); + } + + #[test] + fn test_parse_sam_session_error() { + let reply = "SESSION STATUS RESULT=DUPLICATED_ID MESSAGE=session already exists"; + let pairs = parse_sam_reply(reply); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("DUPLICATED_ID")); + // Whitespace tokenisation stops MESSAGE at the first space; the + // machine-readable error code lives in RESULT. + assert_eq!(sam_reply_get(&pairs, "MESSAGE"), Some("session")); + } + + #[test] + fn test_parse_sam_stream_reply() { + let reply = "STREAM STATUS RESULT=OK"; + let pairs = parse_sam_reply(reply); + + assert!(sam_reply_has_token(&pairs, "STREAM")); + assert!(sam_reply_has_token(&pairs, "STATUS")); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("OK")); + } + + #[test] + fn test_parse_sam_stream_cant_reach() { + let reply = "STREAM STATUS RESULT=CANT_REACH_PEER MESSAGE=unreachable"; + let pairs = parse_sam_reply(reply); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("CANT_REACH_PEER")); + } + + #[test] + fn test_parse_empty_reply() { + let pairs = parse_sam_reply(""); + assert!(pairs.is_empty()); + } + + #[test] + fn test_sam_reply_get_missing_key() { + let pairs = parse_sam_reply("HELLO REPLY RESULT=OK"); + assert_eq!(sam_reply_get(&pairs, "MISSING"), None); + } + + #[test] + fn test_sam_reply_has_token() { + let pairs = parse_sam_reply("HELLO REPLY RESULT=OK"); + assert!(sam_reply_has_token(&pairs, "HELLO")); + assert!(sam_reply_has_token(&pairs, "REPLY")); + assert!(!sam_reply_has_token(&pairs, "RESULT")); + assert!(!sam_reply_has_token(&pairs, "NONEXISTENT")); + } + + #[test] + fn test_generate_session_id() { + let id1 = generate_session_id(); + let id2 = generate_session_id(); + + assert!(id1.starts_with("reticulum_")); + assert!(id2.starts_with("reticulum_")); + assert_ne!(id1, id2); + assert_eq!(id1.len(), 26); + } + + #[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); + } + + #[test] + fn test_check_max_tries_limited() { + let max = Some(3); + let mut tries = 0; + + 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_sam_error_display() { + let e = SamError::HandshakeFailed("test error".to_string()); + assert_eq!(format!("{}", e), "SAM handshake failed: test error"); + + let e = SamError::SessionFailed("dup id".to_string()); + assert_eq!(format!("{}", e), "SAM session creation failed: dup id"); + + let e = SamError::StreamFailed("cant reach".to_string()); + assert_eq!(format!("{}", e), "SAM stream connect failed: cant reach"); + + let e = SamError::AcceptFailed("timeout".to_string()); + assert_eq!(format!("{}", e), "SAM stream accept failed: timeout"); + + let e = SamError::UnexpectedReply("garbage".to_string()); + assert_eq!(format!("{}", e), "unexpected SAM reply: garbage"); + } + + #[test] + fn test_full_sam_handshake_sequence_parsing() { + let hello_reply = "HELLO REPLY RESULT=OK VERSION=3.1"; + let pairs = parse_sam_reply(hello_reply); + assert!(sam_reply_has_token(&pairs, "HELLO")); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("OK")); + assert_eq!(sam_reply_get(&pairs, "VERSION"), Some("3.1")); + + let long_dest = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOP=="; + let session_reply = format!("SESSION STATUS RESULT=OK DESTINATION={}", long_dest); + let pairs = parse_sam_reply(&session_reply); + assert!(sam_reply_has_token(&pairs, "SESSION")); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("OK")); + assert_eq!(sam_reply_get(&pairs, "DESTINATION"), Some(long_dest)); + + let stream_reply = "STREAM STATUS RESULT=OK"; + let pairs = parse_sam_reply(stream_reply); + assert!(sam_reply_has_token(&pairs, "STREAM")); + assert_eq!(sam_reply_get(&pairs, "RESULT"), Some("OK")); + } +} diff --git a/crates/rns-interface/src/kiss.rs b/crates/rns-interface/src/kiss.rs new file mode 100644 index 0000000..0ce22fc --- /dev/null +++ b/crates/rns-interface/src/kiss.rs @@ -0,0 +1,483 @@ +//! KISS TNC framing — used by KISS, AX.25-KISS, RNode, RNodeMulti, TCP/I2P. +//! Wire: `[FEND][CMD][escaped_payload][FEND]`. + +pub const FEND: u8 = 0xC0; +pub const FESC: u8 = 0xDB; +pub const TFEND: u8 = 0xDC; +pub const TFESC: u8 = 0xDD; + +pub const CMD_DATA: u8 = 0x00; +pub const CMD_TXDELAY: u8 = 0x01; +pub const CMD_P: u8 = 0x02; +pub const CMD_SLOTTIME: u8 = 0x03; +pub const CMD_TXTAIL: u8 = 0x04; +pub const CMD_FULLDUPLEX: u8 = 0x05; +pub const CMD_SETHARDWARE: u8 = 0x06; +pub const CMD_READY: u8 = 0x0F; +pub const CMD_RETURN: u8 = 0xFF; +pub const CMD_UNKNOWN: u8 = 0xFE; + +/// High nibble of command byte = TNC port. +pub const PORT_MASK: u8 = 0xF0; +/// Low nibble of command byte = command. +pub const CMD_MASK: u8 = 0x0F; + +/// Sized for full resource transfers on TCP/Local MTUs. +const MAX_FRAME_SIZE: usize = 524288; + +/// Pre-allocated capacity for the deframer accumulator. +const DEFRAME_BUF_CAPACITY: usize = 2048; + +/// Append the KISS-escape-encoded form of `data` to `out`. +pub fn escape_into(data: &[u8], out: &mut Vec) { + let mut i = 0; + while i < data.len() { + match data[i..].iter().position(|&b| b == FESC || b == FEND) { + Some(rel) => { + let hit = i + rel; + out.extend_from_slice(&data[i..hit]); + out.push(FESC); + out.push(if data[hit] == FEND { TFEND } else { TFESC }); + i = hit + 1; + } + None => { + out.extend_from_slice(&data[i..]); + return; + } + } + } +} + +/// Append the unescaped form of `data` to `out`. Unknown escape sequences and +/// a trailing lone FESC byte are passed through unchanged — matching the +/// previous implementation byte-for-byte. +pub fn unescape_into(data: &[u8], out: &mut Vec) { + let mut i = 0; + while i < data.len() { + match data[i..].iter().position(|&b| b == FESC) { + Some(rel) => { + let hit = i + rel; + out.extend_from_slice(&data[i..hit]); + if hit + 1 < data.len() { + match data[hit + 1] { + TFEND => out.push(FEND), + TFESC => out.push(FESC), + other => { + out.push(FESC); + out.push(other); + } + } + i = hit + 2; + } else { + out.push(FESC); + return; + } + } + None => { + out.extend_from_slice(&data[i..]); + return; + } + } + } +} + +/// Append a complete KISS data-frame for `data` to `out`. +pub fn frame_into(data: &[u8], out: &mut Vec) { + out.push(FEND); + out.push(CMD_DATA); + escape_into(data, out); + out.push(FEND); +} + +/// Append a KISS frame with an explicit command byte to `out`. +pub fn frame_with_command_into(cmd: u8, data: &[u8], out: &mut Vec) { + out.push(FEND); + out.push(cmd); + escape_into(data, out); + out.push(FEND); +} + +pub fn escape(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + data.len() / 8); + escape_into(data, &mut out); + out +} + +pub fn unescape(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len()); + unescape_into(data, &mut out); + out +} + +pub fn frame(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + data.len() / 8 + 3); + frame_into(data, &mut out); + out +} + +pub fn frame_with_command(cmd: u8, data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + data.len() / 8 + 3); + frame_with_command_into(cmd, data, &mut out); + out +} + +pub struct KissDeframer { + buffer: Vec, + in_frame: bool, + command: u8, + /// Reusable scratch for unescape output. + unescape_scratch: Vec, +} + +impl KissDeframer { + pub fn new() -> Self { + Self { + buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY), + in_frame: false, + command: CMD_UNKNOWN, + unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY), + } + } + + /// Returns complete frames as (command, data) pairs. + pub fn feed(&mut self, data: &[u8]) -> Vec<(u8, Vec)> { + let mut frames = Vec::new(); + let mut i = 0; + while i < data.len() { + match data[i..].iter().position(|&b| b == FEND) { + Some(rel) => { + let hit = i + rel; + if self.in_frame { + self.append_in_frame(&data[i..hit]); + if !self.buffer.is_empty() { + self.unescape_scratch.clear(); + unescape_into(&self.buffer, &mut self.unescape_scratch); + let frame_data = std::mem::replace( + &mut self.unescape_scratch, + Vec::with_capacity(DEFRAME_BUF_CAPACITY), + ); + frames.push((self.command & CMD_MASK, frame_data)); + } + self.buffer.clear(); + } + self.in_frame = true; + self.command = CMD_UNKNOWN; + i = hit + 1; + } + None => { + if self.in_frame { + self.append_in_frame(&data[i..]); + } + return frames; + } + } + } + frames + } + + /// Append `chunk` to the in-frame buffer. The first byte after a FEND is + /// the command byte (consumed separately); subsequent bytes are payload + /// up to `MAX_FRAME_SIZE`. Overflow drops the in-progress frame and waits + /// for the next FEND to resync — matching the previous byte-loop. + fn append_in_frame(&mut self, chunk: &[u8]) { + let mut chunk = chunk; + if self.command == CMD_UNKNOWN { + if let Some((&first, rest)) = chunk.split_first() { + self.command = first; + chunk = rest; + } else { + return; + } + } + if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE { + self.buffer.clear(); + self.in_frame = false; + self.command = CMD_UNKNOWN; + return; + } + self.buffer.extend_from_slice(chunk); + } + + pub fn reset(&mut self) { + self.buffer.clear(); + self.in_frame = false; + self.command = CMD_UNKNOWN; + } +} + +impl Default for KissDeframer { + fn default() -> Self { + Self::new() + } +} + +/// Extended-KISS deframer that preserves the full command byte. +/// +/// Classic KISS uses the high nibble as a TNC port and the low nibble as the +/// command, so [`KissDeframer`] returns `command & CMD_MASK`. RNode admin +/// commands use the complete byte (`0x50`, `0x62`, `0x84`, ...), so they must +/// use this deframer instead. +pub struct RawKissDeframer { + buffer: Vec, + in_frame: bool, + command: u8, + unescape_scratch: Vec, +} + +impl RawKissDeframer { + pub fn new() -> Self { + Self { + buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY), + in_frame: false, + command: CMD_UNKNOWN, + unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY), + } + } + + /// Returns complete frames as (full_command, data) pairs. + pub fn feed(&mut self, data: &[u8]) -> Vec<(u8, Vec)> { + let mut frames = Vec::new(); + let mut i = 0; + while i < data.len() { + match data[i..].iter().position(|&b| b == FEND) { + Some(rel) => { + let hit = i + rel; + if self.in_frame { + self.append_in_frame(&data[i..hit]); + if !self.buffer.is_empty() { + self.unescape_scratch.clear(); + unescape_into(&self.buffer, &mut self.unescape_scratch); + let frame_data = std::mem::replace( + &mut self.unescape_scratch, + Vec::with_capacity(DEFRAME_BUF_CAPACITY), + ); + frames.push((self.command, frame_data)); + } + self.buffer.clear(); + } + self.in_frame = true; + self.command = CMD_UNKNOWN; + i = hit + 1; + } + None => { + if self.in_frame { + self.append_in_frame(&data[i..]); + } + return frames; + } + } + } + frames + } + + fn append_in_frame(&mut self, chunk: &[u8]) { + let mut chunk = chunk; + if self.command == CMD_UNKNOWN { + if let Some((&first, rest)) = chunk.split_first() { + self.command = first; + chunk = rest; + } else { + return; + } + } + if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE { + self.buffer.clear(); + self.in_frame = false; + self.command = CMD_UNKNOWN; + return; + } + self.buffer.extend_from_slice(chunk); + } + + pub fn reset(&mut self) { + self.buffer.clear(); + self.in_frame = false; + self.command = CMD_UNKNOWN; + } +} + +impl Default for RawKissDeframer { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_escape_unescape_roundtrip() { + let data = vec![0x00, FEND, FESC, 0xFF, FEND, FESC, 0x42]; + let escaped = escape(&data); + let unescaped = unescape(&escaped); + assert_eq!(unescaped, data); + } + + #[test] + fn test_escape_no_special_bytes() { + let data = b"hello"; + let escaped = escape(data); + assert_eq!(escaped, data); + } + + #[test] + fn test_escape_fend() { + let data = vec![FEND]; + let escaped = escape(&data); + assert_eq!(escaped, vec![FESC, TFEND]); + } + + #[test] + fn test_escape_fesc() { + let data = vec![FESC]; + let escaped = escape(&data); + assert_eq!(escaped, vec![FESC, TFESC]); + } + + #[test] + fn test_frame_and_deframe() { + let data = b"test kiss data"; + let framed = frame(data); + + let mut deframer = KissDeframer::new(); + let frames = deframer.feed(&framed); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].0, CMD_DATA); + assert_eq!(frames[0].1, data); + } + + #[test] + fn test_deframer_multiple_frames() { + let f1 = frame(b"first"); + let f2 = frame(b"second"); + + let mut combined = f1; + combined.extend_from_slice(&f2); + + let mut deframer = KissDeframer::new(); + let frames = deframer.feed(&combined); + assert_eq!(frames.len(), 2); + assert_eq!(frames[0].1, b"first"); + assert_eq!(frames[1].1, b"second"); + } + + #[test] + fn test_port_nibble_stripped() { + // High nibble = TNC port, must be masked. + let mut framed = Vec::new(); + framed.push(FEND); + framed.push(0x10 | CMD_DATA); + framed.extend_from_slice(b"data"); + framed.push(FEND); + + let mut deframer = KissDeframer::new(); + let frames = deframer.feed(&framed); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].0, CMD_DATA); + } + + #[test] + fn test_raw_deframer_preserves_extended_commands() { + let mut deframer = RawKissDeframer::new(); + let mut bytes = Vec::new(); + frame_with_command_into(0x50, &[0x00], &mut bytes); + frame_with_command_into(0x62, &[0x00, 0x01, 0xE2, 0x40], &mut bytes); + frame_with_command_into(0x84, &[192, 168, 1, 10], &mut bytes); + + let frames = deframer.feed(&bytes); + assert_eq!(frames.len(), 3); + assert_eq!(frames[0].0, 0x50); + assert_eq!(frames[1].0, 0x62); + assert_eq!(frames[1].1, vec![0x00, 0x01, 0xE2, 0x40]); + assert_eq!(frames[2].0, 0x84); + } + + #[test] + fn test_deframer_streaming() { + let framed = frame(b"stream"); + let mid = framed.len() / 2; + + let mut deframer = KissDeframer::new(); + let f1 = deframer.feed(&framed[..mid]); + assert!(f1.is_empty()); + + let f2 = deframer.feed(&framed[mid..]); + assert_eq!(f2.len(), 1); + assert_eq!(f2[0].1, b"stream"); + } + + #[test] + fn test_frame_with_command() { + let data = b"hardware config"; + let framed = frame_with_command(CMD_SETHARDWARE, data); + + let mut deframer = KissDeframer::new(); + let frames = deframer.feed(&framed); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].0, CMD_SETHARDWARE); + assert_eq!(frames[0].1, data); + } + + #[test] + fn test_into_variants_match_allocating() { + let inputs: &[&[u8]] = &[ + b"", + b"plain", + &[FEND, FESC, 0x00, 0xFF, FEND], + &[FESC, FESC, FESC], + &[0x00; 1024], + ]; + for data in inputs { + let mut buf = Vec::new(); + escape_into(data, &mut buf); + assert_eq!(buf, escape(data)); + + let escaped = escape(data); + let mut buf2 = Vec::new(); + unescape_into(&escaped, &mut buf2); + assert_eq!(buf2, unescape(&escaped)); + + let mut buf3 = Vec::new(); + frame_into(data, &mut buf3); + assert_eq!(buf3, frame(data)); + + let mut buf4 = Vec::new(); + frame_with_command_into(CMD_SETHARDWARE, data, &mut buf4); + assert_eq!(buf4, frame_with_command(CMD_SETHARDWARE, data)); + } + } + + #[test] + fn test_deframer_streaming_command_byte_boundary() { + // Command byte arrives in a separate feed() chunk from the payload. + let framed = frame(b"split"); + let mut deframer = KissDeframer::new(); + // Feed just [FEND] first — no command byte yet. + let f1 = deframer.feed(&framed[..1]); + assert!(f1.is_empty()); + // Feed just the command byte — still no full frame. + let f2 = deframer.feed(&framed[1..2]); + assert!(f2.is_empty()); + // Feed the payload + closing FEND. + let f3 = deframer.feed(&framed[2..]); + assert_eq!(f3.len(), 1); + assert_eq!(f3[0].0, CMD_DATA); + assert_eq!(f3[0].1, b"split"); + } + + #[test] + fn test_deframer_oversized_drops_then_resyncs() { + let mut deframer = KissDeframer::new(); + let mut oversized = vec![FEND, CMD_DATA]; + oversized.extend(std::iter::repeat_n(0x55, MAX_FRAME_SIZE + 100)); + oversized.push(FEND); + let frames = deframer.feed(&oversized); + assert!(frames.is_empty()); + + let small = frame(b"after-overflow"); + let frames = deframer.feed(&small); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].1, b"after-overflow"); + } +} diff --git a/crates/rns-interface/src/kiss_iface.rs b/crates/rns-interface/src/kiss_iface.rs new file mode 100644 index 0000000..0b6aefb --- /dev/null +++ b/crates/rns-interface/src/kiss_iface.rs @@ -0,0 +1,292 @@ +//! Serial port + KISS framing; CMD_DATA + CMD_READY flow control. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use bytes::Bytes; +use tokio::sync::mpsc; + +use crate::kiss; +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +const KISS_READ_TIMEOUT_MS: u64 = 100; + +#[derive(Debug, Clone)] +pub struct KissInterfaceConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + pub data_bits: serialport::DataBits, + pub parity: serialport::Parity, + pub stop_bits: serialport::StopBits, + pub mode: InterfaceMode, + pub slottime: Option, + pub persistence: Option, + pub txdelay: Option, + pub txtail: Option, + /// Honour CMD_READY from TNC. + pub flow_control: bool, +} + +impl KissInterfaceConfig { + pub fn new(name: &str, port: &str, baud: u32) -> Self { + Self { + name: name.to_string(), + port: port.to_string(), + baud_rate: baud, + data_bits: serialport::DataBits::Eight, + parity: serialport::Parity::None, + stop_bits: serialport::StopBits::One, + mode: InterfaceMode::Full, + slottime: None, + persistence: None, + txdelay: None, + txtail: None, + flow_control: false, + } + } +} + +pub async fn spawn_kiss_interface( + config: KissInterfaceConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let port = serialport::new(&config.port, config.baud_rate) + .data_bits(config.data_bits) + .parity(config.parity) + .stop_bits(config.stop_bits) + .timeout(Duration::from_millis(KISS_READ_TIMEOUT_MS)) + .open() + .map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("kiss serial open: {}", e)) + })?; + + tracing::info!( + name = %config.name, + port = %config.port, + baud = config.baud_rate, + "KISS interface opened" + ); + + let online = Arc::new(AtomicBool::new(true)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let (tx, mut rx) = mpsc::channel::(256); + let name = config.name.clone(); + let mode = config.mode; + let flow_control = config.flow_control; + + let port_write = port + .try_clone() + .map_err(|e| crate::traits::InterfaceError::SendFailed(format!("kiss clone: {}", e)))?; + + // Push TNC tuning before main loops so they take effect before first frame. + { + let mut init_port = port_write.try_clone().map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("kiss init clone: {}", e)) + })?; + let mut init_frames = Vec::with_capacity(16); + if let Some(v) = config.txdelay { + kiss::frame_with_command_into(kiss::CMD_TXDELAY, &[v], &mut init_frames); + } + if let Some(v) = config.persistence { + kiss::frame_with_command_into(kiss::CMD_P, &[v], &mut init_frames); + } + if let Some(v) = config.slottime { + kiss::frame_with_command_into(kiss::CMD_SLOTTIME, &[v], &mut init_frames); + } + if let Some(v) = config.txtail { + kiss::frame_with_command_into(kiss::CMD_TXTAIL, &[v], &mut init_frames); + } + if !init_frames.is_empty() { + use std::io::Write; + let _ = init_port.write_all(&init_frames); + let _ = init_port.flush(); + } + } + + let ready = Arc::new(AtomicBool::new(true)); + + let online_w = online.clone(); + let ready_w = ready.clone(); + let txb_w = shared_txb.clone(); + tokio::spawn(async move { + let mut port_w = port_write; + while let Some(data) = rx.recv().await { + txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed); + // Flow control: bounded wait so a stuck TNC can't hang transmit. + if flow_control { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while !ready_w.load(Ordering::SeqCst) { + if tokio::time::Instant::now() >= deadline { + tracing::warn!("KISS flow control timeout, proceeding anyway"); + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + if !online_w.load(Ordering::SeqCst) { + return; + } + } + } + let framed = kiss::frame(&data); + let online_ref = online_w.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::io::Write; + port_w.write_all(&framed)?; + port_w.flush()?; + Ok::<_, std::io::Error>(port_w) + }) + .await; + match result { + Ok(Ok(p)) => { + port_w = p; + } + Ok(Err(e)) => { + tracing::warn!(error = %e, "KISS write error"); + online_ref.store(false, Ordering::SeqCst); + break; + } + Err(e) => { + tracing::warn!(error = %e, "KISS write task panicked"); + break; + } + } + } + }); + + let online_r = online.clone(); + let ready_r = ready; + let rxb_r = shared_rxb.clone(); + let read_task = tokio::spawn(async move { + let mut port_r = port; + let mut deframer = kiss::KissDeframer::new(); + let mut buf = [0u8; 1024]; + + loop { + if !online_r.load(Ordering::SeqCst) { + break; + } + let result = tokio::task::spawn_blocking(move || { + use std::io::Read; + match port_r.read(&mut buf) { + Ok(n) => Ok((port_r, buf, n)), + Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)), + Err(e) => Err((port_r, e)), + } + }) + .await; + + match result { + Ok(Ok((p, b, n))) => { + port_r = p; + buf = b; + if n > 0 { + rxb_r.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); + for (cmd, frame) in deframer.feed(&buf[..n]) { + match cmd { + kiss::CMD_DATA => { + if frame.is_empty() { + continue; + } + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id: id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + kiss::CMD_READY => { + // Nonzero = TNC ready to accept data. + let is_ready = frame.first().copied().unwrap_or(0) != 0; + ready_r.store(is_ready, Ordering::SeqCst); + tracing::debug!(id, ready = is_ready, "KISS flow control"); + } + _ => { + tracing::debug!(id, cmd, "ignoring KISS command"); + } + } + } + } + } + Ok(Err((_p, e))) => { + tracing::warn!(error = %e, "KISS read error"); + online_r.store(false, Ordering::SeqCst); + return; + } + Err(e) => { + tracing::warn!(error = %e, "KISS read task panicked"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: config.baud_rate as u64, + mtu: 564, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_kiss_iface_config() { + let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyUSB0", 9600); + assert_eq!(cfg.baud_rate, 9600); + assert!(!cfg.flow_control); + assert_eq!(cfg.mode, InterfaceMode::Full); + } + + #[test] + fn test_kiss_config_defaults() { + let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyUSB0", 9600); + assert_eq!(cfg.name, "kiss0"); + assert_eq!(cfg.port, "/dev/ttyUSB0"); + assert_eq!(cfg.data_bits, serialport::DataBits::Eight); + assert_eq!(cfg.parity, serialport::Parity::None); + assert_eq!(cfg.stop_bits, serialport::StopBits::One); + assert!(cfg.slottime.is_none()); + assert!(cfg.persistence.is_none()); + assert!(cfg.txdelay.is_none()); + assert!(cfg.txtail.is_none()); + } + + #[test] + fn test_kiss_config_custom() { + let cfg = KissInterfaceConfig::new("kiss1", "/dev/ttyACM0", 57600); + assert_eq!(cfg.port, "/dev/ttyACM0"); + assert_eq!(cfg.baud_rate, 57600); + } + + #[test] + fn test_kiss_config_mode() { + let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyS0", 9600); + assert_eq!(cfg.mode, InterfaceMode::Full); + } +} diff --git a/crates/rns-interface/src/lib.rs b/crates/rns-interface/src/lib.rs new file mode 100644 index 0000000..1521cde --- /dev/null +++ b/crates/rns-interface/src/lib.rs @@ -0,0 +1,39 @@ +//! Network interface implementations for Reticulum. +//! Each module provides a spawn function returning a Tokio task driving a +//! concrete transport; [`traits::Interface`] is the common abstraction. + +#[cfg(target_os = "android")] +pub mod android_usb; +pub mod auto; +pub mod ax25kiss; +pub mod backbone; +#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] +pub mod ble_central_apple; +#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] +pub mod ble_central_apple_connect; +#[cfg(feature = "ble")] +pub mod ble_central_lifecycle; +#[cfg(feature = "ble")] +pub mod ble_peer; +#[cfg(feature = "ble")] +pub mod ble_peer_lifecycle; +#[cfg(feature = "ble")] +pub mod ble_rnode; +pub mod hdlc; +pub mod i2p; +pub mod kiss; +#[cfg(feature = "serial")] +pub mod kiss_iface; +pub mod local; +pub mod pipe; +pub mod rnode; +pub mod rnode_admin; +#[cfg(feature = "serial")] +pub mod rnode_multi; +#[cfg(feature = "serial")] +pub mod serial; +pub mod socket_tuning; +pub mod tcp; +pub mod traits; +pub mod udp; +pub mod weave; diff --git a/crates/rns-interface/src/local.rs b/crates/rns-interface/src/local.rs new file mode 100644 index 0000000..da27c9a --- /dev/null +++ b/crates/rns-interface/src/local.rs @@ -0,0 +1,749 @@ +//! Shared-instance IPC. Unix domain sockets where available, TCP on +//! 127.0.0.1 as fallback. HDLC-framed. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use bytes::Bytes; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::sync::mpsc; + +use crate::hdlc; +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const LOCAL_MTU: u32 = 262_144; + +/// Default filesystem socket path for non-Linux fallback use. +pub const DEFAULT_SOCKET_PATH: &str = "/tmp/rns_reticulum.sock"; + +/// On Android `/tmp` isn't writable; falls back to caller's data directory. +pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf { + if cfg!(target_os = "android") + && let Some(dir) = data_dir + { + return dir.join("cache").join("rns_reticulum.sock"); + } + std::path::PathBuf::from(DEFAULT_SOCKET_PATH) +} + +pub const FALLBACK_TCP_PORT: u16 = 37428; + +pub fn socket_path_for(instance_name: &str) -> String { + format!("/tmp/rns_{}.sock", instance_name) +} + +pub fn python_shared_socket_name(instance_name: &str) -> String { + if cfg!(any(target_os = "linux", target_os = "android")) { + format!("\0rns/{instance_name}") + } else { + socket_path_for(instance_name) + } +} + +#[cfg(unix)] +fn is_abstract_socket_path(path: &str) -> bool { + path.as_bytes().first() == Some(&0) +} + +#[cfg(unix)] +fn display_socket_path(path: &str) -> String { + if is_abstract_socket_path(path) { + format!("\\0{}", &path[1..]) + } else { + path.to_string() + } +} + +#[derive(Debug, Clone)] +pub struct LocalServerConfig { + /// Unix socket path (ignored on non-Unix). + pub socket_path: String, + pub name: String, +} + +impl Default for LocalServerConfig { + fn default() -> Self { + Self { + socket_path: DEFAULT_SOCKET_PATH.to_string(), + name: "LocalServer".to_string(), + } + } +} + +#[derive(Debug, Clone)] +pub struct LocalClientConfig { + pub socket_path: String, + pub name: String, +} + +impl Default for LocalClientConfig { + fn default() -> Self { + Self { + socket_path: DEFAULT_SOCKET_PATH.to_string(), + name: "LocalClient".to_string(), + } + } +} + +async fn local_read_loop( + mut reader: R, + interface_id: InterfaceId, + transport_tx: mpsc::Sender, + online: Arc, + rxb: Arc, +) { + let mut buf = [0u8; 8192]; + let mut deframer = hdlc::HdlcDeframer::new(); + + loop { + match reader.read(&mut buf).await { + Ok(0) => { + tracing::info!(interface_id, "local read: EOF"); + break; + } + Ok(n) => { + rxb.fetch_add(n as u64, Ordering::Relaxed); + for frame in deframer.feed(&buf[..n]) { + if frame.is_empty() { + continue; + } + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(interface_id, "transport channel closed"); + online.store(false, Ordering::SeqCst); + return; + } + } + } + Err(e) => { + tracing::warn!(interface_id, error = %e, "local read error"); + break; + } + } + } + online.store(false, Ordering::SeqCst); +} + +async fn local_write_loop( + mut writer: W, + mut rx: mpsc::Receiver, + online: Arc, + txb: Arc, +) { + while let Some(data) = rx.recv().await { + let framed = hdlc::frame(&data); + if let Err(e) = writer.write_all(&framed).await { + tracing::warn!(error = %e, "local write error"); + break; + } + txb.fetch_add(framed.len() as u64, Ordering::Relaxed); + } + online.store(false, Ordering::SeqCst); +} + +#[cfg(unix)] +mod platform { + use super::*; + use tokio::net::{UnixListener, UnixStream}; + + fn bind_unix_listener(socket_path: &str) -> std::io::Result { + if let Some(abstract_name) = socket_path.strip_prefix('\0') { + return bind_abstract_unix_listener(abstract_name); + } + + let _ = std::fs::remove_file(socket_path); + UnixListener::bind(socket_path) + } + + async fn connect_unix_stream(socket_path: &str) -> std::io::Result { + if let Some(abstract_name) = socket_path.strip_prefix('\0') { + return connect_abstract_unix_stream(abstract_name); + } + + UnixStream::connect(socket_path).await + } + + #[cfg(any(target_os = "linux", target_os = "android"))] + fn bind_abstract_unix_listener(name: &str) -> std::io::Result { + use std::os::unix::net::{SocketAddr, UnixListener as StdUnixListener}; + + #[cfg(target_os = "android")] + use std::os::android::net::SocketAddrExt as _; + #[cfg(target_os = "linux")] + use std::os::linux::net::SocketAddrExt as _; + + let addr = SocketAddr::from_abstract_name(name.as_bytes())?; + let listener = StdUnixListener::bind_addr(&addr)?; + listener.set_nonblocking(true)?; + UnixListener::from_std(listener) + } + + #[cfg(not(any(target_os = "linux", target_os = "android")))] + fn bind_abstract_unix_listener(_name: &str) -> std::io::Result { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "abstract Unix sockets are only available on Linux/Android", + )) + } + + #[cfg(any(target_os = "linux", target_os = "android"))] + fn connect_abstract_unix_stream(name: &str) -> std::io::Result { + use std::os::unix::net::{SocketAddr, UnixStream as StdUnixStream}; + + #[cfg(target_os = "android")] + use std::os::android::net::SocketAddrExt as _; + #[cfg(target_os = "linux")] + use std::os::linux::net::SocketAddrExt as _; + + let addr = SocketAddr::from_abstract_name(name.as_bytes())?; + let stream = StdUnixStream::connect_addr(&addr)?; + stream.set_nonblocking(true)?; + UnixStream::from_std(stream) + } + + #[cfg(not(any(target_os = "linux", target_os = "android")))] + fn connect_abstract_unix_stream(_name: &str) -> std::io::Result { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "abstract Unix sockets are only available on Linux/Android", + )) + } + + pub async fn spawn_local_server_impl( + config: LocalServerConfig, + id_gen: Arc, + transport_tx: mpsc::Sender, + handle_tx: mpsc::Sender, + ) -> Result { + let listener = bind_unix_listener(&config.socket_path)?; + tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local server listening"); + + let online = Arc::new(AtomicBool::new(true)); + let online2 = online.clone(); + let name = config.name.clone(); + let (tx, _rx) = mpsc::channel::(1); + + let read_task = tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((stream, _addr)) => { + let client_id = id_gen.fetch_add(1, Ordering::SeqCst); + let client_name = format!("{}/client_{}", config.name, client_id); + tracing::info!(name = %client_name, "local client connected"); + + let c_online = Arc::new(AtomicBool::new(true)); + let c_rxb = Arc::new(AtomicU64::new(0)); + let c_txb = Arc::new(AtomicU64::new(0)); + let (c_tx, c_rx) = mpsc::channel::(256); + let (reader, writer) = stream.into_split(); + + let c_online2 = c_online.clone(); + let c_txb2 = c_txb.clone(); + tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2)); + + let c_online3 = c_online.clone(); + let c_rxb2 = c_rxb.clone(); + let transport_tx2 = transport_tx.clone(); + let dereg_tx = transport_tx.clone(); + let cname = client_name.clone(); + let read_handle = tokio::spawn(async move { + local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2) + .await; + tracing::info!(name = %cname, "local client disconnected"); + // Proactively notify so transport drops immediately. + let _ = dereg_tx + .send(TransportMessage::DeregisterInterface { id: client_id }) + .await; + }); + + let handle = InterfaceHandle { + id: client_id, + name: client_name, + mode: InterfaceMode::Full, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: 1_000_000_000, + mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU), + online: c_online, + rxb: Some(c_rxb), + txb: Some(c_txb), + tx: c_tx, + read_task: read_handle, + }; + if handle_tx.send(handle).await.is_err() { + tracing::warn!("local handle registry closed"); + break; + } + } + Err(e) => { + tracing::warn!(error = %e, "local accept error"); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + } + } + online2.store(false, Ordering::SeqCst); + }); + + let server_rxb = Arc::new(AtomicU64::new(0)); + let server_txb = Arc::new(AtomicU64::new(0)); + + Ok(InterfaceHandle { + id: 0, + name, + mode: InterfaceMode::Full, + direction: InterfaceDirection { + inbound: true, + outbound: false, + forward: false, + repeat: false, + }, + bitrate: 1_000_000_000, + mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU), + online, + rxb: Some(server_rxb), + txb: Some(server_txb), + tx, + read_task, + }) + } + + pub async fn spawn_local_client_impl( + config: LocalClientConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, + ) -> Result { + let stream = connect_unix_stream(&config.socket_path).await?; + tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected"); + + let online = Arc::new(AtomicBool::new(true)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let (tx, rx) = mpsc::channel::(256); + let (reader, writer) = stream.into_split(); + + let online_w = online.clone(); + let task_txb = shared_txb.clone(); + tokio::spawn(local_write_loop(writer, rx, online_w, task_txb)); + + let online_r = online.clone(); + let task_rxb = shared_rxb.clone(); + let name = config.name.clone(); + let read_task = tokio::spawn(async move { + local_read_loop(reader, id, transport_tx, online_r, task_rxb).await; + }); + + Ok(InterfaceHandle { + id, + name, + mode: InterfaceMode::Full, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: 1_000_000_000, + mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU), + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) + } +} + +#[cfg(not(unix))] +mod platform { + use super::*; + use tokio::net::{TcpListener, TcpStream}; + + fn fallback_tcp_addr(socket_path: &str) -> String { + if let Some(addr) = socket_path + .strip_prefix("tcp://") + .filter(|addr| !addr.is_empty()) + { + addr.to_string() + } else { + format!("127.0.0.1:{FALLBACK_TCP_PORT}") + } + } + + pub async fn spawn_local_server_impl( + config: LocalServerConfig, + id_gen: Arc, + transport_tx: mpsc::Sender, + handle_tx: mpsc::Sender, + ) -> Result { + let addr = fallback_tcp_addr(&config.socket_path); + let listener = TcpListener::bind(&addr).await?; + let local_addr = listener.local_addr()?; + tracing::info!(name = %config.name, addr = %local_addr, "local server (TCP fallback) listening"); + + let online = Arc::new(AtomicBool::new(true)); + let online2 = online.clone(); + let name = config.name.clone(); + let (tx, _rx) = mpsc::channel::(1); + + let read_task = tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((stream, peer)) => { + let client_id = id_gen.fetch_add(1, Ordering::SeqCst); + let client_name = format!("{}/client_{}", config.name, client_id); + tracing::info!(name = %client_name, peer = %peer, "local client connected (TCP)"); + + let c_online = Arc::new(AtomicBool::new(true)); + let c_rxb = Arc::new(AtomicU64::new(0)); + let c_txb = Arc::new(AtomicU64::new(0)); + let (c_tx, c_rx) = mpsc::channel::(256); + let (reader, writer) = stream.into_split(); + + let c_online2 = c_online.clone(); + let c_txb2 = c_txb.clone(); + tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2)); + + let c_online3 = c_online.clone(); + let c_rxb2 = c_rxb.clone(); + let transport_tx2 = transport_tx.clone(); + let dereg_tx = transport_tx.clone(); + let cname = client_name.clone(); + let read_handle = tokio::spawn(async move { + local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2) + .await; + tracing::info!(name = %cname, "local client disconnected"); + // See unix variant — notify proactively to avoid zombies. + let _ = dereg_tx + .send(TransportMessage::DeregisterInterface { id: client_id }) + .await; + }); + + let handle = InterfaceHandle { + id: client_id, + name: client_name, + mode: InterfaceMode::Full, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: 1_000_000_000, + mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU), + online: c_online, + rxb: Some(c_rxb), + txb: Some(c_txb), + tx: c_tx, + read_task: read_handle, + }; + if handle_tx.send(handle).await.is_err() { + tracing::warn!("local handle registry closed"); + break; + } + } + Err(e) => { + tracing::warn!(error = %e, "local accept error"); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + } + } + online2.store(false, Ordering::SeqCst); + }); + + let server_rxb = Arc::new(AtomicU64::new(0)); + let server_txb = Arc::new(AtomicU64::new(0)); + + Ok(InterfaceHandle { + id: 0, + name, + mode: InterfaceMode::Full, + direction: InterfaceDirection { + inbound: true, + outbound: false, + forward: false, + repeat: false, + }, + bitrate: 1_000_000_000, + mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU), + online, + rxb: Some(server_rxb), + txb: Some(server_txb), + tx, + read_task, + }) + } + + pub async fn spawn_local_client_impl( + config: LocalClientConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, + ) -> Result { + let addr = fallback_tcp_addr(&config.socket_path); + let stream = TcpStream::connect(&addr).await?; + tracing::info!(name = %config.name, addr = %addr, "local client connected (TCP fallback)"); + + let online = Arc::new(AtomicBool::new(true)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let (tx, rx) = mpsc::channel::(256); + let (reader, writer) = stream.into_split(); + + let online_w = online.clone(); + let task_txb = shared_txb.clone(); + tokio::spawn(local_write_loop(writer, rx, online_w, task_txb)); + + let online_r = online.clone(); + let task_rxb = shared_rxb.clone(); + let name = config.name.clone(); + let read_task = tokio::spawn(async move { + local_read_loop(reader, id, transport_tx, online_r, task_rxb).await; + }); + + Ok(InterfaceHandle { + id, + name, + mode: InterfaceMode::Full, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: 1_000_000_000, + mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU), + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) + } +} + +#[tracing::instrument( + level = "debug", + name = "local.server.accept", + skip_all, + fields(name = %config.name, socket_path = %config.socket_path), +)] +pub async fn spawn_local_server( + config: LocalServerConfig, + id_gen: Arc, + transport_tx: mpsc::Sender, + handle_tx: mpsc::Sender, +) -> Result { + platform::spawn_local_server_impl(config, id_gen, transport_tx, handle_tx).await +} + +#[tracing::instrument( + level = "debug", + name = "local.client.connect", + skip_all, + fields(name = %config.name, client_id = id, socket_path = %config.socket_path), +)] +pub async fn spawn_local_client( + config: LocalClientConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + platform::spawn_local_client_impl(config, id, transport_tx).await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn unique_test_socket_path(prefix: &str) -> String { + #[cfg(unix)] + { + format!( + "/tmp/{prefix}_{}_{}.sock", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ) + } + + #[cfg(not(unix))] + { + let listener = + std::net::TcpListener::bind("127.0.0.1:0").expect("reserve local test port"); + let port = listener.local_addr().expect("read local test port").port(); + drop(listener); + format!("tcp://127.0.0.1:{port}") + } + } + + #[test] + fn test_local_mtu() { + assert_eq!(LOCAL_MTU, 262_144); + } + + #[test] + fn test_local_server_config() { + let cfg = LocalServerConfig { + socket_path: "/tmp/test_rns.sock".to_string(), + name: "TestServer".to_string(), + }; + assert_eq!(cfg.socket_path, "/tmp/test_rns.sock"); + assert_eq!(cfg.name, "TestServer"); + } + + #[test] + fn test_local_client_config() { + let cfg = LocalClientConfig { + socket_path: "/tmp/test_rns.sock".to_string(), + name: "TestClient".to_string(), + }; + assert_eq!(cfg.socket_path, "/tmp/test_rns.sock"); + assert_eq!(cfg.name, "TestClient"); + } + + #[tokio::test] + async fn test_local_ipc_roundtrip() { + let (transport_tx, mut transport_rx) = mpsc::channel::(64); + let (handle_tx, mut handle_rx) = mpsc::channel::(8); + let id_gen = Arc::new(AtomicU64::new(500)); + + let socket_path = unique_test_socket_path("reticulum_test"); + + let server_cfg = LocalServerConfig { + socket_path: socket_path.clone(), + name: "test-local-server".to_string(), + }; + + let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx) + .await + .unwrap(); + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let client_cfg = LocalClientConfig { + socket_path: socket_path.clone(), + name: "test-local-client".to_string(), + }; + + let client_handle = spawn_local_client(client_cfg, 42, transport_tx.clone()) + .await + .unwrap(); + + let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv()) + .await + .expect("timeout waiting for accepted handle") + .expect("handle channel closed"); + + let payload = Bytes::from_static(b"local ipc test"); + client_handle.tx.send(payload.clone()).await.unwrap(); + + let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) + .await + .expect("timeout") + .expect("channel closed"); + + match msg { + TransportMessage::Inbound(pkt) => { + assert_eq!(pkt.raw, payload); + assert_eq!(pkt.interface_id, accepted.id); + } + other => panic!("unexpected: {:?}", other), + } + + let reply = Bytes::from_static(b"local ipc reply"); + accepted.tx.send(reply.clone()).await.unwrap(); + + let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) + .await + .expect("timeout") + .expect("channel closed"); + + match msg2 { + TransportMessage::Inbound(pkt) => { + assert_eq!(pkt.raw, reply); + assert_eq!(pkt.interface_id, 42); + } + other => panic!("unexpected: {:?}", other), + } + + server_handle.read_task.abort(); + client_handle.read_task.abort(); + let _ = std::fs::remove_file(&socket_path); + } + + /// Server-side read loop must DeregisterInterface on EOF (no zombie leak). + #[tokio::test] + async fn test_local_server_deregisters_on_client_disconnect() { + let (transport_tx, mut transport_rx) = mpsc::channel::(64); + let (handle_tx, mut handle_rx) = mpsc::channel::(8); + let id_gen = Arc::new(AtomicU64::new(700)); + + let socket_path = unique_test_socket_path("reticulum_dereg_test"); + let _ = std::fs::remove_file(&socket_path); + + let server_cfg = LocalServerConfig { + socket_path: socket_path.clone(), + name: "dereg-server".to_string(), + }; + let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx) + .await + .unwrap(); + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let client_cfg = LocalClientConfig { + socket_path: socket_path.clone(), + name: "dereg-client".to_string(), + }; + let client_handle = spawn_local_client(client_cfg, 77, transport_tx.clone()) + .await + .unwrap(); + + let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv()) + .await + .expect("timeout waiting for accepted handle") + .expect("handle channel closed"); + let server_side_client_id = accepted.id; + + // Abort client; server's per-client read_loop sees EOF and exits. + client_handle.read_task.abort(); + drop(client_handle.tx); + + let mut saw_dereg = false; + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3); + while tokio::time::Instant::now() < deadline { + match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv()) + .await + { + Ok(Some(TransportMessage::DeregisterInterface { id })) + if id == server_side_client_id => + { + saw_dereg = true; + break; + } + Ok(Some(_)) => continue, // inbound frames etc. + Ok(None) => break, + Err(_) => continue, + } + } + + assert!( + saw_dereg, + "server must emit DeregisterInterface for disconnected client id {server_side_client_id}" + ); + + server_handle.read_task.abort(); + let _ = std::fs::remove_file(&socket_path); + } +} diff --git a/crates/rns-interface/src/pipe.rs b/crates/rns-interface/src/pipe.rs new file mode 100644 index 0000000..1e05262 --- /dev/null +++ b/crates/rns-interface/src/pipe.rs @@ -0,0 +1,251 @@ +//! HDLC-framed data over a subprocess's stdin/stdout; respawns on exit. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use bytes::Bytes; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::process::Command; +use tokio::sync::mpsc; + +use crate::hdlc; +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const BITRATE_GUESS: u64 = 1_000_000; +pub const HW_MTU: u32 = 1064; +pub const DEFAULT_RESPAWN_DELAY: f64 = 5.0; + +#[derive(Debug, Clone)] +pub struct PipeInterfaceConfig { + pub name: String, + pub command: String, + /// Seconds before respawning after subprocess exit. + pub respawn_delay: f64, + pub mode: InterfaceMode, +} + +impl PipeInterfaceConfig { + pub fn new(name: &str, command: &str) -> Self { + Self { + name: name.to_string(), + command: command.to_string(), + respawn_delay: DEFAULT_RESPAWN_DELAY, + mode: InterfaceMode::Full, + } + } +} + +pub async fn spawn_pipe_interface( + config: PipeInterfaceConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + 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::(256); + let name = config.name.clone(); + let mode = config.mode; + + // Outbound rx must survive respawns; share across write loops. + let rx = Arc::new(tokio::sync::Mutex::new(rx)); + + let online_task = online.clone(); + let rxb_task = shared_rxb.clone(); + let txb_task = shared_txb.clone(); + + let read_task = tokio::spawn(async move { + loop { + if !online_task.load(Ordering::SeqCst) { + break; + } + + let parts: Vec<&str> = config.command.split_whitespace().collect(); + if parts.is_empty() { + tracing::error!("PipeInterface: empty command"); + break; + } + + let child = Command::new(parts[0]) + .args(&parts[1..]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn(); + + let mut child = match child { + Ok(c) => c, + Err(e) => { + tracing::warn!(error = %e, "PipeInterface: failed to spawn subprocess"); + tokio::time::sleep(std::time::Duration::from_secs_f64(config.respawn_delay)) + .await; + continue; + } + }; + + tracing::info!(name = %config.name, cmd = %config.command, "PipeInterface: subprocess spawned"); + + let mut stdout = match child.stdout.take() { + Some(s) => s, + None => { + tracing::error!("PipeInterface: no stdout from subprocess"); + break; + } + }; + let mut stdin = match child.stdin.take() { + Some(s) => s, + None => { + tracing::error!("PipeInterface: no stdin for subprocess"); + break; + } + }; + + // Per-subprocess writer channel; outer rx forwards into conn_tx. + let (conn_tx, mut conn_rx) = mpsc::channel::(256); + let online_w = online_task.clone(); + let txb_w = txb_task.clone(); + let write_handle = tokio::spawn(async move { + while let Some(data) = conn_rx.recv().await { + if !online_w.load(Ordering::SeqCst) { + break; + } + let framed = hdlc::frame(&data); + txb_w.fetch_add(framed.len() as u64, Ordering::Relaxed); + if let Err(e) = stdin.write_all(&framed).await { + tracing::warn!(error = %e, "PipeInterface: write error"); + break; + } + if let Err(e) = stdin.flush().await { + tracing::warn!(error = %e, "PipeInterface: flush error"); + break; + } + } + }); + + let rx_ref = rx.clone(); + let fwd_handle = tokio::spawn(async move { + let mut guard = rx_ref.lock().await; + while let Some(data) = guard.recv().await { + if conn_tx.send(data).await.is_err() { + break; + } + } + }); + + let mut deframer = hdlc::HdlcDeframer::new(); + let mut buf = [0u8; 2048]; + loop { + match stdout.read(&mut buf).await { + Ok(0) => { + tracing::info!("PipeInterface: subprocess stdout EOF"); + break; + } + Ok(n) => { + rxb_task.fetch_add(n as u64, Ordering::Relaxed); + for frame in deframer.feed(&buf[..n]) { + if frame.is_empty() { + continue; + } + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id: id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + online_task.store(false, Ordering::SeqCst); + return; + } + } + } + Err(e) => { + tracing::warn!(error = %e, "PipeInterface: read error"); + break; + } + } + } + + fwd_handle.abort(); + let _ = fwd_handle.await; + write_handle.abort(); + let _ = write_handle.await; + + let _ = child.kill().await; + + if !online_task.load(Ordering::SeqCst) { + break; + } + + tracing::info!( + name = %config.name, + delay = config.respawn_delay, + "PipeInterface: respawning subprocess" + ); + tokio::time::sleep(std::time::Duration::from_secs_f64(config.respawn_delay)).await; + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: BITRATE_GUESS, + mtu: HW_MTU, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pipe_config() { + let cfg = PipeInterfaceConfig::new("pipe0", "cat"); + assert_eq!(cfg.command, "cat"); + assert_eq!(cfg.respawn_delay, DEFAULT_RESPAWN_DELAY); + assert_eq!(cfg.mode, InterfaceMode::Full); + } + + #[test] + fn test_constants() { + assert_eq!(BITRATE_GUESS, 1_000_000); + assert_eq!(HW_MTU, 1064); + } + + #[test] + fn test_pipe_config_custom_command() { + let cfg = PipeInterfaceConfig::new("pipe1", "socat - TCP:10.0.0.1:4242"); + assert_eq!(cfg.command, "socat - TCP:10.0.0.1:4242"); + assert_eq!(cfg.name, "pipe1"); + } + + #[test] + fn test_pipe_config_respawn_delay() { + assert_eq!(DEFAULT_RESPAWN_DELAY, 5.0); + let mut cfg = PipeInterfaceConfig::new("pipe0", "cat"); + assert_eq!(cfg.respawn_delay, 5.0); + cfg.respawn_delay = 10.0; + assert_eq!(cfg.respawn_delay, 10.0); + } + + #[test] + fn test_pipe_config_mode() { + let mut cfg = PipeInterfaceConfig::new("pipe0", "cat"); + assert_eq!(cfg.mode, InterfaceMode::Full); + cfg.mode = InterfaceMode::PointToPoint; + assert_eq!(cfg.mode, InterfaceMode::PointToPoint); + } +} diff --git a/crates/rns-interface/src/rnode.rs b/crates/rns-interface/src/rnode.rs new file mode 100644 index 0000000..ebf2560 --- /dev/null +++ b/crates/rns-interface/src/rnode.rs @@ -0,0 +1,641 @@ +//! LoRa radio control via RNode firmware's extended-KISS protocol. +//! Shared constants + transport-agnostic response handler. Serial: +//! [`spawn_rnode_interface`] (feature `serial`); BLE: [`crate::ble_rnode`]. + +use bytes::Bytes; + +use crate::kiss; +use crate::traits::{InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +#[cfg(feature = "serial")] +use crate::traits::{InterfaceDirection, InterfaceHandle}; +#[cfg(feature = "serial")] +use std::sync::Arc; +#[cfg(feature = "serial")] +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +#[cfg(feature = "serial")] +use std::time::Duration; +#[cfg(feature = "serial")] +use tokio::sync::mpsc; + +pub const CMD_FREQUENCY: u8 = 0x01; +pub const CMD_BANDWIDTH: u8 = 0x02; +pub const CMD_TXPOWER: u8 = 0x03; +pub const CMD_SF: u8 = 0x04; +pub const CMD_CR: u8 = 0x05; +pub const CMD_RADIO_STATE: u8 = 0x06; +pub const CMD_RADIO_LOCK: u8 = 0x07; +pub const CMD_DETECT: u8 = 0x08; +pub const CMD_IMPLICIT: u8 = 0x09; +pub const CMD_LEAVE: u8 = 0x0A; +pub const CMD_PROMISC: u8 = 0x0E; +pub const CMD_READY: u8 = 0x0F; + +pub const CMD_STAT_RX: u8 = 0x21; +pub const CMD_STAT_TX: u8 = 0x22; +pub const CMD_STAT_RSSI: u8 = 0x23; +pub const CMD_STAT_SNR: u8 = 0x24; +pub const CMD_STAT_CHTM: u8 = 0x25; +pub const CMD_STAT_PHYPRM: u8 = 0x26; +pub const CMD_STAT_BAT: u8 = 0x27; +pub const CMD_STAT_EDROP: u8 = 0x28; + +pub const CMD_STAT_TEMP: u8 = 0x29; +pub const CMD_ERROR: u8 = 0x90; + +pub const CMD_BLINK: u8 = 0x30; +pub const CMD_RANDOM: u8 = 0x40; + +pub const CMD_FB_EXT: u8 = 0x41; +pub const CMD_FB_READ: u8 = 0x42; +pub const CMD_FB_WRITE: u8 = 0x43; +pub const CMD_BT_CTRL: u8 = 0x46; + +pub const CMD_BOARD: u8 = 0x47; +pub const CMD_PLATFORM: u8 = 0x48; +pub const CMD_MCU: u8 = 0x49; +pub const CMD_FW_VERSION: u8 = 0x50; +pub const CMD_ROM_READ: u8 = 0x51; +pub const CMD_ROM_WRITE: u8 = 0x52; +pub const CMD_CONF_SAVE: u8 = 0x53; +pub const CMD_CONF_DELETE: u8 = 0x54; +pub const CMD_DEV_HASH: u8 = 0x56; +pub const CMD_DEV_SIG: u8 = 0x57; +pub const CMD_FW_HASH: u8 = 0x58; +pub const CMD_ROM_WIPE: u8 = 0x59; +pub const CMD_HASHES: u8 = 0x60; +pub const CMD_FW_UPD: u8 = 0x61; +pub const CMD_BT_PIN: u8 = 0x62; + +pub const CMD_ST_ALOCK: u8 = 0x0B; +pub const CMD_LT_ALOCK: u8 = 0x0C; + +pub const CMD_RESET: u8 = 0x55; +pub const CMD_DISP_INT: u8 = 0x45; +pub const CMD_DISP_ADR: u8 = 0x63; +pub const CMD_DISP_BLNK: u8 = 0x64; +pub const CMD_NP_INT: u8 = 0x65; +pub const CMD_DISP_ROT: u8 = 0x67; +pub const CMD_DISP_RCND: u8 = 0x68; +pub const CMD_DIS_IA: u8 = 0x69; +pub const CMD_WIFI_MODE: u8 = 0x6A; +pub const CMD_WIFI_SSID: u8 = 0x6B; +pub const CMD_WIFI_PSK: u8 = 0x6C; +pub const CMD_CFG_READ: u8 = 0x6D; +pub const CMD_WIFI_CHN: u8 = 0x6E; +pub const CMD_WIFI_IP: u8 = 0x84; +pub const CMD_WIFI_NM: u8 = 0x85; + +pub const DETECT_REQ: u8 = 0x73; +pub const DETECT_RESP: u8 = 0x46; + +pub const REQUIRED_FW_VER_MAJ: u8 = 1; +pub const REQUIRED_FW_VER_MIN: u8 = 52; + +pub const RSSI_OFFSET: i32 = 157; + +pub const RECONNECT_WAIT: u64 = 5; +pub const MAX_RECONNECT_TRIES: usize = 3; + +pub const RADIO_STATE_ON: u8 = 0x01; +pub const RADIO_STATE_OFF: u8 = 0x00; + +#[cfg(feature = "serial")] +const RNODE_READ_TIMEOUT_MS: u64 = 100; + +#[derive(Debug, Clone)] +pub struct RNodeConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + /// Hz. + pub frequency: u32, + /// Hz. + pub bandwidth: u32, + pub spreading_factor: u8, + pub coding_rate: u8, + /// dBm. + pub tx_power: u8, + pub mode: InterfaceMode, + pub flow_control: bool, + /// Short-term airtime cap, percent (0.0..100.0). `None` = unlimited. + pub st_alock: Option, + /// Long-term airtime cap, percent (0.0..100.0). `None` = unlimited. + pub lt_alock: Option, +} + +impl RNodeConfig { + pub fn new(name: &str, port: &str) -> Self { + Self { + name: name.to_string(), + port: port.to_string(), + baud_rate: 115200, + frequency: 868_000_000, + bandwidth: 125_000, + spreading_factor: 7, + coding_rate: 5, + tx_power: 14, + mode: InterfaceMode::Full, + flow_control: true, + st_alock: None, + lt_alock: None, + } + } +} + +/// LoRa on-air bps via `SF * (4/CR) / (2^SF / BW_kHz) * 1000`. 0 on invalid. +pub fn calculate_bitrate(sf: u8, cr: u8, bandwidth_hz: u32) -> u64 { + if sf == 0 || cr == 0 || bandwidth_hz == 0 { + return 0; + } + let sf_f = sf as f64; + let cr_f = cr as f64; + let bw_khz = bandwidth_hz as f64 / 1000.0; + let two_pow_sf = (2.0_f64).powf(sf_f); + if two_pow_sf == 0.0 { + return 0; + } + let bitrate = sf_f * (4.0 / cr_f) / (two_pow_sf / bw_khz) * 1000.0; + if bitrate.is_finite() && bitrate > 0.0 { + bitrate as u64 + } else { + 0 + } +} + +pub fn build_detect_sequence() -> Vec { + let mut out = Vec::with_capacity(32); + kiss::frame_with_command_into(CMD_DETECT, &[DETECT_REQ], &mut out); + kiss::frame_with_command_into(CMD_FW_VERSION, &[0x00], &mut out); + kiss::frame_with_command_into(CMD_PLATFORM, &[0x00], &mut out); + kiss::frame_with_command_into(CMD_MCU, &[0x00], &mut out); + out +} + +/// Airtime-lock commands. Percent is encoded as `(percent * 100)` big-endian u16. +pub fn build_airtime_sequence(config: &RNodeConfig) -> Vec { + let mut out = Vec::with_capacity(16); + if let Some(st) = config.st_alock { + let at = (st * 100.0) as u16; + let c1 = (at >> 8) as u8; + let c2 = (at & 0xFF) as u8; + kiss::frame_with_command_into(CMD_ST_ALOCK, &[c1, c2], &mut out); + } + if let Some(lt) = config.lt_alock { + let at = (lt * 100.0) as u16; + let c1 = (at >> 8) as u8; + let c2 = (at & 0xFF) as u8; + kiss::frame_with_command_into(CMD_LT_ALOCK, &[c1, c2], &mut out); + } + out +} + +fn u32_to_bytes(val: u32) -> [u8; 4] { + val.to_be_bytes() +} + +/// KISS init sequence. Order matters: RADIO_STATE=ON must be last. +pub fn build_init_sequence(config: &RNodeConfig) -> Vec { + let mut out = Vec::with_capacity(48); + kiss::frame_with_command_into(CMD_FREQUENCY, &u32_to_bytes(config.frequency), &mut out); + kiss::frame_with_command_into(CMD_BANDWIDTH, &u32_to_bytes(config.bandwidth), &mut out); + kiss::frame_with_command_into(CMD_SF, &[config.spreading_factor], &mut out); + kiss::frame_with_command_into(CMD_CR, &[config.coding_rate], &mut out); + kiss::frame_with_command_into(CMD_TXPOWER, &[config.tx_power], &mut out); + kiss::frame_with_command_into(CMD_RADIO_STATE, &[RADIO_STATE_ON], &mut out); + out +} + +// Hot-path interface adapters pass this enum around directly; boxing the +// packet variant would add allocation to every received frame. +#[allow(clippy::large_enum_variant)] +pub enum RNodeResponse { + Packet(TransportMessage), + Ready(bool), + None, +} + +/// Dispatch decoded KISS frame; shared by serial and BLE transports. +pub fn process_rnode_response( + cmd: u8, + frame: &[u8], + id: InterfaceId, + last_rssi: &mut Option, + last_snr: &mut Option, +) -> RNodeResponse { + match cmd { + kiss::CMD_DATA => { + if frame.is_empty() { + return RNodeResponse::None; + } + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::copy_from_slice(frame), + interface_id: id, + rssi: *last_rssi, + snr: *last_snr, + q: None, + }); + // RSSI/SNR stats attach to the next data frame; clear once consumed. + *last_rssi = None; + *last_snr = None; + RNodeResponse::Packet(msg) + } + CMD_STAT_RSSI => { + if !frame.is_empty() { + *last_rssi = Some(frame[0] as i8 as f32); + } + RNodeResponse::None + } + CMD_STAT_SNR => { + if !frame.is_empty() { + *last_snr = Some(frame[0] as i8 as f32 / 4.0); + } + RNodeResponse::None + } + CMD_READY => { + let is_ready = frame.first().copied().unwrap_or(0) != 0; + RNodeResponse::Ready(is_ready) + } + CMD_DETECT => { + if frame.first().copied() == Some(DETECT_RESP) { + tracing::info!(id, "RNode detected"); + } + RNodeResponse::None + } + CMD_RADIO_STATE => { + if frame.first().copied() == Some(RADIO_STATE_ON) { + tracing::info!(id, "RNode radio online"); + } else { + tracing::warn!(id, "RNode radio offline"); + } + RNodeResponse::None + } + CMD_FW_VERSION => { + if frame.len() >= 2 { + let major = frame[0]; + let minor = frame[1]; + tracing::info!( + id, + major, + minor, + "RNode firmware version {}.{}", + major, + minor, + ); + if major < REQUIRED_FW_VER_MAJ + || (major == REQUIRED_FW_VER_MAJ && minor < REQUIRED_FW_VER_MIN) + { + tracing::warn!( + id, + "RNode firmware {}.{} below required {}.{}", + major, + minor, + REQUIRED_FW_VER_MAJ, + REQUIRED_FW_VER_MIN, + ); + } + } + RNodeResponse::None + } + CMD_ST_ALOCK => { + if frame.len() >= 2 { + let at = ((frame[0] as u16) << 8) | frame[1] as u16; + let pct = at as f32 / 100.0; + tracing::debug!(id, "RNode short-term airtime limit: {:.2}%", pct); + } + RNodeResponse::None + } + CMD_LT_ALOCK => { + if frame.len() >= 2 { + let at = ((frame[0] as u16) << 8) | frame[1] as u16; + let pct = at as f32 / 100.0; + tracing::debug!(id, "RNode long-term airtime limit: {:.2}%", pct); + } + RNodeResponse::None + } + CMD_STAT_BAT => { + if frame.len() >= 2 { + let batt = ((frame[0] as u16) << 8) | frame[1] as u16; + tracing::debug!(id, battery_mv = batt, "RNode battery status"); + } + RNodeResponse::None + } + CMD_STAT_TEMP => { + if !frame.is_empty() { + let temp = frame[0] as i8; + tracing::debug!(id, temp_c = temp, "RNode temperature"); + } + RNodeResponse::None + } + CMD_RADIO_LOCK => { + let locked = frame.first().copied().unwrap_or(0) != 0; + tracing::debug!(id, locked, "RNode radio lock state"); + RNodeResponse::None + } + CMD_ERROR => { + tracing::warn!( + id, + error_code = frame.first().copied().unwrap_or(0), + "RNode reported error" + ); + RNodeResponse::None + } + _ => { + tracing::debug!(id, cmd, "RNode: ignoring KISS command"); + RNodeResponse::None + } + } +} + +#[cfg(feature = "serial")] +pub async fn spawn_rnode_interface( + config: RNodeConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let port = serialport::new(&config.port, config.baud_rate) + .timeout(Duration::from_millis(RNODE_READ_TIMEOUT_MS)) + .open() + .map_err(|e| crate::traits::InterfaceError::SendFailed(format!("rnode open: {}", e)))?; + + tracing::info!( + name = %config.name, + port = %config.port, + freq = config.frequency, + bw = config.bandwidth, + sf = config.spreading_factor, + "RNode interface opened" + ); + + // Detect first so firmware version is known before init. + { + let mut detect_port = port.try_clone().map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("rnode clone: {}", e)) + })?; + let detect_seq = build_detect_sequence(); + use std::io::Write; + detect_port.write_all(&detect_seq).map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("rnode detect write: {}", e)) + })?; + detect_port.flush().map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("rnode detect flush: {}", e)) + })?; + } + + { + let mut init_port = port.try_clone().map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("rnode clone: {}", e)) + })?; + let mut init_seq = build_init_sequence(&config); + init_seq.extend_from_slice(&build_airtime_sequence(&config)); + use std::io::Write; + init_port.write_all(&init_seq).map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("rnode init write: {}", e)) + })?; + init_port.flush().map_err(|e| { + crate::traits::InterfaceError::SendFailed(format!("rnode init flush: {}", e)) + })?; + } + + let bitrate = calculate_bitrate( + config.spreading_factor, + config.coding_rate, + config.bandwidth, + ); + tracing::info!( + bitrate_bps = bitrate, + bitrate_kbps = format!("{:.2}", bitrate as f64 / 1000.0), + "RNode on-air bitrate calculated" + ); + + let online = Arc::new(AtomicBool::new(true)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let (tx, mut rx) = mpsc::channel::(256); + let name = config.name.clone(); + let mode = config.mode; + let flow_control = config.flow_control; + + let port_write = port + .try_clone() + .map_err(|e| crate::traits::InterfaceError::SendFailed(format!("rnode clone: {}", e)))?; + + let ready = Arc::new(AtomicBool::new(true)); + + let online_w = online.clone(); + let ready_w = ready.clone(); + let txb_w = shared_txb.clone(); + tokio::spawn(async move { + let mut port_w = port_write; + while let Some(data) = rx.recv().await { + txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed); + if flow_control { + while !ready_w.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + if !online_w.load(Ordering::SeqCst) { + return; + } + } + } + let framed = kiss::frame(&data); + let online_ref = online_w.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::io::Write; + port_w.write_all(&framed)?; + port_w.flush()?; + Ok::<_, std::io::Error>(port_w) + }) + .await; + match result { + Ok(Ok(p)) => { + port_w = p; + } + Ok(Err(e)) => { + tracing::warn!(error = %e, "RNode write error"); + online_ref.store(false, Ordering::SeqCst); + break; + } + Err(e) => { + tracing::warn!(error = %e, "RNode write task panicked"); + break; + } + } + } + }); + + let online_r = online.clone(); + let ready_r = ready; + let rxb_r = shared_rxb.clone(); + let read_task = tokio::spawn(async move { + let mut port_r = port; + let mut deframer = kiss::RawKissDeframer::new(); + let mut buf = [0u8; 1024]; + let mut last_rssi: Option = None; + let mut last_snr: Option = None; + + loop { + if !online_r.load(Ordering::SeqCst) { + break; + } + let result = tokio::task::spawn_blocking(move || { + use std::io::Read; + match port_r.read(&mut buf) { + Ok(n) => Ok((port_r, buf, n)), + Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)), + Err(e) => Err((port_r, e)), + } + }) + .await; + + match result { + Ok(Ok((p, b, n))) => { + port_r = p; + buf = b; + if n > 0 { + for (cmd, frame) in deframer.feed(&buf[..n]) { + match process_rnode_response( + cmd, + &frame, + id, + &mut last_rssi, + &mut last_snr, + ) { + RNodeResponse::Packet(msg) => { + rxb_r.fetch_add( + frame.len() as u64, + std::sync::atomic::Ordering::Relaxed, + ); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + RNodeResponse::Ready(is_ready) => { + ready_r.store(is_ready, Ordering::SeqCst); + } + RNodeResponse::None => {} + } + } + } + } + Ok(Err((_p, e))) => { + tracing::warn!(error = %e, "RNode read error"); + online_r.store(false, Ordering::SeqCst); + return; + } + Err(e) => { + tracing::warn!(error = %e, "RNode read task panicked"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate, + mtu: 508, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_rnode_config() { + let cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0"); + assert_eq!(cfg.baud_rate, 115200); + assert_eq!(cfg.frequency, 868_000_000); + assert_eq!(cfg.spreading_factor, 7); + assert!(cfg.flow_control); + assert!(cfg.st_alock.is_none()); + assert!(cfg.lt_alock.is_none()); + } + + #[test] + fn test_init_sequence_parseable() { + let cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0"); + let seq = build_init_sequence(&cfg); + assert!(!seq.is_empty()); + assert_eq!(seq[0], kiss::FEND); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&seq); + assert_eq!(frames.len(), 6); + } + + #[test] + fn test_u32_to_bytes() { + assert_eq!(u32_to_bytes(868_000_000), 868_000_000u32.to_be_bytes()); + assert_eq!(u32_to_bytes(0x01020304), [0x01, 0x02, 0x03, 0x04]); + } + + #[test] + fn test_calculate_bitrate() { + // 7 * (4/5) / (2^7 / 125) * 1000 = 5468.75 bps -> 5468. + let br = calculate_bitrate(7, 5, 125_000); + assert_eq!(br, 5468); + + let br2 = calculate_bitrate(12, 8, 125_000); + assert!(br2 > 0); + assert!(br2 < br); + + assert_eq!(calculate_bitrate(0, 5, 125_000), 0); + assert_eq!(calculate_bitrate(7, 0, 125_000), 0); + assert_eq!(calculate_bitrate(7, 5, 0), 0); + } + + #[test] + fn test_detect_sequence() { + let seq = build_detect_sequence(); + assert!(!seq.is_empty()); + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&seq); + assert_eq!(frames.len(), 4); + assert_eq!(frames[0].0, CMD_DETECT); + } + + #[test] + fn test_airtime_sequence() { + let mut cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0"); + assert!(build_airtime_sequence(&cfg).is_empty()); + + cfg.st_alock = Some(15.0); + cfg.lt_alock = Some(25.0); + let seq = build_airtime_sequence(&cfg); + assert!(!seq.is_empty()); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&seq); + assert_eq!(frames.len(), 2); + assert_eq!(frames[0].0, CMD_ST_ALOCK); + assert_eq!(frames[1].0, CMD_LT_ALOCK); + } + + #[test] + fn test_rnode_admin_constants_match_upstream() { + assert_eq!(CMD_BOARD, 0x47); + assert_eq!(CMD_BT_PIN, 0x62); + assert_eq!(CMD_DISP_INT, 0x45); + assert_eq!(CMD_DISP_ADR, 0x63); + assert_eq!(CMD_WIFI_IP, 0x84); + assert_eq!(CMD_WIFI_NM, 0x85); + } +} diff --git a/crates/rns-interface/src/rnode_admin.rs b/crates/rns-interface/src/rnode_admin.rs new file mode 100644 index 0000000..ffc96c3 --- /dev/null +++ b/crates/rns-interface/src/rnode_admin.rs @@ -0,0 +1,170 @@ +//! Extended-KISS admin codec shared by RNode runtime and `rnodeconf`. + +use std::net::Ipv4Addr; + +use crate::{kiss, rnode}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdminFrame { + pub command: u8, + pub payload: Vec, +} + +pub fn encode_frame(command: u8, payload: &[u8]) -> Vec { + kiss::frame_with_command(command, payload) +} + +pub fn decode_frames(raw: &[u8]) -> Vec { + let mut deframer = kiss::RawKissDeframer::new(); + deframer + .feed(raw) + .into_iter() + .map(|(command, payload)| AdminFrame { command, payload }) + .collect() +} + +pub fn u32_payload(value: u32) -> [u8; 4] { + value.to_be_bytes() +} + +pub fn parse_u32(payload: &[u8]) -> Option { + let bytes: [u8; 4] = payload.try_into().ok()?; + Some(u32::from_be_bytes(bytes)) +} + +pub fn parse_bt_pin(frame: &AdminFrame) -> Option { + (frame.command == rnode::CMD_BT_PIN) + .then(|| parse_u32(&frame.payload)) + .flatten() +} + +pub fn bool_payload(enabled: bool) -> [u8; 1] { + [u8::from(enabled)] +} + +pub fn nullable_string_payload(value: Option<&str>) -> Vec { + match value { + Some(value) if !value.is_empty() => { + let mut out = value.as_bytes().to_vec(); + out.push(0); + out + } + _ => vec![0], + } +} + +pub fn ipv4_payload(addr: Ipv4Addr) -> [u8; 4] { + addr.octets() +} + +pub fn detect_sequence() -> Vec { + vec![ + frame(rnode::CMD_DETECT, &[rnode::DETECT_REQ]), + frame(rnode::CMD_FW_VERSION, &[0]), + frame(rnode::CMD_PLATFORM, &[0]), + frame(rnode::CMD_MCU, &[0]), + frame(rnode::CMD_BOARD, &[0]), + frame(rnode::CMD_DEV_HASH, &[1]), + frame(rnode::CMD_HASHES, &[1]), + frame(rnode::CMD_HASHES, &[2]), + ] +} + +pub fn eeprom_read_frame() -> AdminFrame { + frame(rnode::CMD_ROM_READ, &[0]) +} + +pub fn eeprom_write_frame(address: u8, value: u8) -> AdminFrame { + frame(rnode::CMD_ROM_WRITE, &[address, value]) +} + +pub fn eeprom_wipe_frame() -> AdminFrame { + frame(rnode::CMD_ROM_WIPE, &[0xF8]) +} + +pub fn reset_frame() -> AdminFrame { + frame(rnode::CMD_RESET, &[0xF8]) +} + +pub fn firmware_update_frame() -> AdminFrame { + frame(rnode::CMD_FW_UPD, &[1]) +} + +pub fn firmware_hash_frame(hash: &[u8; 32]) -> AdminFrame { + frame(rnode::CMD_FW_HASH, hash) +} + +pub fn device_signature_frame(signature: &[u8; 64]) -> AdminFrame { + frame(rnode::CMD_DEV_SIG, signature) +} + +pub fn frame(command: u8, payload: &[u8]) -> AdminFrame { + AdminFrame { + command, + payload: payload.to_vec(), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum WifiMode { + Off = 0, + Station = 1, + AccessPoint = 2, +} + +impl WifiMode { + pub fn payload(self) -> [u8; 1] { + [self as u8] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extended_commands_round_trip_without_masking() { + let mut raw = Vec::new(); + raw.extend_from_slice(&encode_frame(rnode::CMD_WIFI_IP, &[192, 168, 1, 10])); + raw.extend_from_slice(&encode_frame(rnode::CMD_WIFI_NM, &[255, 255, 255, 0])); + raw.extend_from_slice(&encode_frame(rnode::CMD_BT_PIN, &123456u32.to_be_bytes())); + + let frames = decode_frames(&raw); + assert_eq!(frames[0].command, 0x84); + assert_eq!(frames[0].payload, vec![192, 168, 1, 10]); + assert_eq!(frames[1].command, 0x85); + assert_eq!(frames[2].command, 0x62); + assert_eq!(parse_bt_pin(&frames[2]), Some(123456)); + } + + #[test] + fn payload_helpers_match_upstream_shapes() { + assert_eq!(u32_payload(868_000_000), [0x33, 0xBC, 0xA1, 0x00]); + assert_eq!(bool_payload(true), [1]); + assert_eq!(WifiMode::AccessPoint.payload(), [2]); + assert_eq!(nullable_string_payload(None), vec![0]); + assert_eq!(nullable_string_payload(Some("RNode")), b"RNode\0"); + assert_eq!( + ipv4_payload(Ipv4Addr::new(192, 168, 1, 10)), + [192, 168, 1, 10] + ); + } + + #[test] + fn admin_frame_builders_match_upstream_commands() { + let sequence = detect_sequence(); + assert_eq!( + sequence.iter().map(|f| f.command).collect::>(), + vec![0x08, 0x50, 0x48, 0x49, 0x47, 0x56, 0x60, 0x60] + ); + assert_eq!(eeprom_read_frame(), frame(rnode::CMD_ROM_READ, &[0])); + assert_eq!( + eeprom_write_frame(0x9B, 0x73), + frame(rnode::CMD_ROM_WRITE, &[0x9B, 0x73]) + ); + assert_eq!(eeprom_wipe_frame(), frame(rnode::CMD_ROM_WIPE, &[0xF8])); + assert_eq!(reset_frame(), frame(rnode::CMD_RESET, &[0xF8])); + assert_eq!(firmware_update_frame(), frame(rnode::CMD_FW_UPD, &[1])); + } +} diff --git a/crates/rns-interface/src/rnode_multi.rs b/crates/rns-interface/src/rnode_multi.rs new file mode 100644 index 0000000..0931b58 --- /dev/null +++ b/crates/rns-interface/src/rnode_multi.rs @@ -0,0 +1,1237 @@ +//! Multi-radio RNode: up to 11 sub-interfaces on one serial connection. +//! One read task demuxes by per-vport command byte; one write task prepends +//! `CMD_SEL_INT` so the device picks the right radio. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use bytes::Bytes; +use tokio::sync::mpsc; + +use crate::kiss; +use crate::rnode; +use crate::traits::{ + InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode, +}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const MAX_SUBINTERFACES: usize = 11; + +/// Minimum firmware supporting multi-interface mode. +pub const REQUIRED_FW_VER_MAJ: u8 = 1; +pub const REQUIRED_FW_VER_MIN: u8 = 74; + +pub const CMD_SEL_INT: u8 = 0x1F; +pub const CMD_INTERFACES: u8 = 0x71; +pub const CMD_ERROR: u8 = 0x90; + +pub const ERROR_INITRADIO: u8 = 0x01; +pub const ERROR_TXFAILED: u8 = 0x02; + +/// Per-sub-interface data command bytes. NOT port-nibble; some collide +/// (e.g. `CMD_INT5_DATA == CMD_ERROR`) — demux by vport index, not byte. +pub const CMD_INT_DATA: [u8; 12] = [ + 0x00, 0x10, 0x20, 0x70, 0x75, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum RadioType { + SX127X = 0x00, + SX1276 = 0x01, + SX1278 = 0x02, + SX126X = 0x10, + SX1262 = 0x11, + SX128X = 0x20, + SX1280 = 0x21, +} + +impl RadioType { + pub fn from_u8(val: u8) -> Option { + match val { + 0x00 => Some(Self::SX127X), + 0x01 => Some(Self::SX1276), + 0x02 => Some(Self::SX1278), + 0x10 => Some(Self::SX126X), + 0x11 => Some(Self::SX1262), + 0x20 => Some(Self::SX128X), + 0x21 => Some(Self::SX1280), + _ => None, + } + } + + pub fn family_name(&self) -> &'static str { + match self { + Self::SX127X | Self::SX1276 | Self::SX1278 => "SX127X", + Self::SX126X | Self::SX1262 => "SX126X", + Self::SX128X | Self::SX1280 => "SX128X", + } + } + + /// Sub-GHz: 137 MHz..1 GHz; SX128X: 2.2..2.6 GHz. + pub fn validate_frequency(&self, freq_hz: u32) -> bool { + match self { + Self::SX127X | Self::SX1276 | Self::SX1278 | Self::SX126X | Self::SX1262 => { + (137_000_000..=1_000_000_000).contains(&freq_hz) + } + Self::SX128X | Self::SX1280 => (2_200_000_000..=2_600_000_000).contains(&freq_hz), + } + } +} + +#[derive(Debug, Clone)] +pub struct SubInterfaceConfig { + pub name: String, + /// vport index on RNode (0..MAX_SUBINTERFACES). + pub vport: u8, + pub frequency: u32, + pub bandwidth: u32, + pub spreading_factor: u8, + pub coding_rate: u8, + pub tx_power: u8, + pub mode: InterfaceMode, + pub flow_control: bool, + pub outgoing: bool, + /// Short-term airtime cap, percent of duty cycle. + pub st_alock: Option, + /// Long-term airtime cap, percent of duty cycle. + pub lt_alock: Option, +} + +impl SubInterfaceConfig { + pub fn new(name: &str, vport: u8, frequency: u32) -> Self { + Self { + name: name.to_string(), + vport, + frequency, + bandwidth: 125_000, + spreading_factor: 7, + coding_rate: 5, + tx_power: 14, + mode: InterfaceMode::Full, + flow_control: false, + outgoing: true, + st_alock: None, + lt_alock: None, + } + } + + pub fn validate(&self) -> Result<(), String> { + if self.tx_power > 37 { + return Err(format!( + "Invalid TX power {} for sub-interface {}", + self.tx_power, self.name + )); + } + if self.bandwidth < 7800 || self.bandwidth > 1_625_000 { + return Err(format!( + "Invalid bandwidth {} for sub-interface {}", + self.bandwidth, self.name + )); + } + if self.spreading_factor < 5 || self.spreading_factor > 12 { + return Err(format!( + "Invalid spreading factor {} for sub-interface {}", + self.spreading_factor, self.name + )); + } + if self.coding_rate < 5 || self.coding_rate > 8 { + return Err(format!( + "Invalid coding rate {} for sub-interface {}", + self.coding_rate, self.name + )); + } + if let Some(st) = self.st_alock + && (!(0.0..=100.0).contains(&st)) + { + return Err(format!( + "Invalid short-term airtime limit {} for sub-interface {}", + st, self.name + )); + } + if let Some(lt) = self.lt_alock + && (!(0.0..=100.0).contains(<)) + { + return Err(format!( + "Invalid long-term airtime limit {} for sub-interface {}", + lt, self.name + )); + } + if self.vport as usize > MAX_SUBINTERFACES { + return Err(format!( + "Virtual port {} exceeds max {} for sub-interface {}", + self.vport, MAX_SUBINTERFACES, self.name + )); + } + Ok(()) + } +} + +#[derive(Debug, Clone)] +pub struct RNodeMultiConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + pub flow_control: bool, + /// Up to `MAX_SUBINTERFACES` radios on this device. + pub subinterfaces: Vec, +} + +impl RNodeMultiConfig { + pub fn new(name: &str, port: &str) -> Self { + Self { + name: name.to_string(), + port: port.to_string(), + baud_rate: 115200, + flow_control: false, + subinterfaces: Vec::new(), + } + } +} + +/// SEL_INT, push params, then RADIO_STATE=ON last. +pub fn build_subinterface_init(index: u8, config: &SubInterfaceConfig) -> Vec { + let mut out = Vec::with_capacity(80); + + kiss::frame_with_command_into(CMD_SEL_INT, &[index], &mut out); + kiss::frame_with_command_into( + rnode::CMD_FREQUENCY, + &config.frequency.to_be_bytes(), + &mut out, + ); + kiss::frame_with_command_into( + rnode::CMD_BANDWIDTH, + &config.bandwidth.to_be_bytes(), + &mut out, + ); + kiss::frame_with_command_into(rnode::CMD_SF, &[config.spreading_factor], &mut out); + kiss::frame_with_command_into(rnode::CMD_CR, &[config.coding_rate], &mut out); + kiss::frame_with_command_into(rnode::CMD_TXPOWER, &[config.tx_power], &mut out); + if let Some(st) = config.st_alock { + let at = (st * 100.0) as u16; + let c1 = (at >> 8) as u8; + let c2 = (at & 0xFF) as u8; + kiss::frame_with_command_into(rnode::CMD_ST_ALOCK, &[c1, c2], &mut out); + } + if let Some(lt) = config.lt_alock { + let at = (lt * 100.0) as u16; + let c1 = (at >> 8) as u8; + let c2 = (at & 0xFF) as u8; + kiss::frame_with_command_into(rnode::CMD_LT_ALOCK, &[c1, c2], &mut out); + } + kiss::frame_with_command_into(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON], &mut out); + + out +} + +pub fn build_detect_sequence() -> Vec { + let mut out = Vec::with_capacity(40); + kiss::frame_with_command_into(rnode::CMD_DETECT, &[rnode::DETECT_REQ], &mut out); + kiss::frame_with_command_into(rnode::CMD_FW_VERSION, &[0x00], &mut out); + kiss::frame_with_command_into(rnode::CMD_PLATFORM, &[0x00], &mut out); + kiss::frame_with_command_into(rnode::CMD_MCU, &[0x00], &mut out); + kiss::frame_with_command_into(CMD_INTERFACES, &[0x00], &mut out); + out +} + +/// Wire form: `[FEND][CMD_SEL_INT][index][FEND][FEND][CMD_DATA][escaped_data][FEND]`. +pub fn build_subinterface_data_frame(index: u8, data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(8 + data.len() + data.len() / 8); + kiss::frame_with_command_into(CMD_SEL_INT, &[index], &mut out); + kiss::frame_into(data, &mut out); + out +} + +pub fn command_to_subinterface(cmd_byte: u8) -> Option { + for (i, &port_cmd) in CMD_INT_DATA.iter().enumerate() { + if cmd_byte == port_cmd { + return Some(i); + } + } + None +} + +struct WriteRequest { + index: u8, + /// Raw payload, not yet KISS-escaped. + data: Bytes, + flow_control: bool, +} + +#[derive(Default)] +struct SubInterfaceSignal { + last_rssi: Option, + last_snr: Option, +} + +const RNODE_READ_TIMEOUT_MS: u64 = 100; + +/// Spawn one RNodeMulti over a single serial port. +/// +/// Returns one `InterfaceHandle` per configured sub-interface. Each handle has +/// its own tx channel and `InterfaceId`; all of them share one serial +/// connection and one online flag, so the whole device goes up or down atomically. +/// +/// `ids.len()` must equal `config.subinterfaces.len()`. +pub async fn spawn_rnode_multi_interface( + config: RNodeMultiConfig, + ids: &[InterfaceId], + transport_tx: mpsc::Sender, +) -> Result, InterfaceError> { + if config.subinterfaces.is_empty() { + return Err(InterfaceError::SendFailed( + "RNodeMulti: no sub-interfaces configured".to_string(), + )); + } + if ids.len() != config.subinterfaces.len() { + return Err(InterfaceError::SendFailed(format!( + "RNodeMulti: {} IDs provided but {} sub-interfaces configured", + ids.len(), + config.subinterfaces.len() + ))); + } + if config.subinterfaces.len() > MAX_SUBINTERFACES { + return Err(InterfaceError::SendFailed(format!( + "RNodeMulti: {} sub-interfaces exceeds max {}", + config.subinterfaces.len(), + MAX_SUBINTERFACES + ))); + } + + for sub in &config.subinterfaces { + sub.validate() + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti config: {}", e)))?; + } + + let port = serialport::new(&config.port, config.baud_rate) + .timeout(Duration::from_millis(RNODE_READ_TIMEOUT_MS)) + .open() + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti open: {}", e)))?; + + tracing::info!( + name = %config.name, + port = %config.port, + subinterfaces = config.subinterfaces.len(), + "RNodeMulti interface opened" + ); + + { + let mut detect_port = port + .try_clone() + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?; + let detect_seq = build_detect_sequence(); + use std::io::Write; + detect_port + .write_all(&detect_seq) + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect write: {}", e)))?; + detect_port + .flush() + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect flush: {}", e)))?; + } + + { + let mut init_port = port + .try_clone() + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?; + let mut init_seq = Vec::new(); + for sub in &config.subinterfaces { + init_seq.extend_from_slice(&build_subinterface_init(sub.vport, sub)); + } + use std::io::Write; + init_port + .write_all(&init_seq) + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init write: {}", e)))?; + init_port + .flush() + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init flush: {}", e)))?; + } + + let online = Arc::new(AtomicBool::new(true)); + + let num_subs = config.subinterfaces.len(); + + // All sub-interface handles funnel into one writer so CMD_SEL_INT framing + // stays ordered relative to each data frame. + let (write_tx, mut write_rx) = mpsc::channel::(256); + + let mut handles = Vec::with_capacity(num_subs); + let mut sub_txb: Vec> = Vec::with_capacity(num_subs); + let mut sub_rxb: Vec> = Vec::with_capacity(num_subs); + + for (i, sub_cfg) in config.subinterfaces.iter().enumerate() { + let bitrate = rnode::calculate_bitrate( + sub_cfg.spreading_factor, + sub_cfg.coding_rate, + sub_cfg.bandwidth, + ); + + let rxb = Arc::new(AtomicU64::new(0)); + let txb = Arc::new(AtomicU64::new(0)); + sub_rxb.push(rxb.clone()); + sub_txb.push(txb.clone()); + + // Adapt the per-handle `Vec` channel into the shared WriteRequest + // channel so the handle type stays symmetric with other interfaces. + let (sub_tx, mut sub_rx) = mpsc::channel::(256); + let write_tx_clone = write_tx.clone(); + let vport = sub_cfg.vport; + let sub_flow_control = config.flow_control || sub_cfg.flow_control; + let txb_fwd = txb.clone(); + + tokio::spawn(async move { + while let Some(data) = sub_rx.recv().await { + txb_fwd.fetch_add(data.len() as u64, Ordering::Relaxed); + if write_tx_clone + .send(WriteRequest { + index: vport, + data, + flow_control: sub_flow_control, + }) + .await + .is_err() + { + break; + } + } + }); + + let sub_name = format!("{}[{}]", config.name, sub_cfg.name); + + tracing::info!( + name = %sub_name, + vport = vport, + freq = sub_cfg.frequency, + bw = sub_cfg.bandwidth, + sf = sub_cfg.spreading_factor, + cr = sub_cfg.coding_rate, + bitrate_bps = bitrate, + "RNodeMulti sub-interface configured" + ); + + // The real read loop is shared by all sub-interfaces; each handle just + // needs a JoinHandle that exits when the device goes offline. + let online_sub = online.clone(); + let sub_read_task = tokio::spawn(async move { + loop { + if !online_sub.load(Ordering::SeqCst) { + break; + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + }); + + handles.push(InterfaceHandle { + id: ids[i], + name: sub_name, + mode: sub_cfg.mode, + direction: InterfaceDirection { + inbound: true, + outbound: sub_cfg.outgoing, + forward: false, + repeat: false, + }, + bitrate, + mtu: rns_wire::constants::MTU as u32, + online: online.clone(), + rxb: Some(rxb), + txb: Some(txb), + tx: sub_tx, + read_task: sub_read_task, + }); + } + + // Drop our clone so the writer exits once every sub-interface handle drops. + drop(write_tx); + + let port_write = port + .try_clone() + .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?; + let online_w = online.clone(); + let ready = Arc::new(AtomicBool::new(true)); + let ready_w = ready.clone(); + + tokio::spawn(async move { + let mut port_w = port_write; + while let Some(req) = write_rx.recv().await { + if !online_w.load(Ordering::SeqCst) { + break; + } + + if req.flow_control { + // Bound CMD_READY wait at ~5 s so a stuck TNC can't block tx. + let mut wait_count = 0; + while !ready_w.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + wait_count += 1; + if !online_w.load(Ordering::SeqCst) || wait_count > 500 { + break; + } + } + } + + let frame = build_subinterface_data_frame(req.index, &req.data); + let online_ref = online_w.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::io::Write; + port_w.write_all(&frame)?; + port_w.flush()?; + Ok::<_, std::io::Error>(port_w) + }) + .await; + match result { + Ok(Ok(p)) => { + port_w = p; + } + Ok(Err(e)) => { + tracing::warn!(error = %e, "RNodeMulti write error"); + online_ref.store(false, Ordering::SeqCst); + break; + } + Err(e) => { + tracing::warn!(error = %e, "RNodeMulti write task panicked"); + break; + } + } + } + }); + + let online_r = online.clone(); + let ready_r = ready; + let parent_name = config.name.clone(); + + // `vport_map[vport] -> Some(local_index)` for configured sub-interfaces. + let mut vport_map: [Option; 12] = [None; 12]; + let mut sub_ids: Vec = Vec::with_capacity(num_subs); + for (i, sub_cfg) in config.subinterfaces.iter().enumerate() { + let vp = sub_cfg.vport as usize; + if vp < 12 { + vport_map[vp] = Some(i); + } + sub_ids.push(ids[i]); + } + + tokio::spawn(async move { + let mut port_r = port; + let mut deframer = kiss::RawKissDeframer::new(); + let mut buf = [0u8; 1024]; + + let mut signals: Vec = (0..num_subs) + .map(|_| SubInterfaceSignal::default()) + .collect(); + + // Which sub-interface the device is currently addressing via + // CMD_SEL_INT; status commands below target this index. + let mut selected_index: usize = 0; + + let mut interfaces_buf: Vec = Vec::new(); + + loop { + if !online_r.load(Ordering::SeqCst) { + break; + } + + let result = tokio::task::spawn_blocking(move || { + use std::io::Read; + match port_r.read(&mut buf) { + Ok(n) => Ok((port_r, buf, n)), + Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)), + Err(e) => Err((port_r, e)), + } + }) + .await; + + match result { + Ok(Ok((p, b, n))) => { + port_r = p; + buf = b; + if n == 0 { + continue; + } + + for (raw_cmd, frame) in deframer.feed(&buf[..n]) { + if let Some(vport) = command_to_subinterface(raw_cmd) { + if frame.is_empty() { + continue; + } + if let Some(local_idx) = vport_map[vport] { + sub_rxb[local_idx].fetch_add(frame.len() as u64, Ordering::Relaxed); + + let rssi = signals[local_idx].last_rssi.take(); + let snr = signals[local_idx].last_snr.take(); + + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id: sub_ids[local_idx], + rssi, + snr, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!( + parent = %parent_name, + "transport channel closed" + ); + online_r.store(false, Ordering::SeqCst); + return; + } + } else { + tracing::debug!( + parent = %parent_name, + vport, + "data for unconfigured sub-interface, dropping" + ); + } + continue; + } + + match raw_cmd { + CMD_SEL_INT => { + // Device echoes selection before emitting any + // status/config responses for that sub-interface. + if let Some(&idx) = frame.first() { + selected_index = idx as usize; + } + } + + rnode::CMD_STAT_RSSI => { + if !frame.is_empty() { + let rssi = frame[0] as i8 as f32; + if let Some(local_idx) = + vport_map.get(selected_index).copied().flatten() + { + signals[local_idx].last_rssi = Some(rssi); + } + } + } + rnode::CMD_STAT_SNR => { + if !frame.is_empty() { + let snr = frame[0] as i8 as f32 / 4.0; + if let Some(local_idx) = + vport_map.get(selected_index).copied().flatten() + { + signals[local_idx].last_snr = Some(snr); + } + } + } + + rnode::CMD_READY => { + let is_ready = frame.first().copied().unwrap_or(0) != 0; + ready_r.store(is_ready, Ordering::SeqCst); + } + + rnode::CMD_DETECT => { + if frame.first().copied() == Some(rnode::DETECT_RESP) { + tracing::info!( + parent = %parent_name, + "RNodeMulti device detected" + ); + } + } + + rnode::CMD_FW_VERSION => { + if frame.len() >= 2 { + let major = frame[0]; + let minor = frame[1]; + tracing::info!( + parent = %parent_name, + major, minor, + "RNodeMulti firmware version {}.{}", + major, minor, + ); + if major < REQUIRED_FW_VER_MAJ + || (major == REQUIRED_FW_VER_MAJ + && minor < REQUIRED_FW_VER_MIN) + { + tracing::warn!( + parent = %parent_name, + "RNodeMulti firmware {}.{} below required {}.{}", + major, minor, + REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN, + ); + } + } + } + + rnode::CMD_RADIO_STATE => { + if let Some(local_idx) = + vport_map.get(selected_index).copied().flatten() + { + if frame.first().copied() == Some(rnode::RADIO_STATE_ON) { + tracing::info!( + parent = %parent_name, + subinterface = local_idx, + vport = selected_index, + "RNodeMulti sub-interface radio online" + ); + } else { + tracing::warn!( + parent = %parent_name, + subinterface = local_idx, + vport = selected_index, + "RNodeMulti sub-interface radio offline" + ); + } + } + } + + rnode::CMD_FREQUENCY => { + if frame.len() >= 4 { + let freq = u32::from_be_bytes([ + frame[0], frame[1], frame[2], frame[3], + ]); + tracing::debug!( + parent = %parent_name, + vport = selected_index, + freq_mhz = format!("{:.3}", freq as f64 / 1_000_000.0), + "Radio reporting frequency" + ); + } + } + + rnode::CMD_BANDWIDTH => { + if frame.len() >= 4 { + let bw = u32::from_be_bytes([ + frame[0], frame[1], frame[2], frame[3], + ]); + tracing::debug!( + parent = %parent_name, + vport = selected_index, + bw_khz = format!("{:.1}", bw as f64 / 1000.0), + "Radio reporting bandwidth" + ); + } + } + + rnode::CMD_SF => { + if !frame.is_empty() { + tracing::debug!( + parent = %parent_name, + vport = selected_index, + sf = frame[0], + "Radio reporting spreading factor" + ); + } + } + + rnode::CMD_CR => { + if !frame.is_empty() { + tracing::debug!( + parent = %parent_name, + vport = selected_index, + cr = frame[0], + "Radio reporting coding rate" + ); + } + } + + rnode::CMD_TXPOWER => { + if !frame.is_empty() { + let txp = frame[0] as i8; + tracing::debug!( + parent = %parent_name, + vport = selected_index, + txpower_dbm = txp, + "Radio reporting TX power" + ); + } + } + + rnode::CMD_ST_ALOCK => { + if frame.len() >= 2 { + let at = ((frame[0] as u16) << 8) | frame[1] as u16; + let pct = at as f32 / 100.0; + tracing::debug!( + parent = %parent_name, + vport = selected_index, + "RNodeMulti short-term airtime limit: {:.2}%", pct, + ); + } + } + + rnode::CMD_LT_ALOCK => { + if frame.len() >= 2 { + let at = ((frame[0] as u16) << 8) | frame[1] as u16; + let pct = at as f32 / 100.0; + tracing::debug!( + parent = %parent_name, + vport = selected_index, + "RNodeMulti long-term airtime limit: {:.2}%", pct, + ); + } + } + + rnode::CMD_PLATFORM => { + if !frame.is_empty() { + tracing::debug!( + parent = %parent_name, + platform = format!("0x{:02X}", frame[0]), + "RNodeMulti platform" + ); + } + } + + rnode::CMD_MCU => { + if !frame.is_empty() { + tracing::debug!( + parent = %parent_name, + mcu = format!("0x{:02X}", frame[0]), + "RNodeMulti MCU" + ); + } + } + + CMD_INTERFACES => { + // Reply is a stream of 2-byte `[vport, radio_type]` + // pairs, one per radio module; accumulate then pop. + interfaces_buf.extend_from_slice(&frame); + if interfaces_buf.len() >= 2 { + let vp = interfaces_buf[0]; + let rt = interfaces_buf[1]; + let rtype = RadioType::from_u8(rt) + .map(|r| r.family_name().to_string()) + .unwrap_or_else(|| format!("unknown(0x{:02X})", rt)); + tracing::info!( + parent = %parent_name, + vport = vp, + radio_type = %rtype, + "RNodeMulti radio module reported" + ); + interfaces_buf.clear(); + } + } + + CMD_ERROR => { + if !frame.is_empty() { + match frame[0] { + ERROR_INITRADIO => { + tracing::error!( + parent = %parent_name, + "RNodeMulti hardware initialisation error" + ); + } + ERROR_TXFAILED => { + tracing::error!( + parent = %parent_name, + "RNodeMulti hardware TX error" + ); + } + code => { + tracing::error!( + parent = %parent_name, + code = format!("0x{:02X}", code), + "RNodeMulti hardware error" + ); + } + } + } + } + + rnode::CMD_RESET => { + if frame.first().copied() == Some(0xF8) { + tracing::error!( + parent = %parent_name, + "RNodeMulti device reset detected" + ); + online_r.store(false, Ordering::SeqCst); + return; + } + } + + _ => { + tracing::debug!( + parent = %parent_name, + cmd = format!("0x{:02X}", raw_cmd), + "RNodeMulti: ignoring KISS command" + ); + } + } + } + } + Ok(Err((_p, e))) => { + tracing::warn!( + parent = %parent_name, + error = %e, + "RNodeMulti read error" + ); + online_r.store(false, Ordering::SeqCst); + return; + } + Err(e) => { + tracing::warn!( + parent = %parent_name, + error = %e, + "RNodeMulti read task panicked" + ); + online_r.store(false, Ordering::SeqCst); + return; + } + } + } + }); + + Ok(handles) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_rnode_multi_config() { + let mut cfg = RNodeMultiConfig::new("multi0", "/dev/ttyACM0"); + assert_eq!(cfg.baud_rate, 115200); + assert!(!cfg.flow_control); + assert!(cfg.subinterfaces.is_empty()); + + cfg.subinterfaces + .push(SubInterfaceConfig::new("radio0", 0, 868_000_000)); + cfg.subinterfaces + .push(SubInterfaceConfig::new("radio1", 1, 915_000_000)); + assert_eq!(cfg.subinterfaces.len(), 2); + assert!(cfg.subinterfaces.iter().all(|sub| sub.outgoing)); + assert!(cfg.subinterfaces.iter().all(|sub| !sub.flow_control)); + } + + #[test] + fn test_subinterface_init_sequence() { + let sub_cfg = SubInterfaceConfig::new("radio0", 0, 868_000_000); + let seq = build_subinterface_init(0, &sub_cfg); + assert!(!seq.is_empty()); + + let mut deframer = kiss::KissDeframer::new(); + let frames = deframer.feed(&seq); + // sel_int + freq + bw + sf + cr + txpower + radio_state + assert_eq!(frames.len(), 7); + } + + #[test] + fn test_subinterface_init_with_airtime() { + let mut sub_cfg = SubInterfaceConfig::new("radio0", 0, 868_000_000); + sub_cfg.st_alock = Some(15.0); + sub_cfg.lt_alock = Some(25.0); + + let seq = build_subinterface_init(0, &sub_cfg); + let mut deframer = kiss::KissDeframer::new(); + let frames = deframer.feed(&seq); + // 7 base + 2 airtime limits + assert_eq!(frames.len(), 9); + } + + #[test] + fn test_command_to_subinterface() { + assert_eq!(command_to_subinterface(0x00), Some(0)); + assert_eq!(command_to_subinterface(0x10), Some(1)); + assert_eq!(command_to_subinterface(0x20), Some(2)); + assert_eq!(command_to_subinterface(0x70), Some(3)); + assert_eq!(command_to_subinterface(0x75), Some(4)); + assert_eq!(command_to_subinterface(0x90), Some(5)); + assert_eq!(command_to_subinterface(0xA0), Some(6)); + assert_eq!(command_to_subinterface(0xB0), Some(7)); + assert_eq!(command_to_subinterface(0xC0), Some(8)); + assert_eq!(command_to_subinterface(0xD0), Some(9)); + assert_eq!(command_to_subinterface(0xE0), Some(10)); + assert_eq!(command_to_subinterface(0xF0), Some(11)); + assert_eq!(command_to_subinterface(0x55), None); + assert_eq!(command_to_subinterface(0xFF), None); + assert_eq!(command_to_subinterface(0x01), None); + } + + #[test] + fn test_radio_type() { + assert_eq!(RadioType::from_u8(0x00), Some(RadioType::SX127X)); + assert_eq!(RadioType::from_u8(0x11), Some(RadioType::SX1262)); + assert_eq!(RadioType::from_u8(0x21), Some(RadioType::SX1280)); + assert_eq!(RadioType::from_u8(0xFF), None); + + assert_eq!(RadioType::SX127X.family_name(), "SX127X"); + assert_eq!(RadioType::SX1262.family_name(), "SX126X"); + assert_eq!(RadioType::SX1280.family_name(), "SX128X"); + } + + #[test] + fn test_radio_type_frequency_validation() { + let sx127x = RadioType::SX127X; + assert!(sx127x.validate_frequency(868_000_000)); + assert!(sx127x.validate_frequency(915_000_000)); + assert!(sx127x.validate_frequency(137_000_000)); + assert!(sx127x.validate_frequency(1_000_000_000)); + assert!(!sx127x.validate_frequency(136_999_999)); + assert!(!sx127x.validate_frequency(1_000_000_001)); + + let sx1280 = RadioType::SX1280; + assert!(sx1280.validate_frequency(2_400_000_000)); + assert!(!sx1280.validate_frequency(868_000_000)); + } + + #[test] + fn test_max_subinterfaces() { + assert_eq!(MAX_SUBINTERFACES, 11); + assert_eq!(CMD_INT_DATA.len(), 12); + } + + #[test] + fn test_detect_sequence() { + let seq = build_detect_sequence(); + assert!(!seq.is_empty()); + let mut deframer = kiss::KissDeframer::new(); + let frames = deframer.feed(&seq); + // DETECT + FW_VERSION + PLATFORM + MCU + INTERFACES + assert_eq!(frames.len(), 5); + } + + #[test] + fn test_build_subinterface_data_frame() { + let data = b"hello radio"; + let frame = build_subinterface_data_frame(2, data); + assert!(!frame.is_empty()); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&frame); + // CMD_SEL_INT then CMD_DATA + assert_eq!(frames.len(), 2); + assert_eq!(frames[0].0, CMD_SEL_INT); + assert_eq!(frames[0].1, &[2u8]); + assert_eq!(frames[1].0, kiss::CMD_DATA); + assert_eq!(frames[1].1, data); + } + + #[test] + fn test_raw_kiss_deframer_preserves_command() { + // CMD_INT5_DATA = 0x90 collides with CMD_ERROR after masking; the raw + // deframer must keep the high nibble intact. + let payload = b"test data"; + let mut raw_frame = Vec::new(); + raw_frame.push(kiss::FEND); + raw_frame.push(0x90); + raw_frame.extend_from_slice(&kiss::escape(payload)); + raw_frame.push(kiss::FEND); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&raw_frame); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].0, 0x90); + assert_eq!(frames[0].1, payload); + + assert_eq!(command_to_subinterface(0x90), Some(5)); + } + + #[test] + fn test_raw_kiss_deframer_streaming() { + let payload = b"streamed"; + let mut raw_frame = Vec::new(); + raw_frame.push(kiss::FEND); + raw_frame.push(0xA0); + raw_frame.extend_from_slice(&kiss::escape(payload)); + raw_frame.push(kiss::FEND); + + let mid = raw_frame.len() / 2; + let mut deframer = kiss::RawKissDeframer::new(); + + let f1 = deframer.feed(&raw_frame[..mid]); + assert!(f1.is_empty()); + + let f2 = deframer.feed(&raw_frame[mid..]); + assert_eq!(f2.len(), 1); + assert_eq!(f2[0].0, 0xA0); + assert_eq!(f2[0].1, payload); + } + + #[test] + fn test_raw_kiss_deframer_multiple_frames() { + let mut stream = vec![ + kiss::FEND, + CMD_SEL_INT, + 3, + kiss::FEND, + kiss::FEND, + rnode::CMD_STAT_RSSI, + 0x80, + kiss::FEND, + kiss::FEND, + 0x70, + ]; + stream.extend_from_slice(b"packet"); + stream.push(kiss::FEND); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&stream); + assert_eq!(frames.len(), 3); + + assert_eq!(frames[0].0, CMD_SEL_INT); + assert_eq!(frames[0].1, &[3u8]); + + assert_eq!(frames[1].0, rnode::CMD_STAT_RSSI); + assert_eq!(frames[1].1, &[0x80u8]); + + assert_eq!(frames[2].0, 0x70); + assert_eq!(frames[2].1, b"packet"); + } + + #[test] + fn test_raw_kiss_deframer_escape_handling() { + let raw_frame = vec![ + kiss::FEND, + 0xB0, + kiss::FESC, + kiss::TFEND, + kiss::FESC, + kiss::TFESC, + 0x42, + kiss::FEND, + ]; + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&raw_frame); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].0, 0xB0); + assert_eq!(frames[0].1, &[kiss::FEND, kiss::FESC, 0x42]); + } + + #[test] + fn test_subinterface_config_validate() { + let cfg = SubInterfaceConfig::new("radio0", 0, 868_000_000); + assert!(cfg.validate().is_ok()); + + let mut bad = SubInterfaceConfig::new("radio0", 0, 868_000_000); + bad.spreading_factor = 13; + assert!(bad.validate().is_err()); + + let mut bad = SubInterfaceConfig::new("radio0", 0, 868_000_000); + bad.coding_rate = 9; + assert!(bad.validate().is_err()); + + let mut bad = SubInterfaceConfig::new("radio0", 0, 868_000_000); + bad.bandwidth = 1000; + assert!(bad.validate().is_err()); + + let mut bad = SubInterfaceConfig::new("radio0", 0, 868_000_000); + bad.bandwidth = 2_000_000; + assert!(bad.validate().is_err()); + + let mut bad = SubInterfaceConfig::new("radio0", 0, 868_000_000); + bad.st_alock = Some(101.0); + assert!(bad.validate().is_err()); + + let bad = SubInterfaceConfig::new("radio0", 12, 868_000_000); + assert!(bad.validate().is_err()); + } + + #[test] + fn test_subinterface_config_validate_edge_cases() { + let mut cfg = SubInterfaceConfig::new("radio0", 0, 868_000_000); + cfg.spreading_factor = 5; + cfg.coding_rate = 5; + cfg.bandwidth = 7800; + assert!(cfg.validate().is_ok()); + + cfg.spreading_factor = 12; + cfg.coding_rate = 8; + cfg.bandwidth = 1_625_000; + cfg.st_alock = Some(100.0); + cfg.lt_alock = Some(100.0); + assert!(cfg.validate().is_ok()); + + cfg.st_alock = Some(0.0); + cfg.lt_alock = Some(0.0); + assert!(cfg.validate().is_ok()); + + cfg.st_alock = Some(-1.0); + assert!(cfg.validate().is_err()); + } + + #[test] + fn test_multi_detect_sequence_includes_interfaces_query() { + let seq = build_detect_sequence(); + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&seq); + + assert_eq!(frames.len(), 5); + assert_eq!(frames[0].0, rnode::CMD_DETECT); + assert_eq!(frames[1].0, rnode::CMD_FW_VERSION); + assert_eq!(frames[2].0, rnode::CMD_PLATFORM); + assert_eq!(frames[3].0, rnode::CMD_MCU); + assert_eq!(frames[4].0, CMD_INTERFACES); + } + + #[test] + fn test_data_frame_roundtrip() { + let payload = vec![0xAA, 0xBB, 0xCC, 0xDD]; + let frame = build_subinterface_data_frame(1, &payload); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&frame); + assert_eq!(frames.len(), 2); + + assert_eq!(frames[0].0, CMD_SEL_INT); + assert_eq!(frames[0].1, &[1u8]); + + assert_eq!(frames[1].0, kiss::CMD_DATA); + assert_eq!(frames[1].1, payload); + } + + #[test] + fn test_data_frame_with_escape_chars() { + let payload = vec![kiss::FEND, kiss::FESC, 0x42, kiss::FEND]; + let frame = build_subinterface_data_frame(0, &payload); + + let mut deframer = kiss::RawKissDeframer::new(); + let frames = deframer.feed(&frame); + assert_eq!(frames.len(), 2); + assert_eq!(frames[1].0, kiss::CMD_DATA); + assert_eq!(frames[1].1, payload); + } + + #[test] + fn test_all_subinterface_data_commands_unique() { + for (i, lhs) in CMD_INT_DATA.iter().enumerate() { + for (j, rhs) in CMD_INT_DATA.iter().enumerate().skip(i + 1) { + assert_ne!( + lhs, rhs, + "CMD_INT_DATA[{}] == CMD_INT_DATA[{}] == 0x{:02X}", + i, j, *lhs + ); + } + } + } + + #[test] + fn test_data_commands_dont_collide_with_control_commands() { + let control_cmds = [ + CMD_SEL_INT, + rnode::CMD_STAT_RSSI, + rnode::CMD_STAT_SNR, + rnode::CMD_READY, + rnode::CMD_DETECT, + rnode::CMD_FW_VERSION, + rnode::CMD_RADIO_STATE, + rnode::CMD_FREQUENCY, + rnode::CMD_BANDWIDTH, + rnode::CMD_SF, + rnode::CMD_CR, + rnode::CMD_TXPOWER, + rnode::CMD_ST_ALOCK, + rnode::CMD_LT_ALOCK, + rnode::CMD_PLATFORM, + rnode::CMD_MCU, + CMD_INTERFACES, + rnode::CMD_RESET, + ]; + + for &data_cmd in &CMD_INT_DATA { + for &ctrl_cmd in &control_cmds { + // CMD_INT0_DATA == CMD_DATA (0x00) and CMD_INT5_DATA == + // CMD_ERROR (0x90) are known, intentional overlaps; the read + // loop disambiguates by checking data commands first. + if data_cmd == 0x00 || data_cmd == 0x90 { + continue; + } + assert_ne!( + data_cmd, ctrl_cmd, + "CMD_INT_DATA 0x{:02X} collides with control cmd 0x{:02X}", + data_cmd, ctrl_cmd + ); + } + } + } +} diff --git a/crates/rns-interface/src/serial.rs b/crates/rns-interface/src/serial.rs new file mode 100644 index 0000000..d703506 --- /dev/null +++ b/crates/rns-interface/src/serial.rs @@ -0,0 +1,222 @@ +//! HDLC-framed data over a serial port. Uses `serialport` with +//! `spawn_blocking` because no mature async driver exists yet. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use bytes::Bytes; +use tokio::sync::mpsc; + +use crate::hdlc; +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const DEFAULT_BAUD: u32 = 9600; + +const SERIAL_READ_TIMEOUT_MS: u64 = 100; + +#[derive(Debug, Clone)] +pub struct SerialConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + pub data_bits: serialport::DataBits, + pub parity: serialport::Parity, + pub stop_bits: serialport::StopBits, + pub mode: InterfaceMode, +} + +impl SerialConfig { + pub fn new(name: &str, port: &str) -> Self { + Self { + name: name.to_string(), + port: port.to_string(), + baud_rate: DEFAULT_BAUD, + data_bits: serialport::DataBits::Eight, + parity: serialport::Parity::None, + stop_bits: serialport::StopBits::One, + mode: InterfaceMode::Full, + } + } + + pub fn baud(mut self, baud: u32) -> Self { + self.baud_rate = baud; + self + } +} + +pub async fn spawn_serial_interface( + config: SerialConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let port = serialport::new(&config.port, config.baud_rate) + .data_bits(config.data_bits) + .parity(config.parity) + .stop_bits(config.stop_bits) + .timeout(Duration::from_millis(SERIAL_READ_TIMEOUT_MS)) + .open() + .map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial open: {}", e)))?; + + tracing::info!( + name = %config.name, + port = %config.port, + baud = config.baud_rate, + "serial interface opened" + ); + + let online = Arc::new(AtomicBool::new(true)); + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let (tx, mut rx) = mpsc::channel::(256); + let name = config.name.clone(); + let mode = config.mode; + + let port_write = port + .try_clone() + .map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial clone: {}", e)))?; + + let online_w = online.clone(); + let txb_w = shared_txb.clone(); + tokio::spawn(async move { + let mut port_w = port_write; + while let Some(data) = rx.recv().await { + txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed); + let framed = hdlc::frame(&data); + let online_ref = online_w.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::io::Write; + port_w.write_all(&framed)?; + port_w.flush()?; + Ok::<_, std::io::Error>(port_w) + }) + .await; + match result { + Ok(Ok(p)) => { + port_w = p; + } + Ok(Err(e)) => { + tracing::warn!(error = %e, "serial write error"); + online_ref.store(false, Ordering::SeqCst); + break; + } + Err(e) => { + tracing::warn!(error = %e, "serial write task panicked"); + break; + } + } + } + }); + + let online_r = online.clone(); + let rxb_r = shared_rxb.clone(); + let read_task = tokio::spawn(async move { + let mut port_r = port; + let mut deframer = hdlc::HdlcDeframer::new(); + let mut buf = [0u8; 1024]; + + loop { + if !online_r.load(Ordering::SeqCst) { + break; + } + let result = tokio::task::spawn_blocking(move || { + use std::io::Read; + match port_r.read(&mut buf) { + Ok(n) => Ok((port_r, buf, n)), + Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)), + Err(e) => Err((port_r, e)), + } + }) + .await; + + match result { + Ok(Ok((p, b, n))) => { + port_r = p; + buf = b; + if n > 0 { + rxb_r.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); + for frame in deframer.feed(&buf[..n]) { + if frame.is_empty() { + continue; + } + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id: id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + } + } + Ok(Err((_p, e))) => { + tracing::warn!(error = %e, "serial read error"); + online_r.store(false, Ordering::SeqCst); + return; + } + Err(e) => { + tracing::warn!(error = %e, "serial read task panicked"); + online_r.store(false, Ordering::SeqCst); + return; + } + } + } + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: config.baud_rate as u64, + mtu: 564, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_serial_config() { + let cfg = SerialConfig::new("serial0", "/dev/ttyUSB0").baud(115200); + assert_eq!(cfg.baud_rate, 115200); + assert_eq!(cfg.port, "/dev/ttyUSB0"); + } + + #[test] + fn test_serial_config_custom_baud() { + let cfg = SerialConfig::new("ser0", "/dev/ttyUSB0").baud(9600); + assert_eq!(cfg.baud_rate, 9600); + } + + #[test] + fn test_serial_config_default_mode() { + let cfg = SerialConfig::new("ser0", "/dev/ttyUSB0"); + assert_eq!(cfg.mode, InterfaceMode::Full); + } + + #[test] + fn test_serial_config_builder_chain() { + let cfg = SerialConfig::new("serial0", "/dev/ttyACM0").baud(115200); + assert_eq!(cfg.name, "serial0"); + assert_eq!(cfg.port, "/dev/ttyACM0"); + assert_eq!(cfg.baud_rate, 115200); + } +} diff --git a/crates/rns-interface/src/socket_tuning.rs b/crates/rns-interface/src/socket_tuning.rs new file mode 100644 index 0000000..5b68959 --- /dev/null +++ b/crates/rns-interface/src/socket_tuning.rs @@ -0,0 +1,208 @@ +//! Shared TCP socket tuning for [`crate::tcp`] and [`crate::backbone`]. +//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux +//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT. +//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key. + +use std::net::IpAddr; +use std::time::Duration; + +use tokio::net::TcpStream; + +/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`]. +#[cfg(unix)] +pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> { + use std::os::fd::{AsRawFd, FromRawFd}; + let raw_fd = stream.as_ref().as_raw_fd(); + // SAFETY: we borrow the fd without taking ownership (ManuallyDrop ensures + // the socket2::Socket destructor does not close the fd). + let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) }); + sock.set_keepalive(true)?; + Ok(()) +} + +#[cfg(windows)] +pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> { + use std::os::windows::io::{AsRawSocket, FromRawSocket}; + let raw = stream.as_ref().as_raw_socket(); + let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) }); + sock.set_keepalive(true)?; + Ok(()) +} + +/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort. +#[cfg(unix)] +pub fn set_keepalive_tuned( + stream: &TcpStream, + idle: Duration, + intvl: Duration, + retries: u32, + user_timeout: Duration, +) { + use std::os::fd::{AsRawFd, FromRawFd}; + let raw_fd = stream.as_ref().as_raw_fd(); + let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) }); + apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout); +} + +#[cfg(windows)] +pub fn set_keepalive_tuned( + stream: &TcpStream, + idle: Duration, + intvl: Duration, + retries: u32, + user_timeout: Duration, +) { + use std::os::windows::io::{AsRawSocket, FromRawSocket}; + let raw = stream.as_ref().as_raw_socket(); + let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) }); + apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout); +} + +fn apply_tuned_keepalive( + sock: &socket2::Socket, + idle: Duration, + intvl: Duration, + retries: u32, + user_timeout: Duration, +) { + let ka = socket2::TcpKeepalive::new().with_time(idle); + #[cfg(any(unix, windows))] + let ka = ka.with_interval(intvl); + #[cfg(not(any(unix, windows)))] + let _ = intvl; + #[cfg(unix)] + let ka = ka.with_retries(retries); + #[cfg(not(unix))] + let _ = retries; + + if let Err(e) = sock.set_tcp_keepalive(&ka) { + tracing::warn!(error = %e, "set_tcp_keepalive failed"); + } + + // TCP_USER_TIMEOUT — Linux-family only. + #[cfg(any(target_os = "linux", target_os = "android", target_os = "fuchsia"))] + if let Err(e) = sock.set_tcp_user_timeout(Some(user_timeout)) { + tracing::warn!(error = %e, "set_tcp_user_timeout failed"); + } + #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "fuchsia")))] + let _ = user_timeout; +} + +/// Raise TCP send/recv buffers; best-effort. +#[cfg(unix)] +pub fn set_socket_buffers(stream: &TcpStream, size: usize) { + use std::os::fd::{AsRawFd, FromRawFd}; + let raw_fd = stream.as_ref().as_raw_fd(); + let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) }); + let _ = sock.set_recv_buffer_size(size); + let _ = sock.set_send_buffer_size(size); +} + +#[cfg(windows)] +pub fn set_socket_buffers(stream: &TcpStream, size: usize) { + use std::os::windows::io::{AsRawSocket, FromRawSocket}; + let raw = stream.as_ref().as_raw_socket(); + let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) }); + let _ = sock.set_recv_buffer_size(size); + let _ = sock.set_send_buffer_size(size); +} + +/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back +/// to wildcard bind. +pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option { + let ifaces = match if_addrs::get_if_addrs() { + Ok(v) => v, + Err(e) => { + tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed"); + return None; + } + }; + let matches: Vec = ifaces + .into_iter() + .filter(|i| i.name == name) + .map(|i| i.addr.ip()) + .collect(); + if matches.is_empty() { + return None; + } + if prefer_ipv6 { + matches + .iter() + .find(|a| a.is_ipv6()) + .copied() + .or_else(|| matches.first().copied()) + } else { + matches + .iter() + .find(|a| a.is_ipv4()) + .copied() + .or_else(|| matches.first().copied()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::net::TcpListener; + + #[tokio::test] + async fn keepalive_and_buffers_apply_without_panic() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let (server_accept, client_connect) = + tokio::join!(listener.accept(), TcpStream::connect(addr)); + let (server, _) = server_accept.unwrap(); + let client = client_connect.unwrap(); + + set_keepalive(&server).expect("server set_keepalive"); + set_keepalive(&client).expect("client set_keepalive"); + + // Tuned keepalive — must not panic on any platform. + set_keepalive_tuned( + &server, + Duration::from_secs(5), + Duration::from_secs(2), + 12, + Duration::from_secs(24), + ); + set_keepalive_tuned( + &client, + Duration::from_secs(5), + Duration::from_secs(2), + 12, + Duration::from_secs(24), + ); + + set_socket_buffers(&server, 131_072); + set_socket_buffers(&client, 131_072); + } + + #[test] + fn iface_addr_for_loopback_resolves() { + // Loopback name varies by OS; iterate candidates. + let candidates = ["lo", "lo0", "Loopback Pseudo-Interface 1"]; + let mut found_v4 = false; + for name in candidates { + if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false) + && v4.is_loopback() + { + found_v4 = true; + break; + } + } + // Hermetic CI may not expose loopback by name; only assert when seen. + if let Ok(ifaces) = if_addrs::get_if_addrs() + && ifaces.iter().any(|i| candidates.contains(&i.name.as_str())) + { + assert!( + found_v4, + "expected a loopback IPv4 on one of {candidates:?}" + ); + } + } + + #[test] + fn iface_addr_for_missing_returns_none() { + assert!(iface_addr_for("definitely-not-a-real-interface-zzz", false).is_none()); + } +} diff --git a/crates/rns-interface/src/tcp.rs b/crates/rns-interface/src/tcp.rs new file mode 100644 index 0000000..774e165 --- /dev/null +++ b/crates/rns-interface/src/tcp.rs @@ -0,0 +1,799 @@ +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use bytes::Bytes; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::mpsc; + +use crate::hdlc; +use crate::kiss; +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const RECONNECT_WAIT_INITIAL: u64 = 5; +pub const RECONNECT_WAIT_MAX: u64 = 300; +pub const DEFAULT_CONNECT_TIMEOUT: u64 = 5; +pub const DEFAULT_TCP_USER_TIMEOUT: u32 = 24; +/// I2P tunnels need a longer `TCP_USER_TIMEOUT` to absorb latency spikes. +pub const I2P_TCP_USER_TIMEOUT: u32 = 45; + +pub const TCP_HW_MTU: u32 = 262144; + +pub const TCP_KEEPIDLE: u32 = 5; +pub const TCP_KEEPINTVL: u32 = 2; +pub const TCP_KEEPCNT: u32 = 12; + +#[derive(Debug, Clone)] +pub struct TcpClientConfig { + pub name: String, + pub target_host: String, + pub target_port: u16, + pub kiss_framing: bool, + pub connect_timeout_secs: u64, + pub max_reconnect_tries: Option, + pub mode: InterfaceMode, +} + +impl TcpClientConfig { + pub fn new(name: &str, host: &str, port: u16) -> Self { + Self { + name: name.to_string(), + target_host: host.to_string(), + target_port: port, + kiss_framing: false, + connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT, + max_reconnect_tries: None, + mode: InterfaceMode::Full, + } + } +} + +#[derive(Debug, Clone)] +pub struct TcpServerConfig { + pub name: String, + pub listen_ip: String, + pub listen_port: u16, + pub kiss_framing: bool, + pub prefer_ipv6: bool, + pub mode: InterfaceMode, +} + +impl TcpServerConfig { + pub fn new(name: &str, ip: &str, port: u16) -> Self { + Self { + name: name.to_string(), + listen_ip: ip.to_string(), + listen_port: port, + kiss_framing: false, + prefer_ipv6: false, + mode: InterfaceMode::Full, + } + } +} + +pub struct TcpInterfaceState { + pub online: AtomicBool, + pub detached: AtomicBool, + pub rx_bytes: AtomicU64, + pub tx_bytes: AtomicU64, + pub rx_packets: AtomicU64, + pub tx_packets: AtomicU64, + /// Aggregate counters that persist across reconnections. + pub shared_rxb: Option>, + pub shared_txb: Option>, +} + +impl TcpInterfaceState { + pub fn new() -> Arc { + Arc::new(Self { + online: AtomicBool::new(false), + detached: AtomicBool::new(false), + rx_bytes: AtomicU64::new(0), + tx_bytes: AtomicU64::new(0), + rx_packets: AtomicU64::new(0), + tx_packets: AtomicU64::new(0), + shared_rxb: None, + shared_txb: None, + }) + } + + pub fn with_shared_counters(rxb: Arc, txb: Arc) -> Arc { + Arc::new(Self { + online: AtomicBool::new(false), + detached: AtomicBool::new(false), + rx_bytes: AtomicU64::new(0), + tx_bytes: AtomicU64::new(0), + rx_packets: AtomicU64::new(0), + tx_packets: AtomicU64::new(0), + shared_rxb: Some(rxb), + shared_txb: Some(txb), + }) + } + + pub fn record_rx(&self, bytes: usize) { + self.rx_bytes.fetch_add(bytes as u64, Ordering::Relaxed); + self.rx_packets.fetch_add(1, Ordering::Relaxed); + if let Some(shared) = &self.shared_rxb { + shared.fetch_add(bytes as u64, Ordering::Relaxed); + } + } + + pub fn record_tx(&self, bytes: usize) { + self.tx_bytes.fetch_add(bytes as u64, Ordering::Relaxed); + self.tx_packets.fetch_add(1, Ordering::Relaxed); + if let Some(shared) = &self.shared_txb { + shared.fetch_add(bytes as u64, Ordering::Relaxed); + } + } +} + +impl Default for TcpInterfaceState { + fn default() -> Self { + Self { + online: AtomicBool::new(false), + detached: AtomicBool::new(false), + rx_bytes: AtomicU64::new(0), + tx_bytes: AtomicU64::new(0), + rx_packets: AtomicU64::new(0), + tx_packets: AtomicU64::new(0), + shared_rxb: None, + shared_txb: None, + } + } +} + +pub fn frame_for_tcp(data: &[u8], kiss_framing: bool) -> Vec { + if kiss_framing { + crate::kiss::frame(data) + } else { + hdlc::frame(data) + } +} + +use crate::socket_tuning::{set_keepalive, set_socket_buffers}; + +async fn tcp_read_loop( + mut reader: tokio::net::tcp::OwnedReadHalf, + interface_id: InterfaceId, + transport_tx: mpsc::Sender, + state: Arc, + kiss_framing: bool, +) { + let mut buf = [0u8; 32768]; + + if kiss_framing { + let mut deframer = kiss::KissDeframer::new(); + loop { + match reader.read(&mut buf).await { + Ok(0) => { + tracing::info!(interface_id, "TCP read: EOF"); + break; + } + Ok(n) => { + for (_cmd, frame) in deframer.feed(&buf[..n]) { + if frame.is_empty() { + continue; + } + state.record_rx(frame.len()); + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(interface_id, "transport channel closed"); + return; + } + } + } + Err(e) => { + tracing::warn!(interface_id, error = %e, "TCP read error"); + break; + } + } + } + } else { + let mut deframer = hdlc::HdlcDeframer::new(); + loop { + match reader.read(&mut buf).await { + Ok(0) => { + tracing::info!(interface_id, "TCP read: EOF"); + break; + } + Ok(n) => { + for frame in deframer.feed(&buf[..n]) { + if frame.is_empty() { + continue; + } + tracing::debug!( + interface_id, + frame_len = frame.len(), + first_byte = format!("0x{:02x}", frame.first().copied().unwrap_or(0)), + "TCP read: deframed packet" + ); + state.record_rx(frame.len()); + let msg = TransportMessage::Inbound(InboundPacket { + raw: Bytes::from(frame), + interface_id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(interface_id, "transport channel closed"); + return; + } + } + } + Err(e) => { + tracing::warn!(interface_id, error = %e, "TCP read error"); + break; + } + } + } + } + state.online.store(false, Ordering::SeqCst); +} + +async fn tcp_write_loop( + mut writer: tokio::net::tcp::OwnedWriteHalf, + mut rx: mpsc::Receiver, + state: Arc, + kiss_framing: bool, +) { + while let Some(data) = rx.recv().await { + let framed = frame_for_tcp(&data, kiss_framing); + tracing::debug!( + raw_len = data.len(), + framed_len = framed.len(), + first_byte = format!("0x{:02x}", data.first().copied().unwrap_or(0)), + "TCP write: sending frame" + ); + state.record_tx(data.len()); + if let Err(e) = writer.write_all(&framed).await { + tracing::warn!(error = %e, "TCP write error"); + break; + } + } + state.online.store(false, Ordering::SeqCst); +} + +/// Spawn an auto-reconnecting TCP client interface. +pub async fn spawn_tcp_client( + config: TcpClientConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, + _ifac: Option, +) -> Result { + let online = Arc::new(AtomicBool::new(false)); + let online2 = online.clone(); + let (tx, rx) = mpsc::channel::(1024); + let name = config.name.clone(); + let mode = config.mode; + let kiss_framing = config.kiss_framing; + + // Wrap rx so it survives reconnects; forwarder task feeds per-connection channel. + let rx = Arc::new(tokio::sync::Mutex::new(rx)); + + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let task_rxb = shared_rxb.clone(); + let task_txb = shared_txb.clone(); + + let read_task = tokio::spawn(async move { + let max_tries = config.max_reconnect_tries; + let mut tries: usize = 0; + let mut backoff = RECONNECT_WAIT_INITIAL; + + loop { + let addr = format!("{}:{}", config.target_host, config.target_port); + let stream = match tokio::time::timeout( + std::time::Duration::from_secs(config.connect_timeout_secs), + TcpStream::connect(&addr), + ) + .await + { + Ok(Ok(s)) => s, + Ok(Err(e)) => { + tracing::warn!(name = %config.name, error = %e, "TCP connect failed"); + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + tracing::warn!(name = %config.name, "max reconnect tries reached"); + return; + } + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + Err(_) => { + tracing::warn!(name = %config.name, "TCP connect timed out"); + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + tracing::warn!(name = %config.name, "max reconnect tries reached"); + return; + } + } + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + continue; + } + }; + + if let Err(e) = set_keepalive(&stream) { + tracing::debug!(error = %e, "failed to set TCP keepalive"); + } + + // Nagle off for low-latency packets; larger buffers for bulk transfers. + let _ = stream.set_nodelay(true); + set_socket_buffers(&stream, 131072); + + let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone()); + state.online.store(true, Ordering::SeqCst); + online2.store(true, Ordering::SeqCst); + tries = 0; + backoff = RECONNECT_WAIT_INITIAL; + + let (reader, writer) = stream.into_split(); + + let (conn_tx, conn_rx) = mpsc::channel::(1024); + let state_w = state.clone(); + let write_handle = tokio::spawn(tcp_write_loop(writer, conn_rx, state_w, kiss_framing)); + + let rx_ref = rx.clone(); + let fwd_handle = tokio::spawn(async move { + let mut guard = rx_ref.lock().await; + while let Some(data) = guard.recv().await { + if conn_tx.send(data).await.is_err() { + break; + } + } + }); + + tcp_read_loop( + reader, + id, + transport_tx.clone(), + state.clone(), + kiss_framing, + ) + .await; + + online2.store(false, Ordering::SeqCst); + + fwd_handle.abort(); + let _ = fwd_handle.await; + write_handle.abort(); + let _ = write_handle.await; + + if let Some(max) = max_tries { + tries += 1; + if tries >= max { + tracing::warn!(name = %config.name, "max reconnect tries reached"); + // Notify transport immediately rather than waiting for auto-drop. + let _ = transport_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + return; + } + } + tracing::info!(name = %config.name, "reconnecting in {}s", backoff); + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(RECONNECT_WAIT_MAX); + } + }); + + let bitrate: u64 = 10_000_000; + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate, + mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU), + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +/// Wrap an accepted TCP stream as an interface; no reconnect on disconnect. +#[tracing::instrument( + level = "debug", + name = "tcp.server.accept", + skip_all, + fields(client_id = id, name = %name), +)] +async fn spawn_tcp_accepted( + stream: TcpStream, + id: InterfaceId, + name: String, + transport_tx: mpsc::Sender, + kiss_framing: bool, + mode: InterfaceMode, +) -> InterfaceHandle { + let online = Arc::new(AtomicBool::new(true)); + let online2 = online.clone(); + let (tx, conn_rx) = mpsc::channel::(1024); + + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let state = TcpInterfaceState::with_shared_counters(shared_rxb.clone(), shared_txb.clone()); + state.online.store(true, Ordering::SeqCst); + + if let Err(e) = set_keepalive(&stream) { + tracing::debug!(error = %e, "failed to set keepalive on accepted socket"); + } + let _ = stream.set_nodelay(true); + set_socket_buffers(&stream, 131072); + + let (reader, writer) = stream.into_split(); + + let state_w = state.clone(); + tokio::spawn(tcp_write_loop(writer, conn_rx, state_w, kiss_framing)); + + let handle_name = name.clone(); + let dereg_tx = transport_tx.clone(); + let read_task = tokio::spawn(async move { + tcp_read_loop(reader, id, transport_tx, state, kiss_framing).await; + online2.store(false, Ordering::SeqCst); + tracing::info!(name = %handle_name, "accepted TCP client disconnected"); + // Proactively notify transport so broadcasts stop targeting this dead tx. + let _ = dereg_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + }); + + let bitrate: u64 = 10_000_000; + InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate, + mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU), + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + } +} + +/// Spawn a TCP server. Each accepted connection becomes its own +/// `InterfaceHandle`, delivered via `handle_tx` for caller registration. +pub async fn spawn_tcp_server( + config: TcpServerConfig, + id: InterfaceId, + id_gen: Arc, + transport_tx: mpsc::Sender, + handle_tx: mpsc::Sender, +) -> Result { + let addr = format!("{}:{}", config.listen_ip, config.listen_port); + let listener = TcpListener::bind(&addr).await?; + let local_addr = listener.local_addr()?; + tracing::info!(name = %config.name, addr = %local_addr, "TCP server listening"); + + let online = Arc::new(AtomicBool::new(true)); + let online2 = online.clone(); + let name = config.name.clone(); + let mode = config.mode; + let kiss_framing = config.kiss_framing; + + // Server handle tx is unused; only accepted connections send. + let (tx, _rx) = mpsc::channel::(1); + + let read_task = tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((stream, peer)) => { + let client_id = id_gen.fetch_add(1, Ordering::SeqCst); + let client_name = format!("{}/client_{}", config.name, client_id); + tracing::info!(name = %client_name, peer = %peer, "accepted TCP connection"); + let handle = spawn_tcp_accepted( + stream, + client_id, + client_name, + transport_tx.clone(), + kiss_framing, + mode, + ) + .await; + if handle_tx.send(handle).await.is_err() { + tracing::warn!("handle registry channel closed, stopping accept loop"); + break; + } + } + Err(e) => { + tracing::warn!(error = %e, "TCP accept error"); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + } + } + online2.store(false, Ordering::SeqCst); + }); + + let bitrate: u64 = 10_000_000; + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: false, + forward: false, + repeat: false, + }, + bitrate, + mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU), + online, + rxb: Some(Arc::new(AtomicU64::new(0))), + txb: Some(Arc::new(AtomicU64::new(0))), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tcp_client_config() { + let config = TcpClientConfig::new("test", "127.0.0.1", 4242); + assert_eq!(config.target_port, 4242); + assert!(!config.kiss_framing); + assert_eq!(config.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT); + } + + #[test] + fn test_tcp_server_config() { + let config = TcpServerConfig::new("server", "0.0.0.0", 4242); + assert_eq!(config.listen_port, 4242); + assert!(!config.prefer_ipv6); + } + + #[test] + fn test_frame_for_tcp_hdlc() { + let data = b"test packet"; + let framed = frame_for_tcp(data, false); + assert_eq!(framed[0], hdlc::FLAG); + assert_eq!(framed[framed.len() - 1], hdlc::FLAG); + } + + #[test] + fn test_frame_for_tcp_kiss() { + let data = b"test packet"; + let framed = frame_for_tcp(data, true); + assert_eq!(framed[0], crate::kiss::FEND); + assert_eq!(framed[framed.len() - 1], crate::kiss::FEND); + } + + #[test] + fn test_interface_state() { + let state = TcpInterfaceState::new(); + state.record_rx(100); + state.record_tx(200); + assert_eq!(state.rx_bytes.load(Ordering::Relaxed), 100); + assert_eq!(state.tx_bytes.load(Ordering::Relaxed), 200); + assert_eq!(state.rx_packets.load(Ordering::Relaxed), 1); + assert_eq!(state.tx_packets.load(Ordering::Relaxed), 1); + } + + /// TCP loopback: spawn server + client on localhost:0, roundtrip a packet. + #[tokio::test] + async fn test_tcp_loopback_roundtrip() { + let (transport_tx, mut transport_rx) = mpsc::channel::(64); + let (handle_tx, mut handle_rx) = mpsc::channel::(8); + let id_gen = Arc::new(AtomicU64::new(100)); + + // Bind-then-drop to grab a free port for the server config. + let server_cfg = TcpServerConfig::new("test-server", "127.0.0.1", 0); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + + let mut server_cfg2 = server_cfg; + server_cfg2.listen_port = port; + + let server_handle = + spawn_tcp_server(server_cfg2, 99, id_gen, transport_tx.clone(), handle_tx) + .await + .unwrap(); + assert_eq!(server_handle.id, 99); + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let client_cfg = TcpClientConfig { + name: "test-client".into(), + target_host: "127.0.0.1".into(), + target_port: port, + kiss_framing: false, + connect_timeout_secs: 5, + max_reconnect_tries: Some(1), + mode: InterfaceMode::Full, + }; + let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone(), None) + .await + .unwrap(); + + let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv()) + .await + .expect("timeout waiting for accepted handle") + .expect("handle channel closed"); + + let payload = Bytes::from_static(b"hello from client"); + client_handle.tx.send(payload.clone()).await.unwrap(); + + let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) + .await + .expect("timeout waiting for transport message") + .expect("transport channel closed"); + + match msg { + TransportMessage::Inbound(pkt) => { + assert_eq!(pkt.raw, payload); + assert_eq!(pkt.interface_id, accepted.id); + } + other => panic!("unexpected message: {:?}", other), + } + + let reply = Bytes::from_static(b"hello from server"); + accepted.tx.send(reply.clone()).await.unwrap(); + + let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) + .await + .expect("timeout waiting for reply") + .expect("transport channel closed"); + + match msg2 { + TransportMessage::Inbound(pkt) => { + assert_eq!(pkt.raw, reply); + assert_eq!(pkt.interface_id, 1); + } + other => panic!("unexpected reply message: {:?}", other), + } + + server_handle.read_task.abort(); + client_handle.read_task.abort(); + } + + /// HDLC streaming: feed partial frames and verify correct reassembly. + #[test] + fn test_hdlc_streaming_partial_feeds() { + let mut deframer = hdlc::HdlcDeframer::new(); + + let data1 = b"packet one"; + let data2 = b"packet two"; + let framed1 = hdlc::frame(data1); + let framed2 = hdlc::frame(data2); + + let mut combined = Vec::new(); + combined.extend_from_slice(&framed1); + combined.extend_from_slice(&framed2); + + let mut all_frames = Vec::new(); + for &b in &combined { + all_frames.extend(deframer.feed(&[b])); + } + + assert_eq!(all_frames.len(), 2); + assert_eq!(all_frames[0], data1); + assert_eq!(all_frames[1], data2); + } + + /// TCP reconnection: client retries after connection failure. + #[tokio::test] + async fn test_tcp_client_reconnection_max_tries() { + let (transport_tx, _transport_rx) = mpsc::channel::(8); + + // Port 1 is closed, forcing every connect to fail. + let config = TcpClientConfig { + name: "reconnect-test".into(), + target_host: "127.0.0.1".into(), + target_port: 1, + kiss_framing: false, + connect_timeout_secs: 1, + max_reconnect_tries: Some(2), + mode: InterfaceMode::Full, + }; + + let handle = spawn_tcp_client(config, 99, transport_tx, None) + .await + .unwrap(); + + // Two failed tries with 5s waits each; 20s headroom. + let result = + tokio::time::timeout(std::time::Duration::from_secs(20), handle.read_task).await; + + assert!(result.is_ok(), "task should have finished within timeout"); + } + + /// Server's per-client read_task must DeregisterInterface on EOF + /// so transport stops targeting the dead tx channel. + #[tokio::test] + async fn test_tcp_server_deregisters_on_client_disconnect() { + let (transport_tx, mut transport_rx) = mpsc::channel::(64); + let (handle_tx, mut handle_rx) = mpsc::channel::(8); + let id_gen = Arc::new(AtomicU64::new(800)); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + + let mut server_cfg = TcpServerConfig::new("dereg-server", "127.0.0.1", 0); + server_cfg.listen_port = port; + + let server_handle = + spawn_tcp_server(server_cfg, 88, id_gen, transport_tx.clone(), handle_tx) + .await + .unwrap(); + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let client_cfg = TcpClientConfig { + name: "dereg-client".into(), + target_host: "127.0.0.1".into(), + target_port: port, + kiss_framing: false, + connect_timeout_secs: 5, + max_reconnect_tries: Some(1), + mode: InterfaceMode::Full, + }; + let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone(), None) + .await + .unwrap(); + + let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv()) + .await + .expect("timeout waiting for accepted handle") + .expect("handle channel closed"); + let server_side_client_id = accepted.id; + + // Abort client-side tasks; server's per-client reader sees EOF and exits. + client_handle.read_task.abort(); + drop(client_handle.tx); + + let mut saw_dereg = false; + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3); + while tokio::time::Instant::now() < deadline { + match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv()) + .await + { + Ok(Some(TransportMessage::DeregisterInterface { id })) + if id == server_side_client_id => + { + saw_dereg = true; + break; + } + Ok(Some(_)) => continue, + Ok(None) => break, + Err(_) => continue, + } + } + + assert!( + saw_dereg, + "server must emit DeregisterInterface for disconnected client id {server_side_client_id}" + ); + + server_handle.read_task.abort(); + } +} diff --git a/crates/rns-interface/src/traits.rs b/crates/rns-interface/src/traits.rs new file mode 100644 index 0000000..106735c --- /dev/null +++ b/crates/rns-interface/src/traits.rs @@ -0,0 +1,244 @@ +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64}; + +use bytes::Bytes; +use tokio::sync::mpsc; + +pub type InterfaceId = u64; + +/// Handle returned by every `spawn_*`: write channel, status flag, and read task. +pub struct InterfaceHandle { + pub id: InterfaceId, + pub name: String, + pub mode: InterfaceMode, + pub direction: InterfaceDirection, + pub bitrate: u64, + pub mtu: u32, + pub online: Arc, + pub rxb: Option>, + pub txb: Option>, + pub tx: mpsc::Sender, + pub read_task: tokio::task::JoinHandle<()>, +} + +/// Optional per-interface IFAC (Interface Authentication Code) configuration. +pub struct IfacConfig { + pub ifac_key: [u8; 64], + pub ifac_size: usize, +} + +/// Interface operating mode. Byte values are on-wire constants. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +#[derive(Default)] +pub enum InterfaceMode { + #[default] + Full = 0x01, + PointToPoint = 0x02, + AccessPoint = 0x03, + Roaming = 0x04, + Boundary = 0x05, + Gateway = 0x06, +} + +pub const MODE_FULL: InterfaceMode = InterfaceMode::Full; +pub const MODE_POINT_TO_POINT: InterfaceMode = InterfaceMode::PointToPoint; + +/// Modes for which a Transport Node actively discovers paths. +pub const DISCOVER_PATHS_FOR: &[InterfaceMode] = &[ + InterfaceMode::AccessPoint, + InterfaceMode::Gateway, + InterfaceMode::Roaming, +]; + +impl InterfaceMode { + pub fn from_u8(val: u8) -> Option { + match val { + 0x01 => Some(Self::Full), + 0x02 => Some(Self::PointToPoint), + 0x03 => Some(Self::AccessPoint), + 0x04 => Some(Self::Roaming), + 0x05 => Some(Self::Boundary), + 0x06 => Some(Self::Gateway), + _ => None, + } + } +} + +/// Interface direction flags. +#[derive(Debug, Clone, Copy, Default)] +pub struct InterfaceDirection { + pub inbound: bool, + pub outbound: bool, + pub forward: bool, + pub repeat: bool, +} + +/// Interface statistics. +#[derive(Debug, Clone, Default)] +pub struct InterfaceStats { + pub rx_bytes: u64, + pub tx_bytes: u64, + pub rx_packets: u64, + pub tx_packets: u64, + pub online: bool, + pub bitrate: u64, + pub mtu: u32, +} + +/// Base trait for all network interfaces. +pub trait Interface: Send + Sync { + fn process_incoming(&self, data: &[u8]); + + fn process_outgoing(&self, data: &[u8]) -> Result<(), InterfaceError>; + + fn get_stats(&self) -> InterfaceStats; + + fn detach(&mut self); + + fn name(&self) -> &str; + + fn mode(&self) -> InterfaceMode; + + /// Interface bitrate in bits/sec. + fn bitrate(&self) -> u64; + + fn mtu(&self) -> u32 { + rns_wire::constants::MTU as u32 + } + + fn online(&self) -> bool; + + /// 16-byte interface identifier: truncated SHA-256 of the interface name. + fn get_hash(&self) -> [u8; 16] { + let full = rns_crypto::sha::full_hash(self.name().as_bytes()); + let mut h = [0u8; 16]; + h.copy_from_slice(&full[..16]); + h + } +} + +/// Select an MTU for the given bitrate; `None` below 62.5 kbps minimum. +pub fn optimise_mtu(bitrate: u64) -> Option { + if bitrate >= 1_000_000_000 { + Some(524_288) + } else if bitrate > 750_000_000 { + Some(262_144) + } else if bitrate > 400_000_000 { + Some(131_072) + } else if bitrate > 200_000_000 { + Some(65_536) + } else if bitrate > 100_000_000 { + Some(32_768) + } else if bitrate > 10_000_000 { + Some(16_384) + } else if bitrate > 5_000_000 { + Some(8_192) + } else if bitrate > 2_000_000 { + Some(4_096) + } else if bitrate > 1_000_000 { + Some(2_048) + } else if bitrate > 62_500 { + Some(1_024) + } else { + None + } +} + +/// Length of interface name hash (80 bits / 10 bytes). +pub const NAME_HASH_LENGTH: usize = 10; + +// Ingress control constants — must match Reticulum reference. +pub const IA_FREQ_SAMPLES: usize = 6; +pub const OA_FREQ_SAMPLES: usize = 6; +pub const MAX_HELD_ANNOUNCES: usize = 256; +/// Duration a new interface stays in "new" state (seconds). +pub const IC_NEW_TIME: f64 = 7200.0; +/// Burst threshold for new interfaces (announces/sec). +pub const IC_BURST_FREQ_NEW: f64 = 3.5; +/// Burst threshold for established interfaces (announces/sec). +pub const IC_BURST_FREQ: f64 = 12.0; +/// Burst detection window duration (seconds). +pub const IC_BURST_HOLD: f64 = 60.0; +/// Penalty duration after a detected burst (seconds). +pub const IC_BURST_PENALTY: f64 = 300.0; +/// Interval between released held announces (seconds). +pub const IC_HELD_RELEASE_INTERVAL: f64 = 30.0; + +#[derive(Debug, thiserror::Error)] +pub enum InterfaceError { + #[error("interface offline")] + Offline, + #[error("send failed: {0}")] + SendFailed(String), + #[error("interface detached")] + Detached, + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_optimise_mtu() { + assert_eq!(optimise_mtu(1_000_000_000), Some(524_288)); + assert_eq!(optimise_mtu(100_000_001), Some(32_768)); + assert_eq!(optimise_mtu(10_000_001), Some(16_384)); + assert_eq!(optimise_mtu(62_500), None); + assert_eq!(optimise_mtu(62_501), Some(1_024)); + } + + #[test] + fn test_interface_mode_repr() { + assert_eq!(InterfaceMode::Full as u8, 0x01); + assert_eq!(InterfaceMode::PointToPoint as u8, 0x02); + assert_eq!(InterfaceMode::AccessPoint as u8, 0x03); + assert_eq!(InterfaceMode::Roaming as u8, 0x04); + assert_eq!(InterfaceMode::Boundary as u8, 0x05); + assert_eq!(InterfaceMode::Gateway as u8, 0x06); + } + + #[test] + fn test_interface_mode_from_u8() { + assert_eq!(InterfaceMode::from_u8(0x01), Some(InterfaceMode::Full)); + assert_eq!( + InterfaceMode::from_u8(0x02), + Some(InterfaceMode::PointToPoint) + ); + assert_eq!(InterfaceMode::from_u8(0x06), Some(InterfaceMode::Gateway)); + assert_eq!(InterfaceMode::from_u8(0x00), None); + assert_eq!(InterfaceMode::from_u8(0xFF), None); + } + + #[test] + fn test_mode_aliases() { + assert_eq!(MODE_FULL, InterfaceMode::Full); + assert_eq!(MODE_POINT_TO_POINT, InterfaceMode::PointToPoint); + } + + #[test] + fn test_discover_paths_for() { + assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::AccessPoint)); + assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Gateway)); + assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Roaming)); + assert!(!DISCOVER_PATHS_FOR.contains(&InterfaceMode::Full)); + } + + #[test] + fn test_name_hash_length() { + assert_eq!(NAME_HASH_LENGTH, 10); + assert_eq!(NAME_HASH_LENGTH * 8, 80); + } + + #[test] + fn test_ingress_control_constants() { + assert_eq!(IC_BURST_FREQ, 12.0); + assert_eq!(IC_BURST_FREQ_NEW, 3.5); + assert_eq!(IC_BURST_HOLD, 60.0); + assert_eq!(IC_BURST_PENALTY, 300.0); + assert_eq!(IC_NEW_TIME, 7200.0); + assert_eq!(IC_HELD_RELEASE_INTERVAL, 30.0); + } +} diff --git a/crates/rns-interface/src/udp.rs b/crates/rns-interface/src/udp.rs new file mode 100644 index 0000000..6e209cc --- /dev/null +++ b/crates/rns-interface/src/udp.rs @@ -0,0 +1,286 @@ +use std::net::SocketAddr; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use bytes::Bytes; +use tokio::net::UdpSocket; +use tokio::sync::mpsc; + +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use rns_transport::messages::{InboundPacket, TransportMessage}; + +pub const HW_MTU: u32 = 1064; + +#[derive(Debug, Clone)] +pub struct UdpInterfaceConfig { + pub name: String, + pub listen_ip: Option, + pub listen_port: Option, + pub forward_ip: Option, + pub forward_port: Option, + pub device: Option, + pub mode: InterfaceMode, +} + +impl UdpInterfaceConfig { + pub fn new(name: &str) -> Self { + Self { + name: name.to_string(), + listen_ip: None, + listen_port: None, + forward_ip: None, + forward_port: None, + device: None, + mode: InterfaceMode::Full, + } + } + + pub fn listen(mut self, ip: &str, port: u16) -> Self { + self.listen_ip = Some(ip.to_string()); + self.listen_port = Some(port); + self + } + + pub fn forward(mut self, ip: &str, port: u16) -> Self { + self.forward_ip = Some(ip.to_string()); + self.forward_port = Some(port); + self + } +} + +/// Spawn a UDP interface — datagrams are unframed (1 send/recv = 1 packet). +pub async fn spawn_udp_interface( + config: UdpInterfaceConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + let listen_ip = config.listen_ip.as_deref().unwrap_or("0.0.0.0"); + let listen_port = config.listen_port.unwrap_or(0); + let bind_addr = format!("{}:{}", listen_ip, listen_port); + let socket = Arc::new(UdpSocket::bind(&bind_addr).await?); + // Needed for directed broadcasts (255.255.255.255). + socket.set_broadcast(true)?; + let local_addr = socket.local_addr()?; + tracing::info!(name = %config.name, addr = %local_addr, "UDP interface bound"); + + let online = Arc::new(AtomicBool::new(true)); + let online2 = online.clone(); + let (tx, mut rx) = mpsc::channel::(256); + let name = config.name.clone(); + let mode = config.mode; + let shared_rxb = Arc::new(AtomicU64::new(0)); + let shared_txb = Arc::new(AtomicU64::new(0)); + let task_rxb = shared_rxb.clone(); + let task_txb = shared_txb.clone(); + + let forward_addr: Option = match (&config.forward_ip, config.forward_port) { + (Some(ip), Some(port)) => { + let addr_str = format!("{}:{}", ip, port); + match addr_str.parse() { + Ok(a) => Some(a), + Err(e) => { + tracing::warn!(error = %e, "invalid forward address, trying DNS"); + tokio::net::lookup_host(&addr_str) + .await + .ok() + .and_then(|mut addrs| addrs.next()) + } + } + } + _ => None, + }; + + let socket_w = socket.clone(); + tokio::spawn(async move { + while let Some(data) = rx.recv().await { + if let Some(addr) = forward_addr { + let len = data.len(); + if let Err(e) = socket_w.send_to(&data, addr).await { + tracing::warn!(error = %e, "UDP send_to failed"); + } else { + task_txb.fetch_add(len as u64, Ordering::Relaxed); + } + } else { + tracing::debug!("UDP write: no forward address configured, dropping packet"); + } + } + }); + + let read_task = tokio::spawn(async move { + let mut buf = [0u8; 2048]; + loop { + match socket.recv_from(&mut buf).await { + Ok((n, src)) => { + if n == 0 { + continue; + } + task_rxb.fetch_add(n as u64, Ordering::Relaxed); + let raw = Bytes::copy_from_slice(&buf[..n]); + tracing::debug!( + interface_id = id, + from = %src, + len = n, + "UDP read: received packet" + ); + let msg = TransportMessage::Inbound(InboundPacket { + raw, + interface_id: id, + rssi: None, + snr: None, + q: None, + }); + if transport_tx.send(msg).await.is_err() { + tracing::warn!(id, "transport channel closed"); + break; + } + } + Err(e) => { + tracing::warn!(error = %e, "UDP recv_from error"); + break; + } + } + } + online2.store(false, Ordering::SeqCst); + }); + + Ok(InterfaceHandle { + id, + name, + mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: 10_000_000, + mtu: HW_MTU, + online, + rxb: Some(shared_rxb), + txb: Some(shared_txb), + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_udp_config() { + let config = UdpInterfaceConfig::new("udp0") + .listen("0.0.0.0", 4242) + .forward("192.168.1.1", 4243); + + assert_eq!(config.listen_ip.as_deref(), Some("0.0.0.0")); + assert_eq!(config.listen_port, Some(4242)); + assert_eq!(config.forward_ip.as_deref(), Some("192.168.1.1")); + assert_eq!(config.forward_port, Some(4243)); + } + + #[test] + fn test_hw_mtu() { + assert_eq!(HW_MTU, 1064); + } + + #[test] + fn test_udp_config_defaults() { + let cfg = UdpInterfaceConfig::new("udp0"); + assert_eq!(cfg.name, "udp0"); + assert!(cfg.listen_ip.is_none()); + assert!(cfg.listen_port.is_none()); + assert!(cfg.forward_ip.is_none()); + assert!(cfg.forward_port.is_none()); + assert_eq!(cfg.mode, InterfaceMode::Full); + } + + #[test] + fn test_udp_config_listen_only() { + let cfg = UdpInterfaceConfig::new("udp-rx").listen("0.0.0.0", 5555); + assert_eq!(cfg.listen_ip.as_deref(), Some("0.0.0.0")); + assert_eq!(cfg.listen_port, Some(5555)); + assert!(cfg.forward_ip.is_none()); + assert!(cfg.forward_port.is_none()); + } + + #[test] + fn test_udp_config_builder_chain() { + let cfg = UdpInterfaceConfig::new("udp-bidir") + .listen("0.0.0.0", 4242) + .forward("10.0.0.1", 6666); + assert_eq!(cfg.listen_ip.as_deref(), Some("0.0.0.0")); + assert_eq!(cfg.listen_port, Some(4242)); + assert_eq!(cfg.forward_ip.as_deref(), Some("10.0.0.1")); + assert_eq!(cfg.forward_port, Some(6666)); + } + + #[tokio::test] + async fn test_udp_loopback() { + let (transport_tx, mut transport_rx) = mpsc::channel::(64); + + let cfg_a = UdpInterfaceConfig::new("udp-a").listen("127.0.0.1", 0); + let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone()) + .await + .unwrap(); + + // Reserve two free ports via bind-drop; handle doesn't expose its addr. + let sock_tmp1 = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let port_a = sock_tmp1.local_addr().unwrap().port(); + let sock_tmp2 = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let port_b = sock_tmp2.local_addr().unwrap().port(); + drop(sock_tmp1); + drop(sock_tmp2); + handle_a.read_task.abort(); + + let cfg_a = UdpInterfaceConfig::new("udp-a") + .listen("127.0.0.1", port_a) + .forward("127.0.0.1", port_b); + let cfg_b = UdpInterfaceConfig::new("udp-b") + .listen("127.0.0.1", port_b) + .forward("127.0.0.1", port_a); + + let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone()) + .await + .unwrap(); + let handle_b = spawn_udp_interface(cfg_b, 20, transport_tx.clone()) + .await + .unwrap(); + + // A → B's listen port; inbound carries B's interface_id (20). + let payload = Bytes::from_static(b"udp test data"); + handle_a.tx.send(payload.clone()).await.unwrap(); + + let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) + .await + .expect("timeout") + .expect("channel closed"); + + match msg { + TransportMessage::Inbound(pkt) => { + assert_eq!(pkt.raw, payload); + assert_eq!(pkt.interface_id, 20); + } + other => panic!("unexpected: {:?}", other), + } + + let reply = Bytes::from_static(b"udp reply"); + handle_b.tx.send(reply.clone()).await.unwrap(); + + let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) + .await + .expect("timeout") + .expect("channel closed"); + + match msg2 { + TransportMessage::Inbound(pkt) => { + assert_eq!(pkt.raw, reply); + assert_eq!(pkt.interface_id, 10); + } + other => panic!("unexpected: {:?}", other), + } + + handle_a.read_task.abort(); + handle_b.read_task.abort(); + } +} diff --git a/crates/rns-interface/src/weave.rs b/crates/rns-interface/src/weave.rs new file mode 100644 index 0000000..6cf55be --- /dev/null +++ b/crates/rns-interface/src/weave.rs @@ -0,0 +1,491 @@ +//! Weave switching fabric — protocol primitives only. +//! +//! Wire format (WDCL inside HDLC): +//! ```text +//! [HDLC_FLAG] [escaped WDCL] [HDLC_FLAG] +//! WDCL = [ADDR u32][TYPE u8][PAYLOAD…] ADDR 0xFFFFFFFF = broadcast +//! ``` +//! Discovery: Ed25519 challenge-response over WDCL_T_DISCOVER / WDCL_T_CONNECT. +//! Runtime spawn (serial I/O, peer mgmt) not yet wired up. + +use crate::traits::InterfaceMode; + +pub const WDCL_T_DISCOVER: u8 = 0x00; +pub const WDCL_T_CONNECT: u8 = 0x01; +pub const WDCL_T_CMD: u8 = 0x02; +pub const WDCL_T_LOG: u8 = 0x03; +pub const WDCL_T_DISP: u8 = 0x04; +pub const WDCL_T_ENDPOINT_PKT: u8 = 0x05; +pub const WDCL_T_ENCAP_PROTO: u8 = 0x06; + +pub const WDCL_BROADCAST: [u8; 4] = [0xFF, 0xFF, 0xFF, 0xFF]; + +pub const WDCL_HANDSHAKE_TIMEOUT: f64 = 2.0; + +/// WDCL header = `ADDR(4) + TYPE(1)`. +pub const HEADER_MINSIZE: usize = 5; + +pub const SWITCH_ID_LEN: usize = 4; +pub const ENDPOINT_ID_LEN: usize = 8; +pub const FLOWSEQ_LEN: usize = 2; +pub const HMAC_LEN: usize = 8; +pub const AUTH_LEN: usize = ENDPOINT_ID_LEN + HMAC_LEN; +pub const PUBKEY_SIZE: usize = 32; +pub const PRVKEY_SIZE: usize = 64; +pub const SIGNATURE_LEN: usize = 64; + +pub const HW_MTU: u32 = 1024; +pub const FIXED_MTU: bool = true; +pub const DEFAULT_IFAC_SIZE: usize = 16; +pub const PEERING_TIMEOUT: f64 = 20.0; +pub const BITRATE_GUESS: u64 = 250_000; + +pub const MULTI_IF_DEQUE_LEN: usize = 48; +pub const MULTI_IF_DEQUE_TTL: f64 = 0.75; + +pub const STATLEN_MAX: usize = 120; +pub const STAT_UPDATE_THROTTLE: f64 = 0.5; + +pub const ENDPOINT_QUEUE_LEN: usize = 1024; + +pub const CMD_ENDPOINT_PKT: u16 = 0x0001; +pub const CMD_ENDPOINTS_LIST: u16 = 0x0100; +pub const CMD_REMOTE_DISPLAY: u16 = 0x0A00; +pub const CMD_REMOTE_INPUT: u16 = 0x0A01; + +// LOG frame payload: [flags u8][ts_ms u32 BE][level u8][event u16 BE][data…] + +pub const EVT_MSG: u16 = 0x0000; +pub const EVT_SYSTEM_BOOT: u16 = 0x0001; +pub const EVT_CORE_INIT: u16 = 0x0002; + +// Driver events (0x1xxx) +pub const EVT_DRV_UART_INIT: u16 = 0x1000; +pub const EVT_DRV_USB_CDC_INIT: u16 = 0x1010; +pub const EVT_DRV_USB_CDC_HOST_AVAIL: u16 = 0x1011; +pub const EVT_DRV_USB_CDC_HOST_SUSPEND: u16 = 0x1012; +pub const EVT_DRV_USB_CDC_HOST_RESUME: u16 = 0x1013; +pub const EVT_DRV_USB_CDC_CONNECTED: u16 = 0x1014; +pub const EVT_DRV_USB_CDC_READ_ERR: u16 = 0x1015; +pub const EVT_DRV_USB_CDC_OVERFLOW: u16 = 0x1016; +pub const EVT_DRV_USB_CDC_DROPPED: u16 = 0x1017; +pub const EVT_DRV_USB_CDC_TX_TIMEOUT: u16 = 0x1018; +pub const EVT_DRV_I2C_INIT: u16 = 0x1020; +pub const EVT_DRV_NVS_INIT: u16 = 0x1030; +pub const EVT_DRV_NVS_ERASE: u16 = 0x1031; +pub const EVT_DRV_CRYPTO_INIT: u16 = 0x1040; +pub const EVT_DRV_DISPLAY_INIT: u16 = 0x1050; +pub const EVT_DRV_DISPLAY_BUS_AVAILABLE: u16 = 0x1051; +pub const EVT_DRV_DISPLAY_IO_CONFIGURED: u16 = 0x1052; +pub const EVT_DRV_DISPLAY_PANEL_CREATED: u16 = 0x1053; +pub const EVT_DRV_DISPLAY_PANEL_RESET: u16 = 0x1054; +pub const EVT_DRV_DISPLAY_PANEL_INIT: u16 = 0x1055; +pub const EVT_DRV_DISPLAY_PANEL_ENABLE: u16 = 0x1056; +pub const EVT_DRV_DISPLAY_REMOTE_ENABLE: u16 = 0x1057; +pub const EVT_DRV_W80211_INIT: u16 = 0x1060; +pub const EVT_DRV_W80211_CHANNEL: u16 = 0x1062; +pub const EVT_DRV_W80211_POWER: u16 = 0x1063; + +// Kernel events (0x2xxx) +pub const EVT_KRN_LOGGER_INIT: u16 = 0x2000; +pub const EVT_KRN_LOGGER_OUTPUT: u16 = 0x2001; +pub const EVT_KRN_UI_INIT: u16 = 0x2010; + +// Protocol events (0x3xxx) +pub const EVT_PROTO_WDCL_INIT: u16 = 0x3000; +pub const EVT_PROTO_WDCL_RUNNING: u16 = 0x3001; +pub const EVT_PROTO_WDCL_CONNECTION: u16 = 0x3002; +pub const EVT_PROTO_WDCL_HOST_ENDPOINT: u16 = 0x3003; +pub const EVT_PROTO_WEAVE_INIT: u16 = 0x3100; +pub const EVT_PROTO_WEAVE_RUNNING: u16 = 0x3101; +pub const EVT_PROTO_WEAVE_EP_ALIVE: u16 = 0x3102; +pub const EVT_PROTO_WEAVE_EP_TIMEOUT: u16 = 0x3103; +pub const EVT_PROTO_WEAVE_EP_VIA: u16 = 0x3104; + +// Service events +pub const EVT_SRVCTL_REMOTE_DISPLAY: u16 = 0xA000; +pub const EVT_INTERFACE_REGISTERED: u16 = 0xD000; + +// Stats events (0xExxx) +pub const EVT_STAT_STATE: u16 = 0xE000; +pub const EVT_STAT_UPTIME: u16 = 0xE001; +pub const EVT_STAT_TIMEBASE: u16 = 0xE002; +pub const EVT_STAT_CPU: u16 = 0xE003; +pub const EVT_STAT_TASK_CPU: u16 = 0xE004; +pub const EVT_STAT_MEMORY: u16 = 0xE005; +pub const EVT_STAT_STORAGE: u16 = 0xE006; + +// Error events +pub const EVT_SYSERR_MEM_EXHAUSTED: u16 = 0xF000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum PhysicalMedium { + Usb = 0x01, + Uart = 0x02, + W80211 = 0x03, + Ble = 0x04, + Lora = 0x05, + Ethernet = 0x06, + Wifi = 0x07, + Tcp = 0x08, + Udp = 0x09, + Ir = 0x0A, + Afsk = 0x0B, + Gpio = 0x0C, + Spi = 0x0D, + I2c = 0x0E, + Can = 0x0F, + Dma = 0x10, +} + +impl PhysicalMedium { + pub fn from_u8(val: u8) -> Option { + match val { + 0x01 => Some(Self::Usb), + 0x02 => Some(Self::Uart), + 0x03 => Some(Self::W80211), + 0x04 => Some(Self::Ble), + 0x05 => Some(Self::Lora), + 0x06 => Some(Self::Ethernet), + 0x07 => Some(Self::Wifi), + 0x08 => Some(Self::Tcp), + 0x09 => Some(Self::Udp), + 0x0A => Some(Self::Ir), + 0x0B => Some(Self::Afsk), + 0x0C => Some(Self::Gpio), + 0x0D => Some(Self::Spi), + 0x0E => Some(Self::I2c), + 0x0F => Some(Self::Can), + 0x10 => Some(Self::Dma), + _ => None, + } + } + + pub fn short_name(self) -> &'static str { + match self { + Self::Usb => "usb", + Self::Uart => "uart", + Self::W80211 => "mw", + Self::Ble => "ble", + Self::Lora => "lora", + Self::Ethernet => "eth", + Self::Wifi => "wifi", + Self::Tcp => "tcp", + Self::Udp => "udp", + Self::Ir => "ir", + Self::Afsk => "afsk", + Self::Gpio => "gpio", + Self::Spi => "spi", + Self::I2c => "i2c", + Self::Can => "can", + Self::Dma => "dma", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum DeviceLogLevel { + Force = 0, + Critical = 1, + Error = 2, + Warning = 3, + Notice = 4, + Info = 5, + Verbose = 6, + Debug = 7, + Extreme = 8, + System = 9, +} + +impl DeviceLogLevel { + pub fn from_u8(val: u8) -> Option { + match val { + 0 => Some(Self::Force), + 1 => Some(Self::Critical), + 2 => Some(Self::Error), + 3 => Some(Self::Warning), + 4 => Some(Self::Notice), + 5 => Some(Self::Info), + 6 => Some(Self::Verbose), + 7 => Some(Self::Debug), + 8 => Some(Self::Extreme), + 9 => Some(Self::System), + _ => None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WdclFrame { + pub addr: [u8; 4], + pub msg_type: u8, + pub payload: Vec, +} + +pub fn wdcl_frame(addr: [u8; 4], msg_type: u8, payload: &[u8]) -> Vec { + let mut frame = Vec::with_capacity(HEADER_MINSIZE + payload.len()); + frame.extend_from_slice(&addr); + frame.push(msg_type); + frame.extend_from_slice(payload); + frame +} + +/// Parse WDCL after HDLC deframing; `None` if shorter than `HEADER_MINSIZE`. +pub fn wdcl_parse(data: &[u8]) -> Option { + if data.len() < HEADER_MINSIZE { + return None; + } + let mut addr = [0u8; 4]; + addr.copy_from_slice(&data[..4]); + Some(WdclFrame { + addr, + msg_type: data[4], + payload: data[5..].to_vec(), + }) +} + +/// `WDCL_T_CMD` with big-endian u16 command ID prefix. +pub fn wdcl_command(dest: [u8; 4], command: u16, data: &[u8]) -> Vec { + let mut payload = Vec::with_capacity(2 + data.len()); + payload.push((command >> 8) as u8); + payload.push((command & 0xFF) as u8); + payload.extend_from_slice(data); + wdcl_frame(dest, WDCL_T_CMD, &payload) +} + +#[derive(Debug, Clone)] +pub struct LogFrame { + /// Milliseconds since device boot. + pub timestamp_ms: u32, + pub level: u8, + pub event: u16, + pub data: Vec, +} + +pub fn parse_log_frame(payload: &[u8]) -> Option { + if payload.len() < 8 { + return None; + } + let _flags = payload[0]; + let timestamp_ms = u32::from_be_bytes([payload[1], payload[2], payload[3], payload[4]]); + let level = payload[5]; + let event = u16::from_be_bytes([payload[6], payload[7]]); + let data = payload[8..].to_vec(); + Some(LogFrame { + timestamp_ms, + level, + event, + data, + }) +} + +/// Weave interface config (runtime spawn not yet implemented). +#[derive(Debug, Clone)] +pub struct WeaveInterfaceConfig { + pub name: String, + pub port: String, + pub configured_bitrate: Option, + pub mode: InterfaceMode, +} + +impl WeaveInterfaceConfig { + pub fn new(name: &str, port: &str) -> Self { + Self { + name: name.to_string(), + port: port.to_string(), + configured_bitrate: None, + mode: InterfaceMode::Full, + } + } +} + +// Runtime spawn is not wired yet. A production path needs WDCL discovery and +// handshake over serial, Ed25519 verification, per-peer sub-interfaces with +// PEERING_TIMEOUT/MULTI_IF_DEQUE_*, and interface_factory wiring. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_wdcl_message_types() { + assert_eq!(WDCL_T_DISCOVER, 0x00); + assert_eq!(WDCL_T_CONNECT, 0x01); + assert_eq!(WDCL_T_CMD, 0x02); + assert_eq!(WDCL_T_LOG, 0x03); + assert_eq!(WDCL_T_DISP, 0x04); + assert_eq!(WDCL_T_ENDPOINT_PKT, 0x05); + assert_eq!(WDCL_T_ENCAP_PROTO, 0x06); + } + + #[test] + fn test_wdcl_broadcast() { + assert_eq!(WDCL_BROADCAST, [0xFF, 0xFF, 0xFF, 0xFF]); + } + + #[test] + fn test_header_minsize() { + assert_eq!(HEADER_MINSIZE, 5); + } + + #[test] + fn test_weave_constants() { + assert_eq!(HW_MTU, 1024); + const { assert!(FIXED_MTU) }; + assert_eq!(PEERING_TIMEOUT, 20.0); + assert_eq!(BITRATE_GUESS, 250_000); + assert_eq!(DEFAULT_IFAC_SIZE, 16); + } + + #[test] + fn test_identity_sizes() { + assert_eq!(SWITCH_ID_LEN, 4); + assert_eq!(ENDPOINT_ID_LEN, 8); + assert_eq!(PUBKEY_SIZE, 32); + assert_eq!(SIGNATURE_LEN, 64); + assert_eq!(AUTH_LEN, ENDPOINT_ID_LEN + HMAC_LEN); + } + + #[test] + fn test_dedup_constants() { + assert_eq!(MULTI_IF_DEQUE_LEN, 48); + assert_eq!(MULTI_IF_DEQUE_TTL, 0.75); + } + + #[test] + fn test_wdcl_frame_encode() { + let frame = wdcl_frame([0x01, 0x02, 0x03, 0x04], WDCL_T_ENDPOINT_PKT, b"hello"); + assert_eq!(frame.len(), 10); + assert_eq!(&frame[..4], &[0x01, 0x02, 0x03, 0x04]); + assert_eq!(frame[4], WDCL_T_ENDPOINT_PKT); + assert_eq!(&frame[5..], b"hello"); + } + + #[test] + fn test_wdcl_frame_broadcast() { + let frame = wdcl_frame(WDCL_BROADCAST, WDCL_T_DISCOVER, &[0xAA]); + assert_eq!(&frame[..4], &WDCL_BROADCAST); + assert_eq!(frame[4], WDCL_T_DISCOVER); + assert_eq!(&frame[5..], &[0xAA]); + } + + #[test] + fn test_wdcl_frame_empty_payload() { + let frame = wdcl_frame([0; 4], WDCL_T_CMD, &[]); + assert_eq!(frame.len(), 5); + } + + #[test] + fn test_wdcl_parse_valid() { + let raw = [0x0A, 0x0B, 0x0C, 0x0D, WDCL_T_LOG, 0x01, 0x02]; + let parsed = wdcl_parse(&raw).unwrap(); + assert_eq!(parsed.addr, [0x0A, 0x0B, 0x0C, 0x0D]); + assert_eq!(parsed.msg_type, WDCL_T_LOG); + assert_eq!(parsed.payload, vec![0x01, 0x02]); + } + + #[test] + fn test_wdcl_parse_minimum() { + let raw = [0x00, 0x00, 0x00, 0x00, WDCL_T_DISCOVER]; + let parsed = wdcl_parse(&raw).unwrap(); + assert_eq!(parsed.addr, [0; 4]); + assert_eq!(parsed.msg_type, WDCL_T_DISCOVER); + assert!(parsed.payload.is_empty()); + } + + #[test] + fn test_wdcl_parse_too_short() { + assert!(wdcl_parse(&[]).is_none()); + assert!(wdcl_parse(&[0x00]).is_none()); + assert!(wdcl_parse(&[0x00, 0x00, 0x00, 0x00]).is_none()); + } + + #[test] + fn test_wdcl_frame_roundtrip() { + let addr = [0xDE, 0xAD, 0xBE, 0xEF]; + let payload = b"test data"; + let encoded = wdcl_frame(addr, WDCL_T_ENDPOINT_PKT, payload); + let decoded = wdcl_parse(&encoded).unwrap(); + assert_eq!(decoded.addr, addr); + assert_eq!(decoded.msg_type, WDCL_T_ENDPOINT_PKT); + assert_eq!(decoded.payload, payload); + } + + #[test] + fn test_wdcl_command() { + let dest = [0x01, 0x02, 0x03, 0x04]; + let frame = wdcl_command(dest, CMD_ENDPOINT_PKT, &[0xFF]); + let parsed = wdcl_parse(&frame).unwrap(); + assert_eq!(parsed.msg_type, WDCL_T_CMD); + assert_eq!(parsed.payload, vec![0x00, 0x01, 0xFF]); + } + + #[test] + fn test_wdcl_command_remote_display() { + let frame = wdcl_command([0; 4], CMD_REMOTE_DISPLAY, &[0x01]); + let parsed = wdcl_parse(&frame).unwrap(); + assert_eq!(parsed.payload[0], 0x0A); + assert_eq!(parsed.payload[1], 0x00); + assert_eq!(parsed.payload[2], 0x01); + } + + #[test] + fn test_parse_log_frame() { + // flags=0, ts=1000ms, level=INFO, event=EVT_SYSTEM_BOOT, data="ok" + let payload = [0x00, 0x00, 0x00, 0x03, 0xE8, 0x05, 0x00, 0x01, b'o', b'k']; + let frame = parse_log_frame(&payload).unwrap(); + assert_eq!(frame.timestamp_ms, 1000); + assert_eq!(frame.level, 5); + assert_eq!(frame.event, EVT_SYSTEM_BOOT); + assert_eq!(frame.data, b"ok"); + } + + #[test] + fn test_parse_log_frame_too_short() { + assert!(parse_log_frame(&[0; 7]).is_none()); + assert!(parse_log_frame(&[]).is_none()); + } + + #[test] + fn test_parse_log_frame_no_data() { + let payload = [0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x30, 0x00]; + let frame = parse_log_frame(&payload).unwrap(); + assert_eq!(frame.event, EVT_PROTO_WDCL_INIT); + assert!(frame.data.is_empty()); + } + + #[test] + fn test_physical_medium_from_u8() { + assert_eq!(PhysicalMedium::from_u8(0x03), Some(PhysicalMedium::W80211)); + assert_eq!(PhysicalMedium::from_u8(0x05), Some(PhysicalMedium::Lora)); + assert_eq!(PhysicalMedium::from_u8(0x10), Some(PhysicalMedium::Dma)); + assert_eq!(PhysicalMedium::from_u8(0x00), None); + assert_eq!(PhysicalMedium::from_u8(0xFF), None); + } + + #[test] + fn test_physical_medium_short_name() { + assert_eq!(PhysicalMedium::W80211.short_name(), "mw"); + assert_eq!(PhysicalMedium::Lora.short_name(), "lora"); + assert_eq!(PhysicalMedium::Ethernet.short_name(), "eth"); + } + + #[test] + fn test_device_log_level() { + assert_eq!(DeviceLogLevel::from_u8(0), Some(DeviceLogLevel::Force)); + assert_eq!(DeviceLogLevel::from_u8(5), Some(DeviceLogLevel::Info)); + assert_eq!(DeviceLogLevel::from_u8(9), Some(DeviceLogLevel::System)); + assert_eq!(DeviceLogLevel::from_u8(10), None); + } + + #[test] + fn test_config_defaults() { + let cfg = WeaveInterfaceConfig::new("weave0", "/dev/ttyUSB0"); + assert_eq!(cfg.name, "weave0"); + assert_eq!(cfg.port, "/dev/ttyUSB0"); + assert_eq!(cfg.mode, InterfaceMode::Full); + assert!(cfg.configured_bitrate.is_none()); + } +} diff --git a/crates/rns-link/Cargo.toml b/crates/rns-link/Cargo.toml new file mode 100644 index 0000000..759d5e6 --- /dev/null +++ b/crates/rns-link/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "rns-link" +description = "Link layer and encrypted channel for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[features] +default = ["std"] +std = ["rns-crypto/std", "rns-wire/std"] + +[dependencies] +rns-crypto = { workspace = true } +rns-wire = { workspace = true } +rns-identity = { workspace = true } +thiserror = { workspace = true } +zeroize = { workspace = true } +rmpv = { workspace = true } +rand = { workspace = true } +tracing = { workspace = true } +hex = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/rns-link/src/constants.rs b/crates/rns-link/src/constants.rs new file mode 100644 index 0000000..9d23ec3 --- /dev/null +++ b/crates/rns-link/src/constants.rs @@ -0,0 +1,99 @@ +//! Link-level protocol constants. + +/// X25519 public key size in bytes. +pub const KEYSIZE: usize = 32; + +/// Combined ephemeral public key size: X25519(32) + Ed25519(32) = 64 bytes. +pub const ECPUBSIZE: usize = 64; + +/// MTU signalling field size in bytes. +pub const LINK_MTU_SIZE: usize = 3; + +/// Seconds per hop for establishment timeout calculation. +pub const ESTABLISHMENT_TIMEOUT_PER_HOP: f64 = 6.0; + +/// Traffic timeout as a multiple of measured RTT. +pub const TRAFFIC_TIMEOUT_FACTOR: f64 = 6.0; + +/// RTT ceiling for keepalive scaling. +pub const KEEPALIVE_MAX_RTT: f64 = 1.75; + +/// Stale->closed timeout as a multiple of measured RTT. +pub const KEEPALIVE_TIMEOUT_FACTOR: f64 = 4.0; + +/// Grace seconds after going stale before teardown. +pub const STALE_GRACE: f64 = 5.0; + +pub const KEEPALIVE_MAX: f64 = 360.0; +pub const KEEPALIVE_MIN: f64 = 5.0; +pub const KEEPALIVE_DEFAULT: f64 = 360.0; + +/// Stale threshold as a multiple of keepalive interval. +pub const STALE_FACTOR: f64 = 2.0; + +pub const STALE_TIME_DEFAULT: f64 = 720.0; + +/// Max sleep per watchdog cycle. +pub const WATCHDOG_MAX_SLEEP: f64 = 5.0; + +/// Lower bound for traffic timeout; prevents sub-millisecond spins on tiny RTTs. +pub const TRAFFIC_TIMEOUT_FLOOR_MS: u64 = 5; + +pub const MODE_AES128_CBC: u8 = 0x00; +/// Default: AES-256-CBC. +pub const MODE_AES256_CBC: u8 = 0x01; +/// Reserved for future AES-256-GCM support. +pub const MODE_AES256_GCM: u8 = 0x02; +pub const MODE_OTP_RESERVED: u8 = 0x03; +pub const MODE_PQ_RESERVED_1: u8 = 0x04; +pub const MODE_PQ_RESERVED_2: u8 = 0x05; +pub const MODE_PQ_RESERVED_3: u8 = 0x06; +pub const MODE_PQ_RESERVED_4: u8 = 0x07; + +/// Encryption modes accepted by this implementation; others are advertised-but-refused. +pub const ENABLED_MODES: &[u8] = &[MODE_AES256_CBC]; + +pub const DEFAULT_MODE: u8 = MODE_AES256_CBC; + +pub const TIMEOUT: u8 = 0x01; +pub const INITIATOR_CLOSED: u8 = 0x02; +pub const DESTINATION_CLOSED: u8 = 0x03; + +pub const ACCEPT_NONE: u8 = 0x00; +/// Defer acceptance to an application callback. +pub const ACCEPT_APP: u8 = 0x01; +pub const ACCEPT_ALL: u8 = 0x02; + +/// Low 21 bits of the 24-bit MTU signalling value carry the MTU. +pub const MTU_BYTEMASK: u32 = 0x001F_FFFF; + +/// Bits 21-23 of the MTU signalling value carry the encryption mode. +pub const MODE_BYTEMASK: u32 = 0x00E0; + +/// Derived key length for AES-256-CBC: 32 bytes cipher key || 32 bytes HMAC key. +pub const AES256_DERIVED_KEY_LENGTH: usize = 64; + +/// Derived key length for AES-128-CBC: 16 bytes cipher key || 16 bytes HMAC key. +pub const AES128_DERIVED_KEY_LENGTH: usize = 32; + +/// Seconds of slack granted to a response beyond its nominal transfer time. +pub const RESPONSE_MAX_GRACE_TIME: f64 = 10.0; + +/// Sentinel byte sent by the initiator. +pub const KEEPALIVE_REQUEST: u8 = 0xFF; + +/// Sentinel byte returned by the destination. +pub const KEEPALIVE_RESPONSE: u8 = 0xFE; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_constants() { + assert_eq!(ECPUBSIZE, 64); + assert_eq!(STALE_TIME_DEFAULT, KEEPALIVE_DEFAULT * STALE_FACTOR); + assert!(ENABLED_MODES.contains(&MODE_AES256_CBC)); + assert!(!ENABLED_MODES.contains(&MODE_AES128_CBC)); + } +} diff --git a/crates/rns-link/src/encryption.rs b/crates/rns-link/src/encryption.rs new file mode 100644 index 0000000..f9cd12e --- /dev/null +++ b/crates/rns-link/src/encryption.rs @@ -0,0 +1,112 @@ +use crate::key_derivation::LinkKeys; +use zeroize::Zeroizing; + +/// Encrypt a plaintext frame with the link's session keys. +/// +/// Wire format: `IV(16) || AES-CBC(PKCS7(pt)) || HMAC-SHA256(32)`. +pub fn link_encrypt(keys: &LinkKeys, plaintext: &[u8]) -> Result, LinkCryptoError> { + // Token keying is signing(32) || encryption(32); Zeroizing wipes it on drop. + let mut combined_key = Zeroizing::new(Vec::with_capacity( + keys.signing_key.len() + keys.encryption_key.len(), + )); + combined_key.extend_from_slice(&keys.signing_key); + combined_key.extend_from_slice(&keys.encryption_key); + + rns_crypto::token::encrypt(plaintext, &combined_key) + .map_err(|_| LinkCryptoError::EncryptionFailed) +} + +/// Decrypt a ciphertext frame with the link's session keys. +/// +/// Errors are deliberately opaque — padding and HMAC failures are indistinguishable +/// to callers so timing side channels cannot leak which check failed. +pub fn link_decrypt(keys: &LinkKeys, ciphertext: &[u8]) -> Result, LinkCryptoError> { + let mut combined_key = Zeroizing::new(Vec::with_capacity( + keys.signing_key.len() + keys.encryption_key.len(), + )); + combined_key.extend_from_slice(&keys.signing_key); + combined_key.extend_from_slice(&keys.encryption_key); + + rns_crypto::token::decrypt(ciphertext, &combined_key) + .map_err(|_| LinkCryptoError::DecryptionFailed) +} + +#[derive(Debug, thiserror::Error)] +pub enum LinkCryptoError { + #[error("encryption failed")] + EncryptionFailed, + #[error("decryption failed")] + DecryptionFailed, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constants::MODE_AES256_CBC; + use crate::key_derivation::LinkKeys; + use rns_crypto::x25519::X25519PrivateKey; + + fn make_test_keys() -> (LinkKeys, LinkKeys) { + let prv_a = X25519PrivateKey::generate(); + let pub_a = prv_a.public_key(); + let prv_b = X25519PrivateKey::generate(); + let pub_b = prv_b.public_key(); + let link_id = [0x42; 16]; + let keys_a = LinkKeys::derive(&prv_a, &pub_b, &link_id, MODE_AES256_CBC).unwrap(); + let keys_b = LinkKeys::derive(&prv_b, &pub_a, &link_id, MODE_AES256_CBC).unwrap(); + (keys_a, keys_b) + } + + #[test] + fn test_encrypt_decrypt_roundtrip() { + let (keys_a, keys_b) = make_test_keys(); + let plaintext = b"Hello, Reticulum Link!"; + let ct = link_encrypt(&keys_a, plaintext).unwrap(); + let pt = link_decrypt(&keys_b, &ct).unwrap(); + assert_eq!(pt, plaintext); + } + + #[test] + fn test_bidirectional() { + let (keys_a, keys_b) = make_test_keys(); + + // A -> B + let msg1 = b"from A to B"; + let ct1 = link_encrypt(&keys_a, msg1).unwrap(); + let pt1 = link_decrypt(&keys_b, &ct1).unwrap(); + assert_eq!(pt1, msg1); + + // B -> A uses the same keys: the link is symmetric. + let msg2 = b"from B to A"; + let ct2 = link_encrypt(&keys_b, msg2).unwrap(); + let pt2 = link_decrypt(&keys_a, &ct2).unwrap(); + assert_eq!(pt2, msg2); + } + + #[test] + fn test_wrong_keys_fail() { + let (keys_a, _) = make_test_keys(); + let prv = X25519PrivateKey::generate(); + let pub_key = X25519PrivateKey::generate().public_key(); + let wrong_keys = LinkKeys::derive(&prv, &pub_key, &[0xFF; 16], MODE_AES256_CBC).unwrap(); + + let ct = link_encrypt(&keys_a, b"secret").unwrap(); + assert!(link_decrypt(&wrong_keys, &ct).is_err()); + } + + #[test] + fn test_tampered_ciphertext() { + let (keys_a, keys_b) = make_test_keys(); + let mut ct = link_encrypt(&keys_a, b"test").unwrap(); + ct[20] ^= 0xFF; + assert!(link_decrypt(&keys_b, &ct).is_err()); + } + + #[test] + fn test_empty_plaintext() { + let (keys_a, keys_b) = make_test_keys(); + let ct = link_encrypt(&keys_a, b"").unwrap(); + let pt = link_decrypt(&keys_b, &ct).unwrap(); + assert_eq!(pt, b""); + } +} diff --git a/crates/rns-link/src/handshake.rs b/crates/rns-link/src/handshake.rs new file mode 100644 index 0000000..264825c --- /dev/null +++ b/crates/rns-link/src/handshake.rs @@ -0,0 +1,574 @@ +use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; +use rns_crypto::sha::truncated_hash; +use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey}; +use zeroize::Zeroize; + +use crate::constants::{DEFAULT_MODE, ECPUBSIZE, LINK_MTU_SIZE}; +use crate::key_derivation::{LinkKeyError, LinkKeys}; +use crate::mtu_discovery::SignallingData; + +/// Ephemeral key pair generated per link (initiator or responder). +/// +/// The inner `X25519PrivateKey` and `Ed25519PrivateKey` zeroize themselves; +/// the `Drop` impl below propagates that through the composite struct. +pub struct EphemeralKeys { + pub x25519_prv: X25519PrivateKey, + pub x25519_pub: X25519PublicKey, + pub ed25519_prv: Ed25519PrivateKey, + pub ed25519_pub: Ed25519PublicKey, +} + +impl Zeroize for EphemeralKeys { + fn zeroize(&mut self) { + self.x25519_prv.zeroize(); + self.ed25519_prv.zeroize(); + } +} + +impl Drop for EphemeralKeys { + fn drop(&mut self) { + self.zeroize(); + } +} + +impl EphemeralKeys { + /// Generate a fresh ephemeral key pair for link establishment. + pub fn generate() -> Self { + let x25519_prv = X25519PrivateKey::generate(); + let x25519_pub = x25519_prv.public_key(); + let ed25519_prv = Ed25519PrivateKey::generate(); + let ed25519_pub = ed25519_prv.public_key(); + Self { + x25519_prv, + x25519_pub, + ed25519_prv, + ed25519_pub, + } + } +} + +/// Link request payload (Message 1: initiator -> destination). +/// +/// Wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)` — 67 bytes. +#[derive(Debug, Clone)] +pub struct LinkRequestData { + pub peer_x25519_pub: [u8; 32], + pub peer_ed25519_pub: [u8; 32], + pub signalling: SignallingData, +} + +impl LinkRequestData { + /// Serialize as `x25519_pub(32) || ed25519_pub(32) || signalling(3)`. + pub fn pack(keys: &EphemeralKeys, signalling: SignallingData) -> Vec { + let mut data = Vec::with_capacity(ECPUBSIZE + LINK_MTU_SIZE); + data.extend_from_slice(&keys.x25519_pub.to_bytes()); + data.extend_from_slice(&keys.ed25519_pub.to_bytes()); + data.extend_from_slice(&signalling.pack()); + data + } + + /// Parse a link request payload. + /// + /// Python accepts exactly the legacy 64-byte key payload or the modern + /// 67-byte key payload with signalling. Other lengths are dropped. + pub fn unpack(data: &[u8]) -> Result { + if data.len() < ECPUBSIZE { + return Err(HandshakeError::TooShort); + } + if data.len() != ECPUBSIZE && data.len() != ECPUBSIZE + LINK_MTU_SIZE { + return Err(HandshakeError::InvalidLength(data.len())); + } + + let mut x25519_pub = [0u8; 32]; + x25519_pub.copy_from_slice(&data[0..32]); + + let mut ed25519_pub = [0u8; 32]; + ed25519_pub.copy_from_slice(&data[32..64]); + + let signalling = if data.len() == ECPUBSIZE + LINK_MTU_SIZE { + SignallingData::unpack(&data[ECPUBSIZE..ECPUBSIZE + LINK_MTU_SIZE]).unwrap_or( + SignallingData::new(DEFAULT_MODE, rns_wire::constants::MTU as u32), + ) + } else { + SignallingData::new(DEFAULT_MODE, rns_wire::constants::MTU as u32) + }; + + Ok(Self { + peer_x25519_pub: x25519_pub, + peer_ed25519_pub: ed25519_pub, + signalling, + }) + } +} + +/// Compute the link ID from a link request. +/// +/// The hashable body is `flags_low_nibble || dest_hash || context || data[..ECPUBSIZE]` +/// — the signalling trailer is intentionally excluded so both sides agree on the same +/// link ID regardless of MTU/mode negotiation. +pub fn compute_link_id(destination_hash: &[u8; 16], request_data: &[u8]) -> [u8; 16] { + // LinkRequest(0x02) | DestinationType::Single(0x00); context is PacketContext::None. + let flags_low_nibble = 0x02u8; + let context = 0x00u8; + + let data_len = request_data.len().min(ECPUBSIZE); + let mut hashable = Vec::with_capacity(1 + 16 + 1 + data_len); + hashable.push(flags_low_nibble); + hashable.extend_from_slice(destination_hash); + hashable.push(context); + hashable.extend_from_slice(&request_data[..data_len]); + + truncated_hash(&hashable) +} + +/// Compute the link ID from a full raw packet (for transport relay paths). +pub fn compute_link_id_from_raw(raw: &[u8], header_type: rns_wire::flags::HeaderType) -> [u8; 16] { + rns_wire::hash::link_id_from_raw(raw, header_type) +} + +/// Link proof payload (Message 2: destination -> initiator). +/// +/// Wire format: `signature(64) || X25519_pub(32) || signalling(3)` — 99 bytes. +/// The signature covers `link_id || responder_x25519_pub || identity_ed25519_pub || signalling` +/// under the destination's long-term identity Ed25519 key. +#[derive(Debug, Clone)] +pub struct LinkProofData { + pub signature: [u8; 64], + pub responder_x25519_pub: [u8; 32], + pub signalling: SignallingData, +} + +impl LinkProofData { + /// Create and sign a link proof. + /// + /// The signature binds the link to the destination's long-term identity key, not + /// the ephemeral responder key — this is what authenticates the responder to the + /// initiator. + pub fn create( + identity_signing_key: &Ed25519PrivateKey, + responder_x25519_pub: &[u8; 32], + identity_ed25519_pub: &[u8; 32], + link_id: &[u8; 16], + signalling: SignallingData, + ) -> Self { + let sig_bytes = signalling.pack(); + let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3); + signed_data.extend_from_slice(link_id); + signed_data.extend_from_slice(responder_x25519_pub); + signed_data.extend_from_slice(identity_ed25519_pub); + signed_data.extend_from_slice(&sig_bytes); + + let signature = identity_signing_key.sign(&signed_data); + + Self { + signature, + responder_x25519_pub: *responder_x25519_pub, + signalling, + } + } + + /// Create a link proof using an external signer (e.g. YubiKey/PIV). + /// + /// Variant of [`LinkProofData::create`] for identities whose private key cannot + /// be exported — the closure receives the signed-data blob and must return a + /// 64-byte Ed25519 signature. + pub fn create_with( + sign_fn: F, + responder_x25519_pub: &[u8; 32], + identity_ed25519_pub: &[u8; 32], + link_id: &[u8; 16], + signalling: SignallingData, + ) -> Self + where + F: FnOnce(&[u8]) -> [u8; 64], + { + let sig_bytes = signalling.pack(); + let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3); + signed_data.extend_from_slice(link_id); + signed_data.extend_from_slice(responder_x25519_pub); + signed_data.extend_from_slice(identity_ed25519_pub); + signed_data.extend_from_slice(&sig_bytes); + + let signature = sign_fn(&signed_data); + + Self { + signature, + responder_x25519_pub: *responder_x25519_pub, + signalling, + } + } + + /// Serialize as `signature(64) || responder_x25519_pub(32) || signalling(3)`. + pub fn pack(&self) -> Vec { + let mut data = Vec::with_capacity(64 + 32 + LINK_MTU_SIZE); + data.extend_from_slice(&self.signature); + data.extend_from_slice(&self.responder_x25519_pub); + data.extend_from_slice(&self.signalling.pack()); + data + } + + /// Parse a proof payload, accepting exactly 96-byte legacy frames or + /// 99-byte frames with signalling. + pub fn unpack(data: &[u8]) -> Result { + if data.len() < 96 { + return Err(HandshakeError::TooShort); + } + if data.len() != 96 && data.len() != 96 + LINK_MTU_SIZE { + return Err(HandshakeError::InvalidLength(data.len())); + } + + let mut signature = [0u8; 64]; + signature.copy_from_slice(&data[0..64]); + + let mut responder_pub = [0u8; 32]; + responder_pub.copy_from_slice(&data[64..96]); + + let signalling = if data.len() == 96 + LINK_MTU_SIZE { + SignallingData::unpack(&data[96..96 + LINK_MTU_SIZE]).unwrap_or(SignallingData::new( + DEFAULT_MODE, + rns_wire::constants::MTU as u32, + )) + } else { + SignallingData::new(DEFAULT_MODE, rns_wire::constants::MTU as u32) + }; + + Ok(Self { + signature, + responder_x25519_pub: responder_pub, + signalling, + }) + } + + /// Verify the proof signature against the destination's identity public key. + pub fn validate( + &self, + identity_verify_key: &Ed25519PublicKey, + link_id: &[u8; 16], + peer_ed25519_pub: &[u8; 32], + ) -> bool { + let sig_bytes = self.signalling.pack(); + let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3); + signed_data.extend_from_slice(link_id); + signed_data.extend_from_slice(&self.responder_x25519_pub); + signed_data.extend_from_slice(peer_ed25519_pub); + signed_data.extend_from_slice(&sig_bytes); + + identity_verify_key + .verify(&signed_data, &self.signature) + .is_ok() + } +} + +/// Perform the ECDH handshake and derive session keys. +pub fn perform_handshake( + my_x25519_prv: &X25519PrivateKey, + peer_x25519_pub_bytes: &[u8; 32], + link_id: &[u8; 16], + mode: u8, +) -> Result { + let peer_pub = X25519PublicKey::from_bytes(peer_x25519_pub_bytes); + LinkKeys::derive(my_x25519_prv, &peer_pub, link_id, mode) +} + +#[derive(Debug, thiserror::Error)] +pub enum HandshakeError { + #[error("handshake data too short")] + TooShort, + #[error("invalid handshake data length: {0}")] + InvalidLength(usize), + #[error("invalid signature")] + InvalidSignature, + #[error("key derivation failed: {0}")] + KeyDerivation(#[from] LinkKeyError), + #[error("unsupported encryption mode: {0}")] + UnsupportedMode(u8), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_link_request_pack_unpack() { + let keys = EphemeralKeys::generate(); + let sig = SignallingData::new(1, 500); + let packed = LinkRequestData::pack(&keys, sig); + assert_eq!(packed.len(), ECPUBSIZE + LINK_MTU_SIZE); + + let unpacked = LinkRequestData::unpack(&packed).unwrap(); + assert_eq!(unpacked.peer_x25519_pub, keys.x25519_pub.to_bytes()); + assert_eq!(unpacked.peer_ed25519_pub, keys.ed25519_pub.to_bytes()); + assert_eq!(unpacked.signalling.mode, 1); + assert_eq!(unpacked.signalling.mtu, 500); + } + + #[test] + fn test_link_request_unpack_accepts_only_python_lengths() { + let keys = EphemeralKeys::generate(); + let sig = SignallingData::new(1, 500); + let modern = LinkRequestData::pack(&keys, sig); + + let legacy = &modern[..ECPUBSIZE]; + let unpacked = LinkRequestData::unpack(legacy).unwrap(); + assert_eq!(unpacked.peer_x25519_pub, keys.x25519_pub.to_bytes()); + assert_eq!(unpacked.peer_ed25519_pub, keys.ed25519_pub.to_bytes()); + assert_eq!(unpacked.signalling.mode, DEFAULT_MODE); + assert_eq!(unpacked.signalling.mtu, rns_wire::constants::MTU as u32); + + assert!(matches!( + LinkRequestData::unpack(&modern[..ECPUBSIZE - 1]), + Err(HandshakeError::TooShort) + )); + for len in [ECPUBSIZE + 1, ECPUBSIZE + 2] { + assert!(matches!( + LinkRequestData::unpack(&modern[..len]), + Err(HandshakeError::InvalidLength(actual)) if actual == len + )); + } + let mut over = modern.clone(); + over.push(0xCC); + assert!(matches!( + LinkRequestData::unpack(&over), + Err(HandshakeError::InvalidLength(actual)) if actual == ECPUBSIZE + LINK_MTU_SIZE + 1 + )); + } + + #[test] + fn test_link_id_computation() { + let keys = EphemeralKeys::generate(); + let sig = SignallingData::new(1, 500); + let packed = LinkRequestData::pack(&keys, sig); + let dest_hash = [0xAA; 16]; + + let link_id = compute_link_id(&dest_hash, &packed); + assert_eq!(link_id.len(), 16); + + let link_id2 = compute_link_id(&dest_hash, &packed); + assert_eq!(link_id, link_id2); + } + + #[test] + fn test_link_id_excludes_signalling() { + let keys = EphemeralKeys::generate(); + let dest_hash = [0xBB; 16]; + + let sig1 = SignallingData::new(1, 500); + let packed1 = LinkRequestData::pack(&keys, sig1); + + let sig2 = SignallingData::new(2, 1000); + let packed2 = LinkRequestData::pack(&keys, sig2); + + // Different signalling, same keys -> same link_id. + let id1 = compute_link_id(&dest_hash, &packed1); + let id2 = compute_link_id(&dest_hash, &packed2); + assert_eq!(id1, id2); + } + + #[test] + fn test_link_id_includes_dest_hash() { + let keys = EphemeralKeys::generate(); + let sig = SignallingData::new(1, 500); + let packed = LinkRequestData::pack(&keys, sig); + + let id1 = compute_link_id(&[0xAA; 16], &packed); + let id2 = compute_link_id(&[0xBB; 16], &packed); + assert_ne!(id1, id2); + } + + #[test] + fn test_link_id_from_raw_matches_components() { + let keys = EphemeralKeys::generate(); + let sig = SignallingData::new(1, 500); + let request_data = LinkRequestData::pack(&keys, sig); + let dest_hash = [0xCC; 16]; + + // Build a synthetic Header1 packet: LinkRequest + Single, 3 hops, no context. + let flags = 0x02u8; + let hops = 3u8; + let context = 0x00u8; + let mut raw = Vec::new(); + raw.push(flags); + raw.push(hops); + raw.extend_from_slice(&dest_hash); + raw.push(context); + raw.extend_from_slice(&request_data); + + let id_components = compute_link_id(&dest_hash, &request_data); + let id_raw = compute_link_id_from_raw(&raw, rns_wire::flags::HeaderType::Header1); + assert_eq!(id_components, id_raw); + } + + #[test] + fn test_link_proof_create_validate() { + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + let identity_ed25519_pub = identity_pub.to_bytes(); + + let responder_keys = EphemeralKeys::generate(); + let link_id = [0xAB; 16]; + let signalling = SignallingData::new(1, 500); + + let proof = LinkProofData::create( + &identity_key, + &responder_keys.x25519_pub.to_bytes(), + &identity_ed25519_pub, + &link_id, + signalling, + ); + + let packed = proof.pack(); + assert_eq!(packed.len(), 99); + + let unpacked = LinkProofData::unpack(&packed).unwrap(); + + assert!(unpacked.validate(&identity_pub, &link_id, &identity_ed25519_pub,)); + } + + #[test] + fn test_link_proof_unpack_accepts_only_python_lengths() { + let proof = LinkProofData { + signature: [0xAA; 64], + responder_x25519_pub: [0xBB; 32], + signalling: SignallingData::new(1, 500), + }; + let modern = proof.pack(); + + let legacy = LinkProofData::unpack(&modern[..96]).unwrap(); + assert_eq!(legacy.signature, [0xAA; 64]); + assert_eq!(legacy.responder_x25519_pub, [0xBB; 32]); + assert_eq!(legacy.signalling.mode, DEFAULT_MODE); + assert_eq!(legacy.signalling.mtu, rns_wire::constants::MTU as u32); + + assert!(matches!( + LinkProofData::unpack(&modern[..95]), + Err(HandshakeError::TooShort) + )); + for len in [97, 98] { + assert!(matches!( + LinkProofData::unpack(&modern[..len]), + Err(HandshakeError::InvalidLength(actual)) if actual == len + )); + } + let mut over = modern.clone(); + over.push(0xCC); + assert!(matches!( + LinkProofData::unpack(&over), + Err(HandshakeError::InvalidLength(100)) + )); + } + + #[test] + fn test_link_proof_wrong_identity_fails() { + let identity_key = Ed25519PrivateKey::generate(); + let wrong_key = Ed25519PrivateKey::generate(); + let wrong_pub = wrong_key.public_key(); + + let responder_keys = EphemeralKeys::generate(); + let identity_ed25519_pub = identity_key.public_key().to_bytes(); + let link_id = [0xAB; 16]; + let signalling = SignallingData::new(1, 500); + + let proof = LinkProofData::create( + &identity_key, + &responder_keys.x25519_pub.to_bytes(), + &identity_ed25519_pub, + &link_id, + signalling, + ); + + assert!(!proof.validate(&wrong_pub, &link_id, &identity_ed25519_pub,)); + } + + #[test] + fn test_full_handshake_key_agreement() { + let initiator_keys = EphemeralKeys::generate(); + let signalling = SignallingData::new(1, 500); + let request_data = LinkRequestData::pack(&initiator_keys, signalling); + let dest_hash = [0xDD; 16]; + + let link_id = compute_link_id(&dest_hash, &request_data); + + let _request = LinkRequestData::unpack(&request_data).unwrap(); + let responder_keys = EphemeralKeys::generate(); + + let initiator_session = perform_handshake( + &initiator_keys.x25519_prv, + &responder_keys.x25519_pub.to_bytes(), + &link_id, + DEFAULT_MODE, + ) + .unwrap(); + + let responder_session = perform_handshake( + &responder_keys.x25519_prv, + &initiator_keys.x25519_pub.to_bytes(), + &link_id, + DEFAULT_MODE, + ) + .unwrap(); + + assert_eq!(initiator_session.signing_key, responder_session.signing_key); + assert_eq!( + initiator_session.encryption_key, + responder_session.encryption_key + ); + } + + use proptest::prelude::*; + + proptest! { + /// LinkRequest round-trip over arbitrary key + signalling input. + /// The wire layout is `x25519_pub(32) || ed25519_pub(32) || + /// signalling(3)`, so pack → unpack → re-pack must be stable for + /// any bit pattern in the key fields (we don't need valid curve + /// points — the wire codec doesn't care). + #[test] + fn proptest_link_request_pack_unpack_roundtrip( + x25519_pub: [u8; 32], + ed25519_pub: [u8; 32], + mode in 0u8..=7, + mtu in 0u32..=crate::constants::MTU_BYTEMASK, + ) { + let signalling = SignallingData::new(mode, mtu); + // EphemeralKeys is the higher-level wrapper; we pack the + // bytes directly here to avoid generating live ECDH keys in + // the property loop. + let mut data = Vec::with_capacity(ECPUBSIZE + LINK_MTU_SIZE); + data.extend_from_slice(&x25519_pub); + data.extend_from_slice(&ed25519_pub); + data.extend_from_slice(&signalling.pack()); + + let unpacked = LinkRequestData::unpack(&data).unwrap(); + prop_assert_eq!(unpacked.peer_x25519_pub, x25519_pub); + prop_assert_eq!(unpacked.peer_ed25519_pub, ed25519_pub); + prop_assert_eq!(unpacked.signalling, signalling); + } + + /// LinkProof round-trip. Wire: `signature(64) || x25519_pub(32) || + /// signalling(3)` = 99 bytes. Like the request, we skip signature + /// validity and only check the packing byte layout — validity is + /// covered by the non-proptest tests. + #[test] + fn proptest_link_proof_pack_unpack_roundtrip( + signature: [u8; 64], + responder_x25519_pub: [u8; 32], + mode in 0u8..=7, + mtu in 0u32..=crate::constants::MTU_BYTEMASK, + ) { + let signalling = SignallingData::new(mode, mtu); + let proof = LinkProofData { + signature, + responder_x25519_pub, + signalling, + }; + let packed = proof.pack(); + prop_assert_eq!(packed.len(), 64 + 32 + LINK_MTU_SIZE); + + let unpacked = LinkProofData::unpack(&packed).unwrap(); + prop_assert_eq!(unpacked.signature, signature); + prop_assert_eq!(unpacked.responder_x25519_pub, responder_x25519_pub); + prop_assert_eq!(unpacked.signalling, signalling); + prop_assert_eq!(unpacked.pack(), packed); + } + } +} diff --git a/crates/rns-link/src/keepalive.rs b/crates/rns-link/src/keepalive.rs new file mode 100644 index 0000000..63581e8 --- /dev/null +++ b/crates/rns-link/src/keepalive.rs @@ -0,0 +1,285 @@ +use std::time::{Duration, Instant}; + +use crate::constants::*; + +/// Keepalive timing state for a single link. +/// +/// Only the initiator side schedules keepalives; the responder simply echoes them. +#[derive(Debug, Clone)] +pub struct KeepaliveState { + pub keepalive_interval: Duration, + pub stale_time: Duration, + pub is_initiator: bool, + pub last_inbound: Instant, + pub last_keepalive_sent: Option, + /// Last data packet received, excluding keepalives. + pub last_data: Instant, + pub last_outbound: Option, + pub last_proof: Option, + pub activated_at: Option, + /// Per-link ±10% random jitter so neighbouring links don't all fire at the same + /// phase and cause synchronised bursts on shared media. + jitter_offset: Duration, + jitter_negative: bool, +} + +impl KeepaliveState { + pub fn new(is_initiator: bool) -> Self { + use rand::Rng; + let mut rng = rand::thread_rng(); + let jitter_frac: f64 = rng.gen_range(-0.1..0.1); + let now = Instant::now(); + Self { + keepalive_interval: Duration::from_secs_f64(KEEPALIVE_DEFAULT), + stale_time: Duration::from_secs_f64(STALE_TIME_DEFAULT), + is_initiator, + last_inbound: now, + last_keepalive_sent: None, + last_data: now, + last_outbound: None, + last_proof: None, + activated_at: None, + jitter_offset: Duration::from_secs_f64(jitter_frac.abs() * KEEPALIVE_DEFAULT), + jitter_negative: jitter_frac < 0.0, + } + } + + /// Rescale the keepalive interval after a new RTT measurement. + /// + /// Interval scales linearly with RTT up to `KEEPALIVE_MAX_RTT`, then saturates. + /// Jitter is re-rolled so the ±10% spread is relative to the new interval. + pub fn update_from_rtt(&mut self, rtt: Duration) { + let rtt_secs = rtt.as_secs_f64(); + let scale_factor = KEEPALIVE_MAX / KEEPALIVE_MAX_RTT; + let interval = (rtt_secs * scale_factor).clamp(KEEPALIVE_MIN, KEEPALIVE_MAX); + self.keepalive_interval = Duration::from_secs_f64(interval); + self.stale_time = Duration::from_secs_f64(interval * STALE_FACTOR); + + use rand::Rng; + let mut rng = rand::thread_rng(); + let jitter_frac: f64 = rng.gen_range(-0.1..0.1); + self.jitter_offset = Duration::from_secs_f64(jitter_frac.abs() * interval); + self.jitter_negative = jitter_frac < 0.0; + } + + pub fn record_inbound(&mut self) { + self.last_inbound = Instant::now(); + } + + /// Record an inbound data packet (distinct from a keepalive beat). + pub fn record_data(&mut self) { + let now = Instant::now(); + self.last_data = now; + self.last_inbound = now; + } + + pub fn record_outbound(&mut self) { + self.last_outbound = Some(Instant::now()); + } + + pub fn record_proof(&mut self) { + let now = Instant::now(); + self.last_proof = Some(now); + self.last_inbound = now; + } + + pub fn mark_activated(&mut self) { + self.activated_at = Some(Instant::now()); + } + + /// Whether the initiator should emit a keepalive now (jitter applied). + pub fn should_send_keepalive(&self) -> bool { + let jittered = if self.jitter_negative { + self.keepalive_interval + .saturating_sub(self.jitter_offset) + .max(Duration::from_secs_f64(KEEPALIVE_MIN)) + } else { + self.keepalive_interval + self.jitter_offset + }; + + let inbound_elapsed = self.last_inbound.elapsed(); + let keepalive_elapsed = self + .last_keepalive_sent + .map(|t| t.elapsed()) + .unwrap_or(Duration::MAX); + + self.is_initiator && inbound_elapsed >= jittered && keepalive_elapsed >= jittered + } + + /// Whether the link should transition to STALE. + /// + /// Uses the most recent of inbound, proof, or activation as the baseline so a + /// link that just came up isn't immediately flagged stale on a quiet channel. + pub fn is_stale(&self) -> bool { + let mut latest = self.last_inbound; + if let Some(proof) = self.last_proof + && proof > latest + { + latest = proof; + } + if let Some(outbound) = self.last_outbound + && outbound > latest + { + latest = outbound; + } + if let Some(activated) = self.activated_at + && activated > latest + { + latest = activated; + } + latest.elapsed() >= self.stale_time + } + + /// How long to wait in STALE before tearing the link down. + pub fn stale_grace_timeout(&self, rtt: Duration) -> Duration { + rtt * KEEPALIVE_TIMEOUT_FACTOR as u32 + Duration::from_secs_f64(STALE_GRACE) + } + + pub fn mark_keepalive_sent(&mut self) { + self.last_keepalive_sent = Some(Instant::now()); + } + + pub fn since_inbound(&self) -> Duration { + self.last_inbound.elapsed() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::thread; + + #[test] + fn test_rtt_scaling() { + let mut ks = KeepaliveState::new(true); + + // Very fast link saturates at the minimum interval. + ks.update_from_rtt(Duration::from_millis(10)); + assert_eq!( + ks.keepalive_interval, + Duration::from_secs_f64(KEEPALIVE_MIN) + ); + + ks.update_from_rtt(Duration::from_millis(100)); + let expected = 0.1 * (KEEPALIVE_MAX / KEEPALIVE_MAX_RTT); + let diff = (ks.keepalive_interval.as_secs_f64() - expected).abs(); + assert!(diff < 0.01); + + // Very slow link saturates at the maximum interval. + ks.update_from_rtt(Duration::from_secs(2)); + assert_eq!( + ks.keepalive_interval, + Duration::from_secs_f64(KEEPALIVE_MAX) + ); + } + + #[test] + fn test_stale_time_follows_keepalive() { + let mut ks = KeepaliveState::new(true); + ks.update_from_rtt(Duration::from_millis(100)); + let expected_stale = + Duration::from_secs_f64(ks.keepalive_interval.as_secs_f64() * STALE_FACTOR); + // Tolerance absorbs sub-ns Duration round-trip drift. + let diff = ks.stale_time.as_secs_f64() - expected_stale.as_secs_f64(); + assert!( + diff.abs() < 1e-6, + "stale_time {:?} should match recomputed expected {:?}", + ks.stale_time, + expected_stale + ); + } + + #[test] + fn test_should_send_keepalive_timing() { + let mut ks = KeepaliveState::new(true); + ks.keepalive_interval = Duration::from_millis(50); + ks.jitter_offset = Duration::ZERO; + ks.jitter_negative = false; + + assert!(!ks.should_send_keepalive()); + + thread::sleep(Duration::from_millis(60)); + assert!(ks.should_send_keepalive()); + + // Non-initiator side never emits keepalives. + let mut ks2 = KeepaliveState::new(false); + ks2.keepalive_interval = Duration::from_millis(1); + ks2.jitter_offset = Duration::ZERO; + thread::sleep(Duration::from_millis(5)); + assert!(!ks2.should_send_keepalive()); + } + + #[test] + fn test_stale_detection() { + let mut ks = KeepaliveState::new(true); + ks.stale_time = Duration::from_millis(50); + + assert!(!ks.is_stale()); + thread::sleep(Duration::from_millis(60)); + assert!(ks.is_stale()); + + ks.record_inbound(); + assert!(!ks.is_stale()); + } + + #[test] + fn test_jitter_desynchronizes_keepalives() { + let links: Vec = (0..20) + .map(|_| { + let mut ks = KeepaliveState::new(true); + ks.update_from_rtt(Duration::from_millis(500)); + // Push last_inbound just past the interval boundary. + ks.last_inbound = Instant::now() - ks.keepalive_interval; + ks + }) + .collect(); + + let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count(); + + let links_past: Vec = (0..20) + .map(|_| { + let mut ks = KeepaliveState::new(true); + ks.update_from_rtt(Duration::from_millis(500)); + ks.last_inbound = Instant::now() - ks.keepalive_interval * 2; + ks + }) + .collect(); + let firing_past: usize = links_past + .iter() + .filter(|ks| ks.should_send_keepalive()) + .count(); + + assert!( + firing < 20, + "jitter should prevent all links firing simultaneously" + ); + assert_eq!( + firing_past, 20, + "all links should fire well past the interval" + ); + } + + #[test] + fn test_jitter_bounded() { + for _ in 0..100 { + let mut ks = KeepaliveState::new(true); + ks.update_from_rtt(Duration::from_millis(500)); + let max_jitter = ks.keepalive_interval.as_secs_f64() * 0.1; + assert!( + ks.jitter_offset.as_secs_f64() <= max_jitter + 0.001, + "jitter {:?} exceeds ±10% of interval {:?}", + ks.jitter_offset, + ks.keepalive_interval + ); + } + } + + #[test] + fn test_option_sentinels() { + let ks = KeepaliveState::new(true); + assert!(ks.last_keepalive_sent.is_none()); + assert!(ks.last_outbound.is_none()); + assert!(ks.last_proof.is_none()); + assert!(ks.activated_at.is_none()); + } +} diff --git a/crates/rns-link/src/key_derivation.rs b/crates/rns-link/src/key_derivation.rs new file mode 100644 index 0000000..d334c93 --- /dev/null +++ b/crates/rns-link/src/key_derivation.rs @@ -0,0 +1,109 @@ +use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey}; +use zeroize::{Zeroize, Zeroizing}; + +use crate::constants::{ + AES128_DERIVED_KEY_LENGTH, AES256_DERIVED_KEY_LENGTH, MODE_AES128_CBC, MODE_AES256_CBC, +}; + +/// Derived session keys for a link. +#[derive(Clone)] +pub struct LinkKeys { + /// HMAC-SHA256 signing key. + pub signing_key: Vec, + /// AES encryption key. + pub encryption_key: Vec, +} + +impl LinkKeys { + /// Derive link session keys from an ECDH exchange. + /// + /// Runs `HKDF-SHA256(ECDH(my_prv, peer_pub), salt = link_id)` and splits the + /// output into `signing_key || encryption_key`. Intermediate shared secrets + /// are zeroized as soon as HKDF consumes them. + pub fn derive( + my_prv: &X25519PrivateKey, + peer_pub: &X25519PublicKey, + link_id: &[u8; 16], + mode: u8, + ) -> Result { + let derived_key_length = match mode { + MODE_AES128_CBC => AES128_DERIVED_KEY_LENGTH, + MODE_AES256_CBC => AES256_DERIVED_KEY_LENGTH, + _ => return Err(LinkKeyError::UnsupportedMode(mode)), + }; + + let mut shared_key = my_prv.exchange(peer_pub); + + let derived_result = + rns_crypto::hkdf::hkdf_sha256(derived_key_length, &shared_key, Some(link_id), None) + .map_err(|_| LinkKeyError::HkdfFailed); + shared_key.zeroize(); + let derived = Zeroizing::new(derived_result?); + + let half = derived_key_length / 2; + let signing_key = derived[..half].to_vec(); + let encryption_key = derived[half..].to_vec(); + + Ok(Self { + signing_key, + encryption_key, + }) + } +} + +impl Drop for LinkKeys { + fn drop(&mut self) { + self.signing_key.zeroize(); + self.encryption_key.zeroize(); + } +} + +#[derive(Debug, thiserror::Error)] +pub enum LinkKeyError { + #[error("unsupported encryption mode: {0}")] + UnsupportedMode(u8), + #[error("HKDF key derivation failed")] + HkdfFailed, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_derive_aes256() { + let prv_a = X25519PrivateKey::generate(); + let pub_a = prv_a.public_key(); + let prv_b = X25519PrivateKey::generate(); + let pub_b = prv_b.public_key(); + let link_id = [0xAA; 16]; + + let keys_a = LinkKeys::derive(&prv_a, &pub_b, &link_id, MODE_AES256_CBC).unwrap(); + let keys_b = LinkKeys::derive(&prv_b, &pub_a, &link_id, MODE_AES256_CBC).unwrap(); + + assert_eq!(keys_a.signing_key, keys_b.signing_key); + assert_eq!(keys_a.encryption_key, keys_b.encryption_key); + assert_eq!(keys_a.signing_key.len(), 32); + assert_eq!(keys_a.encryption_key.len(), 32); + } + + #[test] + fn test_derive_different_link_ids() { + let prv_a = X25519PrivateKey::generate(); + let pub_b = X25519PrivateKey::generate().public_key(); + + let keys1 = LinkKeys::derive(&prv_a, &pub_b, &[0x01; 16], MODE_AES256_CBC).unwrap(); + let keys2 = LinkKeys::derive(&prv_a, &pub_b, &[0x02; 16], MODE_AES256_CBC).unwrap(); + + assert_ne!(keys1.signing_key, keys2.signing_key); + assert_ne!(keys1.encryption_key, keys2.encryption_key); + } + + #[test] + fn test_unsupported_mode() { + let prv = X25519PrivateKey::generate(); + let pub_key = prv.public_key(); + let result = LinkKeys::derive(&prv, &pub_key, &[0; 16], 0xFF); + assert!(result.is_err()); + } +} diff --git a/crates/rns-link/src/lib.rs b/crates/rns-link/src/lib.rs new file mode 100644 index 0000000..f628754 --- /dev/null +++ b/crates/rns-link/src/lib.rs @@ -0,0 +1,12 @@ +//! Encrypted point-to-point Links between two Reticulum destinations. +//! LR/LRPROOF handshake → AES-256 + HMAC-SHA256 session, MTU discovery, +//! keepalives, request/response. Python reference: `RNS/Link.py`. + +pub mod constants; +pub mod encryption; +pub mod handshake; +pub mod keepalive; +pub mod key_derivation; +pub mod link; +pub mod mtu_discovery; +pub mod request; diff --git a/crates/rns-link/src/link.rs b/crates/rns-link/src/link.rs new file mode 100644 index 0000000..f2ab482 --- /dev/null +++ b/crates/rns-link/src/link.rs @@ -0,0 +1,2239 @@ +use std::time::{Duration, Instant}; + +use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; +use rns_crypto::sha::truncated_hash; + +use crate::constants::*; +use crate::encryption::{LinkCryptoError, link_decrypt, link_encrypt}; +use crate::handshake::{ + EphemeralKeys, HandshakeError, LinkProofData, LinkRequestData, compute_link_id, + perform_handshake, +}; +use crate::keepalive::KeepaliveState; +use crate::key_derivation::LinkKeys; +use crate::mtu_discovery::SignallingData; +use crate::request::{RequestReceipt, RequestState}; + +/// Link lifecycle states. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LinkState { + /// Link request sent or received, awaiting proof. + Pending = 0x00, + /// ECDH complete, awaiting the RTT round-trip that activates the link. + Handshake = 0x01, + /// Link fully established; encrypted traffic flows. + Active = 0x02, + /// No inbound traffic for `stale_time`. + Stale = 0x03, + /// Link torn down and keys purged. + Closed = 0x04, +} + +/// Reason for link closure. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CloseReason { + Timeout, + InitiatorClosed, + DestinationClosed, +} + +/// Resource acceptance strategy. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ResourceStrategy { + #[default] + AcceptNone, + AcceptApp, + AcceptAll, +} + +/// Result of checking whether to accept a resource. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResourceAcceptance { + Accept, + Reject, + /// Application must decide (AcceptApp strategy). + AskApp, +} + +/// Outbound resource state as observed by the link. +/// +/// Duplicates a subset of `rns-protocol`'s `ResourceState` so `rns-link` can make +/// readiness decisions without a reverse dependency on `rns-protocol`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OutboundResourceState { + Transferring, + /// All parts sent, awaiting the receiver's proof. + AwaitingProof, + Complete, + Failed, +} + +/// The result of a `request()` call indicating how the request should be sent. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RequestSendMode { + /// Request fits in a single packet (data size <= MDU). + Packet(Vec), + /// Request exceeds MDU and must be sent as a resource transfer. + /// Contains the packed request data that should be wrapped in a Resource. + Resource(Vec), +} + +fn msgpack_value_from_bytes_or_binary(data: &[u8]) -> rmpv::Value { + let mut cursor = std::io::Cursor::new(data); + match rmpv::decode::read_value(&mut cursor) { + Ok(value) if cursor.position() as usize == data.len() => value, + _ => rmpv::Value::Binary(data.to_vec()), + } +} + +fn msgpack_value_to_bytes(value: &rmpv::Value) -> Result, LinkCryptoError> { + if let Some(bytes) = value.as_slice() { + Ok(bytes.to_vec()) + } else if let Some(text) = value.as_str() { + Ok(text.as_bytes().to_vec()) + } else { + let mut encoded = Vec::new(); + rmpv::encode::write_value(&mut encoded, value) + .map_err(|_| LinkCryptoError::DecryptionFailed)?; + Ok(encoded) + } +} + +/// An encrypted bidirectional tunnel between two peers. +/// +/// The state machine is driven by `tick()` calls from the owning actor/runtime; +/// there is no internal watchdog thread. +pub struct Link { + /// Truncated SHA-256 of the request's hashable part. + pub link_id: [u8; 16], + pub state: LinkState, + pub is_initiator: bool, + pub mode: u8, + + ephemeral_keys: Option, + peer_x25519_pub: Option<[u8; 32]>, + /// Peer's Ed25519 identity key — used to verify the link proof signature. + peer_ed25519_pub: Option<[u8; 32]>, + + /// Identity signing key for `Link::sign()` and local-side proofs. + sig_prv: Option, + + session_keys: Option, + + pub request_time: Instant, + pub rtt: Option, + pub establishment_timeout: Duration, + pub activated_at: Option, + pub stale_since: Option, + + pub keepalive: KeepaliveState, + + pub mtu: u32, + /// Maximum data unit for encrypted payloads (derived from `mtu`). + pub mdu: usize, + + pub resource_strategy: ResourceStrategy, + pub pending_requests: Vec, + pub incoming_resources: Vec<[u8; 32]>, + pub outgoing_resources: Vec<[u8; 32]>, + pub outgoing_resource_states: Vec, + pub incoming_resource_count: usize, + + /// Total bytes transferred during handshake establishment. + pub establishment_cost: usize, + /// Bytes/sec during establishment: `establishment_cost / rtt`. + pub establishment_rate: Option, + /// Expected in-flight data rate (bits/sec), refreshed after each resource transfer. + pub expected_rate: Option, + + pub destination_hash: [u8; 16], + + remote_identity_pub: Option<[u8; 64]>, + pub identified: bool, + + pub tx_bytes: u64, + pub rx_bytes: u64, + pub tx_count: u64, + pub rx_count: u64, + + /// RSSI in dBm, populated from LoRa/radio interfaces. + pub rssi: Option, + /// Signal-to-noise ratio in dB. + pub snr: Option, + /// Link quality indicator in `[0.0, 1.0]`. + pub q: Option, + + pub has_channel: bool, + + pub packet_callback: Option, + /// Called when a resource transfer begins; returns `true` to accept. + pub resource_callback: Option, + pub remote_identified_callback: Option, + /// Fires when the link transitions to `Active`. + pub link_established_callback: Option, + pub link_closed_callback: Option, +} + +/// Callback for decrypted link-packet payloads. +pub type PacketCallback = Box; +/// Callback for accepting or rejecting an incoming resource transfer. +pub type ResourceCallback = Box bool + Send + Sync>; +/// Callback fired after the remote peer identifies on the link. +pub type RemoteIdentifiedCallback = Box; +/// Callback fired for link lifecycle transitions. +pub type LinkCallback = Box; +/// Parsed REQUEST data: `(request_id, path_hash, timestamp, payload)`. +pub type ParsedRequestData = ([u8; 16], [u8; 16], f64, Vec); + +impl Link { + /// Create an outbound link and return `(link, request_data)` to transmit. + #[tracing::instrument( + level = "debug", + name = "link.handshake", + skip_all, + fields( + destination_hash = %hex::encode(&destination_hash[..8]), + role = "initiator", + hops, + ), + )] + pub fn new_initiator(destination_hash: [u8; 16], hops: u8) -> (Self, Vec) { + let ephemeral_keys = EphemeralKeys::generate(); + let signalling = SignallingData::new(DEFAULT_MODE, rns_wire::constants::MTU as u32); + let request_data = LinkRequestData::pack(&ephemeral_keys, signalling); + let link_id = compute_link_id(&destination_hash, &request_data); + + // Base timeout scales with hops. Callers may extend it via + // extend_establishment_timeout() once they know the first-hop latency. + let timeout_secs = ESTABLISHMENT_TIMEOUT_PER_HOP * (hops.max(1) as f64); + let now = Instant::now(); + + let establishment_cost = request_data.len(); + + let link = Self { + link_id, + state: LinkState::Pending, + is_initiator: true, + mode: DEFAULT_MODE, + ephemeral_keys: Some(ephemeral_keys), + peer_x25519_pub: None, + peer_ed25519_pub: None, + // Initiator supplies its signing key later via set_signing_key(). + sig_prv: None, + session_keys: None, + request_time: now, + rtt: None, + establishment_timeout: Duration::from_secs_f64(timeout_secs), + activated_at: None, + stale_since: None, + keepalive: KeepaliveState::new(true), + mtu: rns_wire::constants::MTU as u32, + mdu: rns_wire::constants::ENCRYPTED_MDU, + resource_strategy: ResourceStrategy::default(), + pending_requests: Vec::new(), + incoming_resources: Vec::new(), + outgoing_resources: Vec::new(), + outgoing_resource_states: Vec::new(), + incoming_resource_count: 0, + establishment_cost, + establishment_rate: None, + expected_rate: None, + destination_hash, + remote_identity_pub: None, + identified: false, + tx_bytes: 0, + rx_bytes: 0, + tx_count: 0, + rx_count: 0, + rssi: None, + snr: None, + q: None, + has_channel: false, + packet_callback: None, + resource_callback: None, + remote_identified_callback: None, + link_established_callback: None, + link_closed_callback: None, + }; + + (link, request_data) + } + + /// Extend the establishment timeout, typically by the transport's first-hop RTT. + pub fn extend_establishment_timeout(&mut self, additional_secs: f64) { + self.establishment_timeout += Duration::from_secs_f64(additional_secs); + } + + /// Handle a received link proof (initiator side, Message 2). + /// + /// Verifies the signature, runs ECDH, derives session keys, and returns the + /// encrypted RTT measurement (Message 3) to hand back to the responder. + pub fn validate_proof( + &mut self, + proof_data: &[u8], + identity_verify_key: &Ed25519PublicKey, + identity_ed25519_pub_bytes: &[u8; 32], + ) -> Result, HandshakeError> { + if self.state != LinkState::Pending { + return Err(HandshakeError::InvalidSignature); + } + + // Python reads the LRPROOF mode byte before validating the exact proof + // length; a wrong mode closes the pending link even for otherwise odd + // proof lengths. + if proof_data.len() > 96 { + let proof_mode = (proof_data[96] & MODE_BYTEMASK as u8) >> 5; + if proof_mode != self.mode { + self.state = LinkState::Closed; + return Err(HandshakeError::InvalidSignature); + } + } + + let proof = LinkProofData::unpack(proof_data)?; + + if proof.signalling.mode != self.mode { + self.state = LinkState::Closed; + return Err(HandshakeError::InvalidSignature); + } + + self.establishment_cost += proof_data.len(); + + // Verify the signature before deriving session keys so we never hold keys + // tied to an unvalidated proof, even transiently. + if !proof.validate( + identity_verify_key, + &self.link_id, + identity_ed25519_pub_bytes, + ) { + self.state = LinkState::Closed; + return Err(HandshakeError::InvalidSignature); + } + + self.peer_x25519_pub = Some(proof.responder_x25519_pub); + self.peer_ed25519_pub = Some(*identity_ed25519_pub_bytes); + + let ephemeral = self + .ephemeral_keys + .as_ref() + .ok_or(HandshakeError::InvalidSignature)?; + + let keys = perform_handshake( + &ephemeral.x25519_prv, + &proof.responder_x25519_pub, + &self.link_id, + self.mode, + )?; + + self.session_keys = Some(keys); + self.state = LinkState::Handshake; + tracing::debug!(link_id = ?self.link_id, "link state -> Handshake (initiator)"); + + let rtt = self.request_time.elapsed(); + self.rtt = Some(rtt); + + self.state = LinkState::Active; + self.activated_at = Some(Instant::now()); + tracing::debug!( + link_id = ?self.link_id, + rtt_ms = rtt.as_millis() as u64, + "link state -> Active (initiator)" + ); + + // Seed the keepalive baseline so stale detection starts from activation. + self.keepalive.mark_activated(); + + let rtt_secs_val = rtt.as_secs_f64(); + if rtt_secs_val > 0.0 && self.establishment_cost > 0 { + self.establishment_rate = Some(self.establishment_cost as f64 / rtt_secs_val); + } + + self.keepalive.update_from_rtt(rtt); + + if proof.signalling.mtu > 0 { + self.mtu = self.mtu.min(proof.signalling.mtu); + } + self.update_mdu(); + + // RTT is carried as a msgpack f64 so both ends see the same encoding. + let rtt_secs = rtt.as_secs_f64(); + let mut rtt_bytes = Vec::new(); + rmpv::encode::write_value(&mut rtt_bytes, &rmpv::Value::F64(rtt_secs)) + .map_err(|_| HandshakeError::InvalidSignature)?; + let encrypted_rtt = self + .encrypt(&rtt_bytes) + .map_err(|_| HandshakeError::InvalidSignature)?; + + Ok(encrypted_rtt) + } + + /// Create an inbound link (responder side) in response to a LINKREQUEST. + /// + /// Runs ECDH eagerly and returns the packed proof bytes to send back. + #[tracing::instrument( + level = "debug", + name = "link.handshake", + skip_all, + fields( + destination_hash = %hex::encode(&destination_hash[..8]), + role = "responder", + hops, + ), + )] + pub fn new_responder( + request_data: &[u8], + identity_signing_key: &Ed25519PrivateKey, + destination_hash: [u8; 16], + hops: u8, + ) -> Result<(Self, Vec), HandshakeError> { + let request = LinkRequestData::unpack(request_data)?; + let link_id = compute_link_id(&destination_hash, request_data); + + if request.signalling.mode != MODE_AES128_CBC && request.signalling.mode != MODE_AES256_CBC + { + return Err(HandshakeError::UnsupportedMode(request.signalling.mode)); + } + + let responder_keys = EphemeralKeys::generate(); + + let session_keys = perform_handshake( + &responder_keys.x25519_prv, + &request.peer_x25519_pub, + &link_id, + request.signalling.mode, + )?; + + // The proof binds the link to the responder's long-term identity key, not + // its ephemeral one — that's what lets the initiator authenticate us. + let identity_ed25519_pub = identity_signing_key.public_key().to_bytes(); + let signalling = + SignallingData::new(request.signalling.mode, rns_wire::constants::MTU as u32); + let proof = LinkProofData::create( + identity_signing_key, + &responder_keys.x25519_pub.to_bytes(), + &identity_ed25519_pub, + &link_id, + signalling, + ); + let proof_data = proof.pack(); + + let timeout_secs = ESTABLISHMENT_TIMEOUT_PER_HOP * (hops.max(1) as f64) + KEEPALIVE_DEFAULT; + let now = Instant::now(); + + let establishment_cost = request_data.len() + proof_data.len(); + + let link = Self { + link_id, + state: LinkState::Handshake, + is_initiator: false, + mode: request.signalling.mode, + ephemeral_keys: Some(responder_keys), + peer_x25519_pub: Some(request.peer_x25519_pub), + peer_ed25519_pub: Some(request.peer_ed25519_pub), + sig_prv: Some(Ed25519PrivateKey::from_bytes( + &identity_signing_key.to_bytes(), + )), + session_keys: Some(session_keys), + request_time: now, + rtt: None, + establishment_timeout: Duration::from_secs_f64(timeout_secs), + activated_at: None, + stale_since: None, + keepalive: KeepaliveState::new(false), + mtu: request.signalling.mtu.min(rns_wire::constants::MTU as u32), + mdu: rns_wire::constants::ENCRYPTED_MDU, + resource_strategy: ResourceStrategy::default(), + pending_requests: Vec::new(), + incoming_resources: Vec::new(), + outgoing_resources: Vec::new(), + outgoing_resource_states: Vec::new(), + incoming_resource_count: 0, + establishment_cost, + establishment_rate: None, + expected_rate: None, + destination_hash, + remote_identity_pub: None, + identified: false, + tx_bytes: 0, + rx_bytes: 0, + tx_count: 0, + rx_count: 0, + rssi: None, + snr: None, + q: None, + has_channel: false, + packet_callback: None, + resource_callback: None, + remote_identified_callback: None, + link_established_callback: None, + link_closed_callback: None, + }; + + Ok((link, proof_data)) + } + + /// Handle the RTT packet (Message 3) and activate the link. + pub fn receive_rtt_packet(&mut self, encrypted_data: &[u8]) -> Result<(), HandshakeError> { + if self.state != LinkState::Handshake { + return Err(HandshakeError::InvalidSignature); + } + + self.establishment_cost += encrypted_data.len(); + + let plaintext = self + .decrypt(encrypted_data) + .map_err(|_| HandshakeError::InvalidSignature)?; + + // RTT is a msgpack f64 — see matching encode in validate_proof(). + if let Ok(value) = rmpv::decode::read_value(&mut &plaintext[..]) + && let Some(peer_rtt) = value.as_f64() + { + let local_rtt = self.request_time.elapsed().as_secs_f64(); + let rtt = local_rtt.max(peer_rtt); + let rtt_dur = Duration::from_secs_f64(rtt); + self.rtt = Some(rtt_dur); + self.keepalive.update_from_rtt(rtt_dur); + } + + self.state = LinkState::Active; + self.activated_at = Some(Instant::now()); + self.keepalive.mark_activated(); + self.update_mdu(); + tracing::debug!(link_id = ?self.link_id, "link state -> Active (responder)"); + + if let Some(rtt) = self.rtt { + let rtt_secs = rtt.as_secs_f64(); + if rtt_secs > 0.0 && self.establishment_cost > 0 { + self.establishment_rate = Some(self.establishment_cost as f64 / rtt_secs); + } + } + + Ok(()) + } + + /// AES-CBC encrypt with the initiator-to-responder session key. + pub fn encrypt(&self, plaintext: &[u8]) -> Result, LinkCryptoError> { + let keys = self + .session_keys + .as_ref() + .ok_or(LinkCryptoError::EncryptionFailed)?; + link_encrypt(keys, plaintext) + } + + /// AES-CBC decrypt and verify the HMAC tag. + pub fn decrypt(&self, ciphertext: &[u8]) -> Result, LinkCryptoError> { + let keys = self + .session_keys + .as_ref() + .ok_or(LinkCryptoError::DecryptionFailed)?; + link_decrypt(keys, ciphertext) + } + + /// Build a LINKIDENTIFY payload that reveals the initiator's identity. + /// + /// Wire format (after encryption): `public_key(64) || signature(64)`, where + /// the signature covers `link_id(16) || public_key(64)`. Send with context + /// LINKIDENTIFY (0xFB). + pub fn identify( + &self, + identity_pub_key: &[u8; 64], + identity_signing_key: &Ed25519PrivateKey, + ) -> Result, LinkCryptoError> { + if !self.is_initiator || self.state != LinkState::Active { + return Err(LinkCryptoError::EncryptionFailed); + } + + let mut signed_data = Vec::with_capacity(16 + 64); + signed_data.extend_from_slice(&self.link_id); + signed_data.extend_from_slice(identity_pub_key); + + let signature = identity_signing_key.sign(&signed_data); + + let mut proof_data = Vec::with_capacity(128); + proof_data.extend_from_slice(identity_pub_key); + proof_data.extend_from_slice(&signature); + + self.encrypt(&proof_data) + } + + /// Identify with an external signer (e.g. hardware identity). + /// + /// Variant of [`Link::identify`] for keys that cannot be exported. + pub fn identify_with( + &self, + identity_pub_key: &[u8; 64], + sign_fn: F, + ) -> Result, LinkCryptoError> + where + F: FnOnce(&[u8]) -> [u8; 64], + { + if !self.is_initiator || self.state != LinkState::Active { + return Err(LinkCryptoError::EncryptionFailed); + } + + let mut signed_data = Vec::with_capacity(16 + 64); + signed_data.extend_from_slice(&self.link_id); + signed_data.extend_from_slice(identity_pub_key); + + let signature = sign_fn(&signed_data); + + let mut proof_data = Vec::with_capacity(128); + proof_data.extend_from_slice(identity_pub_key); + proof_data.extend_from_slice(&signature); + + self.encrypt(&proof_data) + } + + /// Verify a received LINKIDENTIFY and record the remote identity key. + pub fn handle_identification( + &mut self, + encrypted_data: &[u8], + ) -> Result<[u8; 64], LinkCryptoError> { + if self.state != LinkState::Active { + return Err(LinkCryptoError::DecryptionFailed); + } + + let plaintext = self.decrypt(encrypted_data)?; + + // Exactly one public_key(64) || signature(64) payload. + if plaintext.len() != 128 { + return Err(LinkCryptoError::DecryptionFailed); + } + + let mut public_key = [0u8; 64]; + public_key.copy_from_slice(&plaintext[..64]); + + let mut signature = [0u8; 64]; + signature.copy_from_slice(&plaintext[64..128]); + + let mut signed_data = Vec::with_capacity(16 + 64); + signed_data.extend_from_slice(&self.link_id); + signed_data.extend_from_slice(&public_key); + + // In the 64-byte identity blob, bytes 32..64 are the Ed25519 verifying key. + let mut ed25519_pub_bytes = [0u8; 32]; + ed25519_pub_bytes.copy_from_slice(&public_key[32..64]); + + let verify_key = Ed25519PublicKey::from_bytes(&ed25519_pub_bytes) + .map_err(|_| LinkCryptoError::DecryptionFailed)?; + if verify_key.verify(&signed_data, &signature).is_err() { + return Err(LinkCryptoError::DecryptionFailed); + } + + self.remote_identity_pub = Some(public_key); + self.identified = true; + + Ok(public_key) + } + + /// Remote identity public key, if the peer has identified itself. + pub fn remote_identity(&self) -> Option<&[u8; 64]> { + self.remote_identity_pub.as_ref() + } + + /// Build a REQUEST payload and return `(encrypted, request_id)`. + /// + /// Plaintext is msgpack `[timestamp_f64, sha256_trunc(path), data]`. Send with + /// context REQUEST (0x09); the returned `request_id` matches what the remote + /// side will compute. + pub fn request( + &mut self, + path: &str, + data: Option<&[u8]>, + timeout: Duration, + ) -> Result<(Vec, [u8; 16]), LinkCryptoError> { + let data_value = data + .map(msgpack_value_from_bytes_or_binary) + .unwrap_or(rmpv::Value::Nil); + self.request_value(path, data_value, timeout) + } + + /// Build a REQUEST payload with a MsgPack string body. + /// + /// Python Reticulum preserves Python `str` request bodies as MsgPack + /// strings. Some utilities, including rncp fetch, expect that exact type. + pub fn request_str( + &mut self, + path: &str, + data: &str, + timeout: Duration, + ) -> Result<(Vec, [u8; 16]), LinkCryptoError> { + self.request_value(path, rmpv::Value::String(data.into()), timeout) + } + + fn request_value( + &mut self, + path: &str, + data_value: rmpv::Value, + timeout: Duration, + ) -> Result<(Vec, [u8; 16]), LinkCryptoError> { + if self.state != LinkState::Active { + return Err(LinkCryptoError::EncryptionFailed); + } + + let path_hash = truncated_hash(path.as_bytes()); + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let array = rmpv::Value::Array(vec![ + rmpv::Value::F64(timestamp), + rmpv::Value::Binary(path_hash.to_vec()), + data_value, + ]); + let mut packed = Vec::new(); + rmpv::encode::write_value(&mut packed, &array) + .map_err(|_| LinkCryptoError::EncryptionFailed)?; + + let encrypted = self.encrypt(&packed)?; + + // request_id is a truncated SHA-256 of the plaintext, so both sides derive + // the same ID without exchanging it. + let request_id = truncated_hash(&packed); + + let mut receipt_id = [0u8; 32]; + receipt_id[..16].copy_from_slice(&request_id); + let receipt = RequestReceipt::new(receipt_id, self.link_id, timeout); + self.pending_requests.push(receipt); + + Ok((encrypted, request_id)) + } + + /// Replace the initial request id with the packet-hash id used by + /// Reticulum for packet-sized Link requests. + pub fn update_pending_request_id( + &mut self, + old_request_id: &[u8; 16], + new_request_id: [u8; 16], + ) -> bool { + if let Some(receipt) = self + .pending_requests + .iter_mut() + .find(|r| r.request_id[..16] == old_request_id[..]) + { + receipt.request_id = [0u8; 32]; + receipt.request_id[..16].copy_from_slice(&new_request_id); + true + } else { + false + } + } + + /// Decrypt and parse a REQUEST packet into `(request_id, path_hash, timestamp, data)`. + pub fn handle_request( + &self, + encrypted_data: &[u8], + ) -> Result { + let plaintext = self.decrypt(encrypted_data)?; + + // request_id = SHA-256(packed_request)[:16] + let request_id = truncated_hash(&plaintext); + + // Unpack msgpack array: [timestamp, path_hash, data] + let value = rmpv::decode::read_value(&mut &plaintext[..]) + .map_err(|_| LinkCryptoError::DecryptionFailed)?; + + let array = value.as_array().ok_or(LinkCryptoError::DecryptionFailed)?; + if array.len() < 3 { + return Err(LinkCryptoError::DecryptionFailed); + } + + let timestamp = array[0].as_f64().ok_or(LinkCryptoError::DecryptionFailed)?; + + let path_hash_bytes = array[1] + .as_slice() + .ok_or(LinkCryptoError::DecryptionFailed)?; + if path_hash_bytes.len() != 16 { + return Err(LinkCryptoError::DecryptionFailed); + } + let mut path_hash = [0u8; 16]; + path_hash.copy_from_slice(path_hash_bytes); + + let data = msgpack_value_to_bytes(&array[2])?; + + Ok((request_id, path_hash, timestamp, data)) + } + + /// Build a RESPONSE payload: `encrypt(msgpack([request_id, response_data]))`. + /// + /// Send with context RESPONSE (0x0A). + pub fn create_response( + &self, + request_id: &[u8; 16], + response_data: &[u8], + ) -> Result, LinkCryptoError> { + let packed = Self::pack_response(request_id, response_data)?; + self.encrypt(&packed) + } + + /// Build plaintext msgpack `[request_id, response_data]` for a Link + /// response packet or response resource. + pub fn pack_response( + request_id: &[u8; 16], + response_data: &[u8], + ) -> Result, LinkCryptoError> { + let response_value = msgpack_value_from_bytes_or_binary(response_data); + let array = rmpv::Value::Array(vec![ + rmpv::Value::Binary(request_id.to_vec()), + response_value, + ]); + let mut packed = Vec::new(); + rmpv::encode::write_value(&mut packed, &array) + .map_err(|_| LinkCryptoError::EncryptionFailed)?; + Ok(packed) + } + + /// Decrypt a RESPONSE payload, deliver it to the matching receipt, and return + /// `(request_id, response_data)`. + pub fn handle_response( + &mut self, + encrypted_data: &[u8], + ) -> Result<([u8; 16], Vec), LinkCryptoError> { + let plaintext = self.decrypt(encrypted_data)?; + + self.handle_response_plaintext(&plaintext) + } + + /// Deliver a plaintext msgpack `[request_id, response_data]` response. + /// + /// This is used for response resources, where the Resource layer has already + /// reassembled and decrypted the transferred blob. + pub fn handle_response_plaintext( + &mut self, + plaintext: &[u8], + ) -> Result<([u8; 16], Vec), LinkCryptoError> { + let value = rmpv::decode::read_value(&mut &plaintext[..]) + .map_err(|_| LinkCryptoError::DecryptionFailed)?; + + let array = value.as_array().ok_or(LinkCryptoError::DecryptionFailed)?; + if array.len() < 2 { + return Err(LinkCryptoError::DecryptionFailed); + } + + let id_bytes = array[0] + .as_slice() + .ok_or(LinkCryptoError::DecryptionFailed)?; + if id_bytes.len() != 16 { + return Err(LinkCryptoError::DecryptionFailed); + } + let mut request_id = [0u8; 16]; + request_id.copy_from_slice(id_bytes); + + let response_data = msgpack_value_to_bytes(&array[1])?; + + if let Some(receipt) = self + .pending_requests + .iter_mut() + .find(|r| r.request_id[..16] == request_id[..]) + { + receipt.receive_response(response_data.clone()); + } + + self.pending_requests + .retain(|r| r.state == RequestState::Sent); + + Ok((request_id, response_data)) + } + + /// Update RTT from an LRRTT packet (context 0xFE) received after handshake. + /// + /// The initiator sends the first measurement as part of `validate_proof`; this + /// path handles subsequent updates during the link's lifetime. + pub fn update_rtt_from_packet( + &mut self, + encrypted_data: &[u8], + ) -> Result { + let plaintext = self.decrypt(encrypted_data)?; + + let value = rmpv::decode::read_value(&mut &plaintext[..]) + .map_err(|_| LinkCryptoError::DecryptionFailed)?; + let peer_rtt = value.as_f64().ok_or(LinkCryptoError::DecryptionFailed)?; + + // Prefer the larger of peer and local measurements so timeouts are based on + // the slower path — a one-sided smaller value would understate round-trip. + let rtt = if let Some(existing) = self.rtt { + Duration::from_secs_f64(peer_rtt.max(existing.as_secs_f64())) + } else { + Duration::from_secs_f64(peer_rtt) + }; + + self.rtt = Some(rtt); + self.keepalive.update_from_rtt(rtt); + + Ok(rtt) + } + + /// Build an LRRTT payload containing the current RTT as a msgpack f64. + pub fn create_rtt_packet(&self) -> Result, LinkCryptoError> { + let rtt_secs = self.rtt.map(|r| r.as_secs_f64()).unwrap_or(0.0); + let mut rtt_bytes = Vec::new(); + rmpv::encode::write_value(&mut rtt_bytes, &rmpv::Value::F64(rtt_secs)) + .map_err(|_| LinkCryptoError::EncryptionFailed)?; + self.encrypt(&rtt_bytes) + } + + /// Sign a received packet hash and return a `packet_hash(32) || signature(64)` proof. + pub fn prove_packet( + &self, + packet_hash: &[u8; 32], + identity_signing_key: &Ed25519PrivateKey, + ) -> Result, LinkCryptoError> { + if self.state != LinkState::Active && self.state != LinkState::Stale { + return Err(LinkCryptoError::EncryptionFailed); + } + + let signature = identity_signing_key.sign(packet_hash); + + let mut proof = Vec::with_capacity(96); + proof.extend_from_slice(packet_hash); + proof.extend_from_slice(&signature); + + Ok(proof) + } + + /// Sign a received link packet with this link's ephemeral signing key. + /// + /// Initiators advertise an ephemeral Ed25519 public key in the LINKREQUEST; + /// responders validate later link-packet proofs against that key. + pub fn prove_packet_with_link_key( + &self, + packet_hash: &[u8; 32], + ) -> Result, LinkCryptoError> { + if self.state != LinkState::Active && self.state != LinkState::Stale { + return Err(LinkCryptoError::EncryptionFailed); + } + + let signature = if let Some(signature) = self.sign(packet_hash) { + signature + } else if let Some(ephemeral_keys) = self.ephemeral_keys.as_ref() { + ephemeral_keys.ed25519_prv.sign(packet_hash) + } else { + return Err(LinkCryptoError::EncryptionFailed); + }; + + let mut proof = Vec::with_capacity(96); + proof.extend_from_slice(packet_hash); + proof.extend_from_slice(&signature); + + Ok(proof) + } + + /// Variant of [`Link::prove_packet`] for external signers. + pub fn prove_packet_with( + &self, + packet_hash: &[u8; 32], + sign_fn: F, + ) -> Result, LinkCryptoError> + where + F: FnOnce(&[u8]) -> [u8; 64], + { + if self.state != LinkState::Active && self.state != LinkState::Stale { + return Err(LinkCryptoError::EncryptionFailed); + } + + let signature = sign_fn(packet_hash); + + let mut proof = Vec::with_capacity(96); + proof.extend_from_slice(packet_hash); + proof.extend_from_slice(&signature); + + Ok(proof) + } + + /// Verify a `packet_hash(32) || signature(64)` proof against the peer's identity key. + pub fn validate_packet_proof(&self, packet_hash: &[u8; 32], proof_data: &[u8]) -> bool { + if proof_data.len() < 96 { + return false; + } + + let received_hash = &proof_data[..32]; + if received_hash != packet_hash { + return false; + } + + let mut signature = [0u8; 64]; + signature.copy_from_slice(&proof_data[32..96]); + + if let Some(peer_ed25519_pub) = &self.peer_ed25519_pub { + match Ed25519PublicKey::from_bytes(peer_ed25519_pub) { + Ok(verify_key) => verify_key.verify(packet_hash, &signature).is_ok(), + Err(_) => false, + } + } else { + false + } + } + + /// Flag that a channel has been attached. + /// + /// `rns-link` does not own the channel type (it lives in `rns-protocol`); this + /// just records lazy creation so callers don't build two. + pub fn mark_channel_created(&mut self) { + self.has_channel = true; + } + + pub fn set_resource_strategy(&mut self, strategy: ResourceStrategy) { + self.resource_strategy = strategy; + } + + /// Evaluate the configured strategy. + /// + /// `AskApp` defers to the caller's application callback. + pub fn should_accept_resource(&self) -> ResourceAcceptance { + match self.resource_strategy { + ResourceStrategy::AcceptNone => ResourceAcceptance::Reject, + ResourceStrategy::AcceptAll => ResourceAcceptance::Accept, + ResourceStrategy::AcceptApp => ResourceAcceptance::AskApp, + } + } + + pub fn track_incoming_resource(&mut self, resource_hash: [u8; 32]) { + self.incoming_resources.push(resource_hash); + } + + pub fn track_outgoing_resource(&mut self, resource_hash: [u8; 32]) { + self.outgoing_resources.push(resource_hash); + } + + pub fn untrack_resource(&mut self, resource_hash: &[u8; 32]) { + self.incoming_resources.retain(|h| h != resource_hash); + self.outgoing_resources.retain(|h| h != resource_hash); + } + + pub fn record_tx(&mut self, bytes: usize) { + self.tx_bytes += bytes as u64; + self.tx_count += 1; + self.keepalive.record_outbound(); + } + + pub fn record_rx(&mut self, bytes: usize) { + self.rx_bytes += bytes as u64; + self.rx_count += 1; + } + + /// Totals as `(tx_bytes, rx_bytes, tx_count, rx_count)`. + pub fn traffic_stats(&self) -> (u64, u64, u64, u64) { + (self.tx_bytes, self.rx_bytes, self.tx_count, self.rx_count) + } + + /// Merge PHY measurements from the receiving interface; `None` values leave + /// the current reading intact. + pub fn update_phy_stats(&mut self, rssi: Option, snr: Option, q: Option) { + if rssi.is_some() { + self.rssi = rssi; + } + if snr.is_some() { + self.snr = snr; + } + if q.is_some() { + self.q = q; + } + } + + /// Current PHY measurements as `(rssi, snr, q)`. + pub fn phy_stats(&self) -> (Option, Option, Option) { + (self.rssi, self.snr, self.q) + } + + /// Clone of the session keys, for handing to a Channel or Resource. + pub fn session_keys(&self) -> Option { + self.session_keys.clone() + } + + pub fn rtt_secs(&self) -> f64 { + self.rtt.map(|r| r.as_secs_f64()).unwrap_or(0.0) + } + + /// Drive the link state machine forward; call periodically from the owning actor. + #[tracing::instrument( + level = "trace", + name = "link.tick", + skip_all, + fields( + link_id = %hex::encode(&self.link_id[..8]), + state = ?self.state, + ), + )] + pub fn tick(&mut self) -> LinkAction { + match self.state { + LinkState::Pending | LinkState::Handshake => { + if self.request_time.elapsed() > self.establishment_timeout { + self.close(CloseReason::Timeout); + return LinkAction::Closed(CloseReason::Timeout); + } + LinkAction::None + } + LinkState::Active => { + // Emit any pending keepalive before checking staleness so a final + // beat goes out on the same tick the link transitions to STALE. + if self.keepalive.should_send_keepalive() { + self.keepalive.mark_keepalive_sent(); + return LinkAction::SendKeepalive; + } + if self.keepalive.is_stale() { + self.state = LinkState::Stale; + self.stale_since = Some(Instant::now()); + tracing::debug!(link_id = ?self.link_id, "link state -> Stale"); + return LinkAction::TransitionedToStale; + } + LinkAction::None + } + LinkState::Stale => { + // Encrypt the teardown payload before close() purges the keys — + // otherwise we'd have nothing to sign the teardown with. + let rtt = self.rtt.unwrap_or(Duration::from_secs(1)); + let grace = self.keepalive.stale_grace_timeout(rtt); + if let Some(stale_since) = self.stale_since + && stale_since.elapsed() >= grace + { + let teardown_data = self.encrypt(&self.link_id).unwrap_or_default(); + self.close(CloseReason::Timeout); + return LinkAction::SendTeardownAndClose(teardown_data); + } + LinkAction::None + } + LinkState::Closed => LinkAction::None, + } + } + + /// Record that an inbound packet was received; recovers the link from STALE. + pub fn record_inbound(&mut self) { + self.keepalive.record_inbound(); + + if self.state == LinkState::Stale { + self.state = LinkState::Active; + self.stale_since = None; + } + } + + /// Initiate link teardown and return the encrypted teardown payload to send. + pub fn teardown(&mut self, reason: CloseReason) -> Option> { + if self.state == LinkState::Closed { + return None; + } + + // Teardown payload is the link ID sealed with the session key — the peer + // can verify authenticity of the teardown without a separate signature. + let teardown_data = self.encrypt(&self.link_id).ok(); + self.close(reason); + teardown_data + } + + /// Handle a received teardown packet and close the link on success. + pub fn receive_teardown(&mut self, encrypted_data: &[u8]) -> bool { + match self.decrypt(encrypted_data) { + Ok(plaintext) => { + if plaintext.len() >= 16 && plaintext[..16] == self.link_id { + self.close(CloseReason::DestinationClosed); + true + } else { + false + } + } + Err(_) => false, + } + } + + fn close(&mut self, reason: CloseReason) { + tracing::debug!(link_id = ?self.link_id, ?reason, "link state -> Closed"); + self.state = LinkState::Closed; + self.purge_keys(); + } + + /// Mark the link closed without emitting a teardown packet. + /// + /// Owners use this when an external close notification arrives without a + /// link-authenticated teardown payload, such as a local manager shutdown. + pub fn mark_closed(&mut self, reason: CloseReason) { + if self.state != LinkState::Closed { + self.close(reason); + } + } + + fn purge_keys(&mut self) { + self.ephemeral_keys = None; + self.session_keys = None; + self.peer_x25519_pub = None; + self.peer_ed25519_pub = None; + self.sig_prv = None; + } + + /// Attach the initiator's identity signing key after construction. + pub fn set_signing_key(&mut self, key: &Ed25519PrivateKey) { + self.sig_prv = Some(Ed25519PrivateKey::from_bytes(&key.to_bytes())); + } + + /// Sign a message with the link's identity key, or `None` if no key is set. + pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> { + self.sig_prv.as_ref().map(|key| key.sign(message)) + } + + /// Verify a signature using the peer's Ed25519 identity key. + pub fn validate(&self, signature: &[u8], message: &[u8]) -> bool { + if let Some(ref peer_pub_bytes) = self.peer_ed25519_pub { + if signature.len() != 64 { + return false; + } + let mut sig = [0u8; 64]; + sig.copy_from_slice(signature); + if let Ok(pub_key) = Ed25519PublicKey::from_bytes(peer_pub_bytes) { + pub_key.verify(message, &sig).is_ok() + } else { + false + } + } else { + false + } + } + + pub fn set_packet_callback(&mut self, cb: impl Fn(&[u8]) + Send + Sync + 'static) { + self.packet_callback = Some(Box::new(cb)); + } + + /// Install a callback invoked for each inbound resource; return `true` to accept. + pub fn set_resource_callback(&mut self, cb: impl Fn(bool) -> bool + Send + Sync + 'static) { + self.resource_callback = Some(Box::new(cb)); + } + + pub fn set_remote_identified_callback( + &mut self, + cb: impl Fn(&Link, &[u8; 64]) + Send + Sync + 'static, + ) { + self.remote_identified_callback = Some(Box::new(cb)); + } + + pub fn set_link_established_callback(&mut self, cb: impl Fn(&Link) + Send + Sync + 'static) { + self.link_established_callback = Some(Box::new(cb)); + } + + pub fn set_link_closed_callback(&mut self, cb: impl Fn(&Link) + Send + Sync + 'static) { + self.link_closed_callback = Some(Box::new(cb)); + } + + /// Recompute MDU from the current MTU. + /// + /// MDU = `floor((mtu - header - token) / AES block) * AES block - 1`; the + /// trailing `-1` reserves room for PKCS7 padding worst case. + fn update_mdu(&mut self) { + let mtu = self.mtu as usize; + let overhead = + 1 + rns_wire::constants::HEADER_MINSIZE + rns_wire::constants::TOKEN_OVERHEAD; + if mtu > overhead { + self.mdu = ((mtu - overhead) / rns_wire::constants::AES128_BLOCKSIZE) + * rns_wire::constants::AES128_BLOCKSIZE + - 1; + } + } + + pub fn is_active(&self) -> bool { + self.state == LinkState::Active + } + + pub fn has_keys(&self) -> bool { + self.session_keys.is_some() + } + + /// Time since the last data packet, excluding keepalives. + pub fn no_data_for(&self) -> Duration { + self.keepalive.last_data.elapsed() + } + + /// Time since the last outbound packet, or `Duration::MAX` if none has been sent. + pub fn no_outbound_for(&self) -> Duration { + self.keepalive + .last_outbound + .map(|t| t.elapsed()) + .unwrap_or(Duration::MAX) + } + + /// Time since any inbound activity. + pub fn no_inbound_for(&self) -> Duration { + self.keepalive.last_inbound.elapsed() + } + + /// Time since the last activity in either direction. + pub fn inactive_for(&self) -> Duration { + let last_outbound = self + .keepalive + .last_outbound + .unwrap_or(self.keepalive.last_inbound); + let last = if last_outbound > self.keepalive.last_inbound { + last_outbound + } else { + self.keepalive.last_inbound + }; + last.elapsed() + } + + /// Add bytes to the handshake byte counter (divided by RTT to compute the rate). + pub fn add_establishment_cost(&mut self, bytes: usize) { + self.establishment_cost += bytes; + } + + /// Handshake throughput in bits/sec, or `None` before activation. + pub fn get_establishment_rate(&self) -> Option { + self.establishment_rate.map(|rate| rate * 8.0) + } + + /// Expected in-flight rate in bits/sec for an active link; `None` until the + /// first resource transfer completes. + pub fn get_expected_rate(&self) -> Option { + if self.state == LinkState::Active { + self.expected_rate + } else { + None + } + } + + /// Notify the link that a resource transfer has concluded. + /// + /// Refreshes `expected_rate` from the transfer's size and duration, and drops + /// one entry from the relevant pending-resource tracker. + pub fn resource_concluded( + &mut self, + resource_size: usize, + transfer_duration_secs: f64, + is_incoming: bool, + ) { + // Clamp the denominator so an essentially instant transfer doesn't divide by zero. + let duration = transfer_duration_secs.max(0.0001); + self.expected_rate = Some((resource_size as f64 * 8.0) / duration); + + if is_incoming { + if self.incoming_resource_count > 0 { + self.incoming_resource_count -= 1; + } + } else if let Some(pos) = self.outgoing_resource_states.iter().position(|s| { + matches!( + s, + OutboundResourceState::AwaitingProof + | OutboundResourceState::Complete + | OutboundResourceState::Failed + ) + }) { + self.outgoing_resource_states.remove(pos); + } + } + + pub fn register_outgoing_resource(&mut self) { + self.outgoing_resource_states + .push(OutboundResourceState::Transferring); + } + + pub fn register_incoming_resource(&mut self) { + self.incoming_resource_count += 1; + } + + pub fn update_outgoing_resource_state(&mut self, index: usize, state: OutboundResourceState) { + if index < self.outgoing_resource_states.len() { + self.outgoing_resource_states[index] = state; + } + } + + /// Whether the link can accept a new outbound resource. + /// + /// Allows new transfers not just when the queue is empty but also when all + /// existing transfers have finished sending data and are only waiting on the + /// receiver's proof — otherwise a single slow proof would block the pipeline. + pub fn ready_for_new_resource(&self) -> bool { + if self.outgoing_resource_states.is_empty() { + return true; + } + self.outgoing_resource_states.iter().all(|s| { + matches!( + s, + OutboundResourceState::AwaitingProof + | OutboundResourceState::Complete + | OutboundResourceState::Failed + ) + }) + } + + /// Pick the send mode for a packed request: inline packet if it fits the MDU, + /// otherwise a resource transfer. + pub fn classify_request(&self, packed_request: Vec) -> RequestSendMode { + if packed_request.len() <= self.mdu { + RequestSendMode::Packet(packed_request) + } else { + RequestSendMode::Resource(packed_request) + } + } + + /// Default request timeout: `rtt * TRAFFIC_TIMEOUT_FACTOR + 1.125 * RESPONSE_MAX_GRACE_TIME`. + pub fn default_request_timeout(&self) -> Duration { + let rtt_secs = self.rtt.map(|r| r.as_secs_f64()).unwrap_or(1.0); + let timeout = + rtt_secs * TRAFFIC_TIMEOUT_FACTOR + crate::constants::RESPONSE_MAX_GRACE_TIME * 1.125; + Duration::from_secs_f64(timeout) + } +} + +/// Outcome of one `tick()`, instructing the owning runtime what to emit. +#[derive(Debug, Clone, PartialEq)] +pub enum LinkAction { + None, + /// Initiator should send a keepalive frame. + SendKeepalive, + /// Link just entered STALE; initiator should flush a final keepalive. + TransitionedToStale, + /// Send the wrapped (already encrypted) teardown payload, then drop the link. + SendTeardownAndClose(Vec), + /// Link closed without an outbound frame (e.g. timeout before handshake). + Closed(CloseReason), +} + +#[cfg(test)] +mod tests { + use super::*; + use rns_crypto::ed25519::Ed25519PrivateKey; + use rns_crypto::sha::full_hash; + + #[test] + fn test_initiator_creation() { + let dest_hash = [0xAA; 16]; + let (link, request_data) = Link::new_initiator(dest_hash, 1); + + assert_eq!(link.state, LinkState::Pending); + assert!(link.is_initiator); + assert_eq!(link.destination_hash, dest_hash); + assert_eq!(request_data.len(), ECPUBSIZE + LINK_MTU_SIZE); + } + + #[test] + fn test_full_handshake() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator_link, request_data) = Link::new_initiator(dest_hash, 1); + assert_eq!(initiator_link.state, LinkState::Pending); + + let (mut responder_link, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + assert_eq!(responder_link.state, LinkState::Handshake); + assert_eq!(responder_link.link_id, initiator_link.link_id); + + let rtt_data = initiator_link + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + assert_eq!(initiator_link.state, LinkState::Active); + assert!(initiator_link.rtt.is_some()); + + responder_link.receive_rtt_packet(&rtt_data).unwrap(); + assert_eq!(responder_link.state, LinkState::Active); + + let msg = b"Hello over the link!"; + let ct = initiator_link.encrypt(msg).unwrap(); + let pt = responder_link.decrypt(&ct).unwrap(); + assert_eq!(pt, msg); + + let msg2 = b"Response back!"; + let ct2 = responder_link.encrypt(msg2).unwrap(); + let pt2 = initiator_link.decrypt(&ct2).unwrap(); + assert_eq!(pt2, msg2); + } + + #[test] + fn test_teardown() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut responder, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + let rtt_data = initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + responder.receive_rtt_packet(&rtt_data).unwrap(); + + let teardown_data = initiator.teardown(CloseReason::InitiatorClosed); + assert_eq!(initiator.state, LinkState::Closed); + assert!(teardown_data.is_some()); + + let accepted = responder.receive_teardown(&teardown_data.unwrap()); + assert!(accepted); + assert_eq!(responder.state, LinkState::Closed); + } + + #[test] + fn test_wrong_proof_identity() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let wrong_identity = Ed25519PrivateKey::generate(); + let wrong_pub = wrong_identity.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + // Hand the initiator a mismatched public key on proof validation. + let result = initiator.validate_proof(&proof_data, &wrong_pub, &wrong_pub.to_bytes()); + assert!(result.is_err()); + assert_eq!(initiator.state, LinkState::Closed); + } + + #[test] + fn test_responder_accepts_python_request_lengths_only() { + let dest_hash = [0xA1; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let (_, request_data) = Link::new_initiator(dest_hash, 1); + + assert!(Link::new_responder(&request_data[..63], &identity_key, dest_hash, 1).is_err()); + assert!(Link::new_responder(&request_data[..64], &identity_key, dest_hash, 1).is_ok()); + assert!(Link::new_responder(&request_data[..65], &identity_key, dest_hash, 1).is_err()); + assert!(Link::new_responder(&request_data[..66], &identity_key, dest_hash, 1).is_err()); + assert!(Link::new_responder(&request_data, &identity_key, dest_hash, 1).is_ok()); + + let mut over = request_data.clone(); + over.push(0); + assert!(Link::new_responder(&over, &identity_key, dest_hash, 1).is_err()); + } + + #[test] + fn test_responder_accepts_python_inbound_modes() { + let dest_hash = [0xA2; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let (mut request_link, request_data) = Link::new_initiator(dest_hash, 1); + + let mut aes128_request = request_data.clone(); + aes128_request[64] = MODE_AES128_CBC << 5; + let (responder, proof) = + Link::new_responder(&aes128_request, &identity_key, dest_hash, 1).unwrap(); + assert_eq!(responder.mode, MODE_AES128_CBC); + assert_eq!( + LinkProofData::unpack(&proof).unwrap().signalling.mode, + MODE_AES128_CBC + ); + + let identity_pub = identity_key.public_key(); + assert!( + request_link + .validate_proof(&proof, &identity_pub, &identity_pub.to_bytes()) + .is_err(), + "initiator requested AES256 and must reject an AES128 proof" + ); + assert_eq!(request_link.state, LinkState::Closed); + + let mut unsupported_request = request_data; + unsupported_request[64] = MODE_AES256_GCM << 5; + assert!( + matches!( + Link::new_responder(&unsupported_request, &identity_key, dest_hash, 1), + Err(HandshakeError::UnsupportedMode(mode)) if mode == MODE_AES256_GCM + ), + "Python raises for unsupported inbound mode 2" + ); + } + + #[test] + fn test_initiator_rejects_proof_mode_mismatch() { + let dest_hash = [0xA3; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (_, mut proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + proof_data[96] = MODE_AES128_CBC << 5; + let result = initiator.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()); + assert!(matches!(result, Err(HandshakeError::InvalidSignature))); + assert_eq!(initiator.state, LinkState::Closed); + } + + #[test] + fn test_establishment_timeout() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + + link.establishment_timeout = Duration::from_millis(1); + std::thread::sleep(Duration::from_millis(5)); + + let action = link.tick(); + assert_eq!(action, LinkAction::Closed(CloseReason::Timeout)); + assert_eq!(link.state, LinkState::Closed); + } + + #[test] + fn test_keys_purged_on_close() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut _responder, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + + assert!(initiator.has_keys()); + initiator.teardown(CloseReason::InitiatorClosed); + assert!(!initiator.has_keys()); + } + + #[test] + fn test_stale_recovery() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + + initiator.state = LinkState::Stale; + initiator.stale_since = Some(Instant::now()); + + // Any inbound activity should rescue the link back to ACTIVE. + initiator.record_inbound(); + assert_eq!(initiator.state, LinkState::Active); + } + + /// `teardown()` must be safe to call more than once. The second call on + /// an already-closed link returns `None` without panicking or emitting + /// a spurious teardown payload (keys are already gone). + #[test] + fn test_teardown_idempotent_when_closed() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + + let first = initiator.teardown(CloseReason::InitiatorClosed); + assert!(first.is_some(), "first teardown emits a payload"); + assert_eq!(initiator.state, LinkState::Closed); + + let second = initiator.teardown(CloseReason::InitiatorClosed); + assert!( + second.is_none(), + "repeat teardown on Closed is a no-op with no payload" + ); + assert_eq!(initiator.state, LinkState::Closed); + } + + /// Stale links past the grace window must emit a `SendTeardownAndClose` + /// on `tick()` and transition to Closed. Complements `test_stale_recovery`, + /// which covers the happy path where inbound traffic resurrects the link. + #[test] + fn test_stale_grace_timeout_emits_teardown() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + + initiator.state = LinkState::Stale; + let rtt = Duration::from_millis(50); + initiator.rtt = Some(rtt); + let expired_by = initiator.keepalive.stale_grace_timeout(rtt) + Duration::from_millis(1); + let now = Instant::now(); + initiator.stale_since = Some(if let Some(stale_since) = now.checked_sub(expired_by) { + stale_since + } else { + std::thread::sleep(expired_by); + now + }); + + let action = initiator.tick(); + assert!( + matches!(action, LinkAction::SendTeardownAndClose(_)), + "stale link past grace must emit teardown, got {action:?}" + ); + assert_eq!(initiator.state, LinkState::Closed); + assert!(!initiator.has_keys(), "keys purged after teardown close"); + } + + /// `tick()` on a Closed link is a no-op. Protects against re-entry from + /// scheduler callbacks that fire after teardown. + #[test] + fn test_tick_on_closed_link_is_noop() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + link.close(CloseReason::InitiatorClosed); + assert_eq!(link.state, LinkState::Closed); + + let action = link.tick(); + assert_eq!(action, LinkAction::None); + assert_eq!(link.state, LinkState::Closed); + } + + /// `validate_proof` on an already-Closed link must not resurrect it. + /// Models a late proof arriving after the initiator timed out. + #[test] + fn test_validate_proof_on_closed_link_rejected() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + initiator.close(CloseReason::Timeout); + assert_eq!(initiator.state, LinkState::Closed); + + let result = initiator.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()); + assert!(result.is_err(), "validate_proof on Closed link must reject"); + assert_eq!(initiator.state, LinkState::Closed); + assert!(!initiator.has_keys(), "keys stay purged"); + } + + /// `record_inbound` must refresh keepalive even on an already-Active + /// link (not just on Stale→Active recovery). This is the common path: + /// every received packet resets the inactivity clock. + #[test] + fn test_record_inbound_refreshes_keepalive_on_active() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + assert_eq!(initiator.state, LinkState::Active); + + std::thread::sleep(Duration::from_millis(5)); + let before = initiator.inactive_for(); + std::thread::sleep(Duration::from_millis(5)); + + initiator.record_inbound(); + let after = initiator.inactive_for(); + assert!( + after < before, + "record_inbound should reset inactivity clock: before={before:?} after={after:?}" + ); + assert_eq!(initiator.state, LinkState::Active); + } + + #[test] + fn test_establishment_rate_computed() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut responder, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + let rtt_data = initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + responder.receive_rtt_packet(&rtt_data).unwrap(); + + assert!(initiator.establishment_rate.is_some()); + assert!(responder.establishment_rate.is_some()); + + assert!(initiator.establishment_cost > 0); + assert!(responder.establishment_cost > 0); + + // get_establishment_rate reports bits/sec (byte rate * 8). + let initiator_rate_bps = initiator.get_establishment_rate().unwrap(); + let initiator_rate_bytes = initiator.establishment_rate.unwrap(); + assert!((initiator_rate_bps - initiator_rate_bytes * 8.0).abs() < 0.001); + } + + #[test] + fn test_expected_rate_computed_on_resource_concluded() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut link, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + link.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + + assert!(link.expected_rate.is_none()); + + link.register_incoming_resource(); + link.resource_concluded(1000, 0.5, true); + + // (1000 bytes * 8) / 0.5 s = 16000 bits/sec + assert!(link.expected_rate.is_some()); + let rate = link.expected_rate.unwrap(); + assert!((rate - 16000.0).abs() < 0.1); + + assert_eq!(link.get_expected_rate(), Some(rate)); + + // get_expected_rate() suppresses the reading once the link is no longer active. + link.state = LinkState::Closed; + assert_eq!(link.get_expected_rate(), None); + } + + #[test] + fn test_expected_rate_zero_duration_clamped() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut link, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + link.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + + // Zero-duration transfers must not divide by zero; the implementation clamps to 0.0001 s. + link.resource_concluded(1000, 0.0, false); + let rate = link.expected_rate.unwrap(); + let expected = (1000.0 * 8.0) / 0.0001; + assert!((rate - expected).abs() < 1.0); + } + + #[test] + fn test_ready_for_new_resource_empty() { + let dest_hash = [0xAA; 16]; + let (link, _) = Link::new_initiator(dest_hash, 1); + assert!(link.ready_for_new_resource()); + } + + #[test] + fn test_ready_for_new_resource_transferring_blocks() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + + link.register_outgoing_resource(); + assert!(!link.ready_for_new_resource()); + } + + #[test] + fn test_ready_for_new_resource_awaiting_proof_allows() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + + link.register_outgoing_resource(); + link.update_outgoing_resource_state(0, OutboundResourceState::AwaitingProof); + // Once the payload has been sent, queuing the next resource should not block on the proof. + assert!(link.ready_for_new_resource()); + } + + #[test] + fn test_ready_for_new_resource_mixed_states() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + + link.register_outgoing_resource(); + link.register_outgoing_resource(); + link.update_outgoing_resource_state(0, OutboundResourceState::AwaitingProof); + // Index 1 is still Transferring, so the pipeline must remain closed. + assert!(!link.ready_for_new_resource()); + + link.update_outgoing_resource_state(1, OutboundResourceState::AwaitingProof); + assert!(link.ready_for_new_resource()); + } + + #[test] + fn test_classify_request_packet() { + let dest_hash = [0xAA; 16]; + let (link, _) = Link::new_initiator(dest_hash, 1); + + let small_data = vec![0u8; 10]; + match link.classify_request(small_data.clone()) { + RequestSendMode::Packet(data) => assert_eq!(data, small_data), + RequestSendMode::Resource(_) => panic!("Expected Packet mode"), + } + } + + #[test] + fn test_classify_request_resource() { + let dest_hash = [0xAA; 16]; + let (link, _) = Link::new_initiator(dest_hash, 1); + + let large_data = vec![0u8; link.mdu + 1]; + match link.classify_request(large_data.clone()) { + RequestSendMode::Resource(data) => assert_eq!(data, large_data), + RequestSendMode::Packet(_) => panic!("Expected Resource mode"), + } + } + + #[test] + fn test_classify_request_exact_mdu() { + let dest_hash = [0xAA; 16]; + let (link, _) = Link::new_initiator(dest_hash, 1); + + // An exactly-MDU-sized payload must still fit in a single packet. + let exact_data = vec![0u8; link.mdu]; + match link.classify_request(exact_data.clone()) { + RequestSendMode::Packet(data) => assert_eq!(data, exact_data), + RequestSendMode::Resource(_) => panic!("Expected Packet mode for exact MDU"), + } + } + + #[test] + fn test_default_request_timeout() { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut link, request_data) = Link::new_initiator(dest_hash, 1); + let (_, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + link.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + + let timeout = link.default_request_timeout(); + let rtt_secs = link.rtt.unwrap().as_secs_f64(); + let expected = + rtt_secs * TRAFFIC_TIMEOUT_FACTOR + crate::constants::RESPONSE_MAX_GRACE_TIME * 1.125; + assert!((timeout.as_secs_f64() - expected).abs() < 0.001); + } + + #[test] + fn test_resource_concluded_removes_outgoing() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + link.state = LinkState::Active; + + link.register_outgoing_resource(); + link.update_outgoing_resource_state(0, OutboundResourceState::AwaitingProof); + assert_eq!(link.outgoing_resource_states.len(), 1); + + link.resource_concluded(500, 1.0, false); + assert_eq!(link.outgoing_resource_states.len(), 0); + } + + #[test] + fn test_resource_concluded_decrements_incoming() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + link.state = LinkState::Active; + + link.register_incoming_resource(); + link.register_incoming_resource(); + assert_eq!(link.incoming_resource_count, 2); + + link.resource_concluded(500, 1.0, true); + assert_eq!(link.incoming_resource_count, 1); + } + + fn make_active_link() -> (Link, Link, Ed25519PrivateKey) { + let dest_hash = [0xAA; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut responder, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + let rtt_data = initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + responder.receive_rtt_packet(&rtt_data).unwrap(); + + (initiator, responder, identity_key) + } + + #[test] + fn test_identify_roundtrip() { + let (initiator, mut responder, _dest_identity) = make_active_link(); + + let initiator_identity = Ed25519PrivateKey::generate(); + let initiator_x25519_pub = [0x11; 32]; // mock X25519 pub + let mut identity_pub = [0u8; 64]; + identity_pub[..32].copy_from_slice(&initiator_x25519_pub); + identity_pub[32..].copy_from_slice(&initiator_identity.public_key().to_bytes()); + + let identify_data = initiator + .identify(&identity_pub, &initiator_identity) + .unwrap(); + + let remote_pub = responder.handle_identification(&identify_data).unwrap(); + assert_eq!(remote_pub, identity_pub); + assert!(responder.identified); + assert_eq!(responder.remote_identity().unwrap(), &identity_pub); + } + + #[test] + fn test_identify_non_initiator_fails() { + let (_initiator, responder, _identity) = make_active_link(); + let key = Ed25519PrivateKey::generate(); + let pub_key = [0u8; 64]; + // Only the initiator is allowed to reveal its identity. + assert!(responder.identify(&pub_key, &key).is_err()); + } + + #[test] + fn test_identify_wrong_signature_fails() { + let (initiator, mut responder, _) = make_active_link(); + + let wrong_key = Ed25519PrivateKey::generate(); + let real_key = Ed25519PrivateKey::generate(); + let mut identity_pub = [0u8; 64]; + identity_pub[32..].copy_from_slice(&real_key.public_key().to_bytes()); + + // Claim real_key's public half but sign with a different private key — signature must not verify. + let identify_data = initiator.identify(&identity_pub, &wrong_key).unwrap(); + + assert!(responder.handle_identification(&identify_data).is_err()); + assert!(!responder.identified); + } + + #[test] + fn test_request_response_roundtrip() { + let (mut initiator, responder, _) = make_active_link(); + + let (request_data, request_id) = initiator + .request("test.path", Some(b"request data"), Duration::from_secs(10)) + .unwrap(); + + assert!(!initiator.pending_requests.is_empty()); + + let (recv_id, path_hash, _ts, data) = responder.handle_request(&request_data).unwrap(); + assert_eq!(recv_id, request_id); + assert_eq!(data, b"request data"); + + let expected_path_hash = truncated_hash("test.path".as_bytes()); + assert_eq!(path_hash, expected_path_hash); + + let response_data = responder + .create_response(&request_id, b"response data") + .unwrap(); + + let (resp_id, resp_data) = initiator.handle_response(&response_data).unwrap(); + assert_eq!(resp_id, request_id); + assert_eq!(resp_data, b"response data"); + + // handle_response() must drain the receipt on success. + assert!(initiator.pending_requests.is_empty()); + } + + #[test] + fn test_request_response_preserves_msgpack_object_bodies() { + use rmpv::Value; + + let (mut initiator, responder, _) = make_active_link(); + + let request_body = Value::Array(vec![Value::Nil, Value::Nil]); + let mut request_body_bytes = Vec::new(); + rmpv::encode::write_value(&mut request_body_bytes, &request_body).unwrap(); + + let (request_data, request_id) = initiator + .request( + "lxmf.propagation.get", + Some(&request_body_bytes), + Duration::from_secs(10), + ) + .unwrap(); + + let (recv_id, _path_hash, _ts, data) = responder.handle_request(&request_data).unwrap(); + assert_eq!(recv_id, request_id); + let decoded_request: Value = rmpv::decode::read_value(&mut &data[..]).unwrap(); + assert_eq!(decoded_request, request_body); + + let response_body = Value::Array(vec![Value::Binary(vec![0xAA; 32])]); + let mut response_body_bytes = Vec::new(); + rmpv::encode::write_value(&mut response_body_bytes, &response_body).unwrap(); + + let response_data = responder + .create_response(&request_id, &response_body_bytes) + .unwrap(); + + let (resp_id, resp_data) = initiator.handle_response(&response_data).unwrap(); + assert_eq!(resp_id, request_id); + let decoded_response: Value = rmpv::decode::read_value(&mut &resp_data[..]).unwrap(); + assert_eq!(decoded_response, response_body); + assert!(initiator.pending_requests.is_empty()); + } + + #[test] + fn test_request_str_roundtrip_as_plain_utf8_body() { + let (mut initiator, responder, _) = make_active_link(); + + let (request_data, request_id) = initiator + .request_str("fetch_file", "example.bin", Duration::from_secs(10)) + .unwrap(); + + let (recv_id, path_hash, _ts, data) = responder.handle_request(&request_data).unwrap(); + assert_eq!(recv_id, request_id); + assert_eq!(path_hash, truncated_hash("fetch_file".as_bytes())); + assert_eq!(data, b"example.bin"); + } + + #[test] + fn test_request_on_inactive_link_fails() { + let dest_hash = [0xAA; 16]; + let (mut link, _) = Link::new_initiator(dest_hash, 1); + assert!(link.request("test", None, Duration::from_secs(10)).is_err()); + } + + #[test] + fn test_prove_packet_roundtrip() { + let (initiator, responder, dest_identity) = make_active_link(); + + let packet_hash = full_hash(b"test packet data"); + + let proof = responder + .prove_packet(&packet_hash, &dest_identity) + .unwrap(); + assert_eq!(proof.len(), 96); + + assert!(initiator.validate_packet_proof(&packet_hash, &proof)); + } + + #[test] + fn test_prove_packet_wrong_hash_fails() { + let (initiator, responder, dest_identity) = make_active_link(); + + let packet_hash = full_hash(b"test packet"); + let wrong_hash = full_hash(b"wrong packet"); + + let proof = responder + .prove_packet(&packet_hash, &dest_identity) + .unwrap(); + assert!(!initiator.validate_packet_proof(&wrong_hash, &proof)); + } + + #[test] + fn test_rtt_packet_update() { + let (initiator, mut responder, _) = make_active_link(); + + let rtt_packet = initiator.create_rtt_packet().unwrap(); + let rtt = responder.update_rtt_from_packet(&rtt_packet).unwrap(); + assert!(rtt.as_secs_f64() >= 0.0); + } + + #[test] + fn test_session_keys_accessible() { + let (initiator, _, _) = make_active_link(); + assert!(initiator.session_keys().is_some()); + assert!(initiator.rtt_secs() >= 0.0); + } + + #[test] + fn test_channel_creation_flag() { + let (mut initiator, _, _) = make_active_link(); + assert!(!initiator.has_channel); + initiator.mark_channel_created(); + assert!(initiator.has_channel); + } + + #[test] + fn test_resource_strategy() { + let (mut link, _, _) = make_active_link(); + + assert_eq!(link.should_accept_resource(), ResourceAcceptance::Reject); + + link.set_resource_strategy(ResourceStrategy::AcceptAll); + assert_eq!(link.should_accept_resource(), ResourceAcceptance::Accept); + + link.set_resource_strategy(ResourceStrategy::AcceptApp); + assert_eq!(link.should_accept_resource(), ResourceAcceptance::AskApp); + } + + #[test] + fn test_traffic_stats() { + let (mut link, _, _) = make_active_link(); + + link.record_tx(100); + link.record_tx(200); + link.record_rx(50); + + let (tx_b, rx_b, tx_c, rx_c) = link.traffic_stats(); + assert_eq!(tx_b, 300); + assert_eq!(rx_b, 50); + assert_eq!(tx_c, 2); + assert_eq!(rx_c, 1); + } + + #[test] + fn test_phy_stats() { + let (mut link, _, _) = make_active_link(); + + assert_eq!(link.phy_stats(), (None, None, None)); + + link.update_phy_stats(Some(-80.0), Some(12.5), Some(0.95)); + assert_eq!(link.rssi, Some(-80.0)); + assert_eq!(link.snr, Some(12.5)); + assert_eq!(link.q, Some(0.95)); + + // `None` components must leave the existing reading intact. + link.update_phy_stats(Some(-75.0), None, None); + assert_eq!(link.rssi, Some(-75.0)); + assert_eq!(link.snr, Some(12.5)); + } + + #[test] + fn test_resource_tracking() { + let (mut link, _, _) = make_active_link(); + + let hash1 = [0x11; 32]; + let hash2 = [0x22; 32]; + + link.track_incoming_resource(hash1); + link.track_outgoing_resource(hash2); + + assert_eq!(link.incoming_resources.len(), 1); + assert_eq!(link.outgoing_resources.len(), 1); + + link.untrack_resource(&hash1); + assert_eq!(link.incoming_resources.len(), 0); + assert_eq!(link.outgoing_resources.len(), 1); + } + + #[test] + fn test_sign_validate_roundtrip() { + let dest_hash = [0xEE; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let (initiator_link, request_data) = Link::new_initiator(dest_hash, 1); + let (responder_link, _proof) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + + let message = b"hello from responder"; + let sig = responder_link + .sign(message) + .expect("responder should have sig_prv"); + let _ = initiator_link; + assert_eq!(sig.len(), 64); + } + + #[test] + fn test_sign_without_key_returns_none() { + let dest_hash = [0xFF; 16]; + let (link, _) = Link::new_initiator(dest_hash, 1); + assert!(link.sign(b"test").is_none()); + } + + #[test] + fn test_validate_without_peer_key_returns_false() { + let dest_hash = [0xFF; 16]; + let (link, _) = Link::new_initiator(dest_hash, 1); + assert!(!link.validate(&[0u8; 64], b"test")); + } + + #[test] + fn test_signing_key_purged_on_close() { + let dest_hash = [0xEE; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let (_, request_data) = Link::new_initiator(dest_hash, 1); + let (mut link, _proof) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + assert!(link.sign(b"test").is_some()); + link.close(CloseReason::Timeout); + assert!(link.sign(b"test").is_none()); + } +} diff --git a/crates/rns-link/src/mtu_discovery.rs b/crates/rns-link/src/mtu_discovery.rs new file mode 100644 index 0000000..65ef34b --- /dev/null +++ b/crates/rns-link/src/mtu_discovery.rs @@ -0,0 +1,116 @@ +use crate::constants::{MODE_BYTEMASK, MTU_BYTEMASK}; + +/// MTU and encryption-mode signalling packed into 3 bytes (big-endian). +/// +/// Wire layout: `[23:21] mode (0..=7)`, `[20:0] mtu (0..=2_097_151)`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SignallingData { + pub mode: u8, + pub mtu: u32, +} + +impl SignallingData { + pub fn new(mode: u8, mtu: u32) -> Self { + Self { + mode: mode & 0x07, + mtu: mtu & MTU_BYTEMASK, + } + } + + /// Pack into 3 big-endian bytes. + pub fn pack(&self) -> [u8; 3] { + let value = (self.mtu & MTU_BYTEMASK) | ((((self.mode as u32) << 5) & MODE_BYTEMASK) << 16); + let bytes = value.to_be_bytes(); + // Value fits in 24 bits; drop the high byte of the u32. + [bytes[1], bytes[2], bytes[3]] + } + + /// Parse 3 big-endian bytes. Returns `None` if the input is shorter. + pub fn unpack(bytes: &[u8]) -> Option { + if bytes.len() < 3 { + return None; + } + let value = ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32); + let mtu = value & MTU_BYTEMASK; + let mode = ((value >> 21) & 0x07) as u8; + Some(Self { mode, mtu }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC}; + + #[test] + fn test_pack_unpack_roundtrip() { + let sd = SignallingData::new(MODE_AES256_CBC, 500); + let packed = sd.pack(); + let unpacked = SignallingData::unpack(&packed).unwrap(); + assert_eq!(unpacked.mode, MODE_AES256_CBC); + assert_eq!(unpacked.mtu, 500); + } + + #[test] + fn test_mode_zero_mtu_500() { + let sd = SignallingData::new(0, 500); + let packed = sd.pack(); + let unpacked = SignallingData::unpack(&packed).unwrap(); + assert_eq!(unpacked.mode, 0); + assert_eq!(unpacked.mtu, 500); + } + + #[test] + fn test_mode_bits_isolated() { + // Setting the mode must not corrupt the MTU field. + let sd = SignallingData::new(1, 500); + let packed = sd.pack(); + let unpacked = SignallingData::unpack(&packed).unwrap(); + assert_eq!(unpacked.mtu, 500); + assert_eq!(unpacked.mode, 1); + } + + #[test] + fn test_max_mtu_value() { + let max_mtu = MTU_BYTEMASK; + let sd = SignallingData::new(7, max_mtu); + let packed = sd.pack(); + let unpacked = SignallingData::unpack(&packed).unwrap(); + assert_eq!(unpacked.mtu, max_mtu); + assert_eq!(unpacked.mode, 7); + } + + #[test] + fn test_default_mode() { + let sd = SignallingData::new(DEFAULT_MODE, 500); + assert_eq!(sd.mode, MODE_AES256_CBC); + } + + #[test] + fn test_too_short() { + assert!(SignallingData::unpack(&[0x00, 0x01]).is_none()); + } + + use proptest::prelude::*; + + proptest! { + #[test] + fn proptest_signalling_pack_unpack_roundtrip( + mode in 0u8..=7, + mtu in 0u32..=MTU_BYTEMASK, + ) { + let sd = SignallingData::new(mode, mtu); + let packed = sd.pack(); + let unpacked = SignallingData::unpack(&packed).unwrap(); + prop_assert_eq!(unpacked.mode, mode); + prop_assert_eq!(unpacked.mtu, mtu); + prop_assert_eq!(unpacked.pack(), packed); + } + + #[test] + fn proptest_signalling_bytes_canonical(bytes: [u8; 3]) { + let sd = SignallingData::unpack(&bytes).unwrap(); + prop_assert_eq!(sd.pack(), bytes); + } + } +} diff --git a/crates/rns-link/src/request.rs b/crates/rns-link/src/request.rs new file mode 100644 index 0000000..9dccba2 --- /dev/null +++ b/crates/rns-link/src/request.rs @@ -0,0 +1,248 @@ +use std::time::{Duration, Instant}; + +/// State of a request receipt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RequestState { + Sent, + /// Response is arriving as a resource transfer rather than a single packet. + Receiving, + Delivered, + Failed, + /// Response payload has arrived; kept distinct from [`Delivered`] so callers + /// can distinguish "ack with data" from "ack only". + /// + /// [`Delivered`]: RequestState::Delivered + ResponseReceived, +} + +/// Callbacks for request receipt state changes. +#[derive(Default)] +pub struct RequestCallbacks { + pub response: Option, + pub failed: Option, + pub progress: Option, +} + +/// Callback invoked once when a request receives a response or terminal failure. +pub type RequestCallback = Box; +/// Progress callback for resource-backed request responses. +pub type ProgressCallback = Box; + +/// Tracks the lifecycle of an outbound request over a link. +pub struct RequestReceipt { + pub request_id: [u8; 32], + pub link_id: [u8; 16], + pub state: RequestState, + pub sent_at: Instant, + pub timeout: Duration, + pub response: Option>, + pub rtt: Option, + /// Transfer progress in [0.0, 1.0]; only meaningful for resource responses. + pub progress: f32, + pub callbacks: RequestCallbacks, +} + +impl RequestReceipt { + pub fn new(request_id: [u8; 32], link_id: [u8; 16], timeout: Duration) -> Self { + Self { + request_id, + link_id, + state: RequestState::Sent, + sent_at: Instant::now(), + timeout, + response: None, + rtt: None, + progress: 0.0, + callbacks: RequestCallbacks::default(), + } + } + + /// Record a response payload, transition to `Delivered`, and fire the response callback. + pub fn deliver(&mut self, response: Vec) { + if self.state == RequestState::Sent || self.state == RequestState::Receiving { + self.rtt = Some(self.sent_at.elapsed()); + self.response = Some(response); + self.state = RequestState::Delivered; + self.progress = 1.0; + if let Some(cb) = self.callbacks.response.take() { + cb(self); + } + } + } + + /// Transition to `Failed` and fire the failure callback. + pub fn fail(&mut self) { + if self.state == RequestState::Sent || self.state == RequestState::Receiving { + self.state = RequestState::Failed; + if let Some(cb) = self.callbacks.failed.take() { + cb(self); + } + } + } + + pub fn is_timed_out(&self) -> bool { + self.state == RequestState::Sent && self.sent_at.elapsed() > self.timeout + } + + pub fn is_pending(&self) -> bool { + self.state == RequestState::Sent + } + + /// Store the response payload and advance to `ResponseReceived`. + /// + /// Distinct from `deliver()`: `receive_response` can fire after `mark_delivered()` + /// for protocols that ack then stream the payload. + pub fn receive_response(&mut self, data: Vec) { + if self.state == RequestState::Sent || self.state == RequestState::Delivered { + self.rtt = Some(self.sent_at.elapsed()); + self.response = Some(data); + self.state = RequestState::ResponseReceived; + } + } + + /// Transition to `Delivered` without a response payload (ack-only). + pub fn mark_delivered(&mut self) { + if self.state == RequestState::Sent { + self.state = RequestState::Delivered; + } + } + + /// Transition to `Failed` without firing the failure callback. + pub fn mark_failed(&mut self) { + if self.state == RequestState::Sent { + self.state = RequestState::Failed; + } + } + + /// True once the request has reached a terminal state (delivered, failed, or response received). + pub fn concluded(&self) -> bool { + matches!( + self.state, + RequestState::Delivered | RequestState::Failed | RequestState::ResponseReceived + ) + } + + pub fn get_response_time(&self) -> Option { + self.rtt + } + + pub fn get_progress(&self) -> f32 { + self.progress + } + + pub fn update_progress(&mut self, progress: f32) { + self.progress = progress; + if let Some(ref cb) = self.callbacks.progress { + cb(progress); + } + } + + pub fn set_response_callback(&mut self, cb: impl FnOnce(&RequestReceipt) + Send + 'static) { + self.callbacks.response = Some(Box::new(cb)); + } + + pub fn set_failed_callback(&mut self, cb: impl FnOnce(&RequestReceipt) + Send + 'static) { + self.callbacks.failed = Some(Box::new(cb)); + } + + pub fn set_progress_callback(&mut self, cb: impl Fn(f32) + Send + Sync + 'static) { + self.callbacks.progress = Some(Box::new(cb)); + } + + /// Expire the request if past its deadline, firing the failure callback. Returns `true` if expired. + pub fn check_timeout(&mut self) -> bool { + if self.is_timed_out() { + self.state = RequestState::Failed; + if let Some(cb) = self.callbacks.failed.take() { + cb(self); + } + true + } else { + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_request_receipt_lifecycle() { + let mut receipt = RequestReceipt::new([0xAA; 32], [0xBB; 16], Duration::from_secs(10)); + + assert_eq!(receipt.state, RequestState::Sent); + assert!(receipt.is_pending()); + assert!(receipt.response.is_none()); + + receipt.deliver(b"response data".to_vec()); + assert_eq!(receipt.state, RequestState::Delivered); + assert!(!receipt.is_pending()); + assert!(receipt.response.is_some()); + assert!(receipt.rtt.is_some()); + } + + #[test] + fn test_request_receipt_fail() { + let mut receipt = RequestReceipt::new([0xAA; 32], [0xBB; 16], Duration::from_secs(10)); + + receipt.fail(); + assert_eq!(receipt.state, RequestState::Failed); + assert!(!receipt.is_pending()); + } + + #[test] + fn test_cannot_deliver_after_fail() { + let mut receipt = RequestReceipt::new([0xAA; 32], [0xBB; 16], Duration::from_secs(10)); + + receipt.fail(); + receipt.deliver(b"too late".to_vec()); + assert_eq!(receipt.state, RequestState::Failed); + assert!(receipt.response.is_none()); + } + + #[test] + fn test_receive_response() { + let mut receipt = RequestReceipt::new([0xCC; 32], [0xDD; 16], Duration::from_secs(10)); + + assert_eq!(receipt.state, RequestState::Sent); + receipt.receive_response(b"response payload".to_vec()); + assert_eq!(receipt.state, RequestState::ResponseReceived); + assert_eq!( + receipt.response.as_deref(), + Some(b"response payload".as_slice()) + ); + assert!(receipt.rtt.is_some()); + } + + #[test] + fn test_mark_delivered_then_response() { + let mut receipt = RequestReceipt::new([0xEE; 32], [0xFF; 16], Duration::from_secs(10)); + + receipt.mark_delivered(); + assert_eq!(receipt.state, RequestState::Delivered); + + receipt.receive_response(b"late response".to_vec()); + assert_eq!(receipt.state, RequestState::ResponseReceived); + assert!(receipt.response.is_some()); + } + + #[test] + fn test_mark_failed_method() { + let mut receipt = RequestReceipt::new([0x11; 32], [0x22; 16], Duration::from_secs(10)); + + receipt.mark_failed(); + assert_eq!(receipt.state, RequestState::Failed); + assert!(!receipt.is_pending()); + } + + #[test] + fn test_cannot_receive_response_after_fail() { + let mut receipt = RequestReceipt::new([0x33; 32], [0x44; 16], Duration::from_secs(10)); + + receipt.mark_failed(); + receipt.receive_response(b"too late".to_vec()); + assert_eq!(receipt.state, RequestState::Failed); + assert!(receipt.response.is_none()); + } +} diff --git a/crates/rns-protocol/Cargo.toml b/crates/rns-protocol/Cargo.toml new file mode 100644 index 0000000..4d9ac08 --- /dev/null +++ b/crates/rns-protocol/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "rns-protocol" +description = "Resource, Channel, and Buffer protocols for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +rns-crypto = { workspace = true, features = ["std"] } +rns-wire = { workspace = true, features = ["std"] } +rns-link = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +bzip2 = { workspace = true } +rmpv = { workspace = true } +rmp-serde = { workspace = true } +hex = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/rns-protocol/src/buffer.rs b/crates/rns-protocol/src/buffer.rs new file mode 100644 index 0000000..15252c1 --- /dev/null +++ b/crates/rns-protocol/src/buffer.rs @@ -0,0 +1,499 @@ +use std::collections::VecDeque; + +use crate::compression; +use crate::stream_data::{STREAM_ID_MAX, StreamDataMessage}; + +/// Upper bound on a single chunk before the writer splits (16 KiB). +pub const MAX_CHUNK_LEN: usize = 16384; + +/// Number of progressively smaller segments the writer will try when +/// compressing a chunk before giving up and sending it uncompressed. +pub const COMPRESSION_TRIES: usize = 4; + +/// Accumulates inbound [`StreamDataMessage`] payloads into a byte queue and +/// tracks explicit EOF. +pub struct StreamReader { + stream_id: u16, + buffer: VecDeque, + eof: bool, +} + +impl StreamReader { + pub fn new(stream_id: u16) -> Self { + Self { + stream_id: stream_id & STREAM_ID_MAX, + buffer: VecDeque::new(), + eof: false, + } + } + + /// Append `msg` to the buffer. Returns `false` (and ignores the payload) + /// if the message belongs to a different stream. + pub fn feed(&mut self, msg: &StreamDataMessage) -> bool { + if msg.stream_id != self.stream_id { + return false; + } + + if !msg.data.is_empty() { + self.buffer.extend(&msg.data); + } + + if msg.eof { + self.eof = true; + } + + true + } + + /// Pop up to `size` bytes off the front of the buffer. + /// + /// Returns `None` when the buffer is empty and EOF has not yet arrived, + /// and `Some(Vec::new())` once it has — letting callers distinguish "wait" + /// from "end of stream". + pub fn read(&mut self, size: usize) -> Option> { + if self.buffer.is_empty() { + if self.eof { + return Some(Vec::new()); + } + return None; + } + + let n = size.min(self.buffer.len()); + let data: Vec = self.buffer.drain(..n).collect(); + Some(data) + } + + /// Drain the entire buffer. Same empty/`None` semantics as [`Self::read`]. + pub fn read_all(&mut self) -> Option> { + if self.buffer.is_empty() { + if self.eof { + return Some(Vec::new()); + } + return None; + } + let data: Vec = self.buffer.drain(..).collect(); + Some(data) + } + + pub fn available(&self) -> usize { + self.buffer.len() + } + + pub fn is_eof(&self) -> bool { + self.eof + } + + /// True once EOF has been received *and* all buffered data has been drained. + pub fn is_done(&self) -> bool { + self.eof && self.buffer.is_empty() + } +} + +/// Chunks outbound bytes into [`StreamDataMessage`]s sized for the underlying +/// channel, opportunistically compressing each chunk with bzip2. +pub struct StreamWriter { + stream_id: u16, + max_data_len: usize, + closed: bool, +} + +impl StreamWriter { + pub fn new(stream_id: u16, max_data_len: usize) -> Self { + Self { + stream_id: stream_id & STREAM_ID_MAX, + max_data_len, + closed: false, + } + } + + /// Slice `data` into channel-sized frames. Each frame is sent compressed + /// if bzip2 would fit a larger source segment into `max_data_len` than the + /// uncompressed alternative; otherwise the chunk is sent raw. + pub fn write(&mut self, data: &[u8]) -> Result, BufferError> { + if self.closed { + return Err(BufferError::WriterClosed); + } + + if data.is_empty() { + return Ok(Vec::new()); + } + + let mut messages = Vec::new(); + let mut offset = 0; + + while offset < data.len() { + let remaining = &data[offset..]; + + let chunk_len = remaining.len().min(MAX_CHUNK_LEN); + let chunk = &remaining[..chunk_len]; + + let (msg_data, consumed, compressed) = self.try_compress_chunk(chunk); + + let mut msg = StreamDataMessage::new(self.stream_id, msg_data, false); + msg.compressed = compressed; + messages.push(msg); + offset += consumed; + } + + Ok(messages) + } + + /// Compress `chunk` at progressively smaller prefixes (chunk/1, chunk/2, …) + /// until the bzip2 output fits within `max_data_len` and is actually + /// shorter than the source, returning the first match. Falls back to a raw + /// send when no prefix benefits from compression. + fn try_compress_chunk(&self, chunk: &[u8]) -> (Vec, usize, bool) { + if chunk.len() <= 32 { + // bzip2 overhead dominates for very small inputs. + let send_len = chunk.len().min(self.max_data_len); + return (chunk[..send_len].to_vec(), send_len, false); + } + + for comp_try in 1..COMPRESSION_TRIES { + let segment_len = chunk.len() / comp_try; + if segment_len <= 32 { + break; + } + if let Ok(compressed) = compression::bz2_compress(&chunk[..segment_len]) + && compressed.len() < self.max_data_len + && compressed.len() < segment_len + { + return (compressed, segment_len, true); + } + } + + let send_len = chunk.len().min(self.max_data_len); + (chunk[..send_len].to_vec(), send_len, false) + } + + /// Close the writer and return the EOF frame paired with a drain contract: + /// the caller must ensure every message produced by prior `write()` calls + /// has been sent (and acknowledged) before transmitting `eof_message`. + pub fn close(&mut self) -> DrainClose { + self.closed = true; + DrainClose { + eof_message: StreamDataMessage::new(self.stream_id, Vec::new(), true), + } + } + + /// Close the writer and return a bare EOF frame. Use when the caller + /// already manages ordering with the underlying channel. + pub fn close_simple(&mut self) -> StreamDataMessage { + self.closed = true; + StreamDataMessage::new(self.stream_id, Vec::new(), true) + } + + pub fn is_closed(&self) -> bool { + self.closed + } +} + +/// EOF frame handed back by [`StreamWriter::close`]. Must be sent only after +/// every earlier frame produced by the writer has been delivered. +pub struct DrainClose { + pub eof_message: StreamDataMessage, +} + +#[derive(Debug, thiserror::Error)] +pub enum BufferError { + #[error("writer is closed")] + WriterClosed, +} + +/// Bidirectional convenience wrapper that pairs a [`StreamWriter`] and +/// [`StreamReader`] on the same stream ID. +pub struct ChannelBuffer { + writer: StreamWriter, + reader: StreamReader, + stream_id: u16, +} + +impl ChannelBuffer { + pub fn new(stream_id: u16, max_data_len: usize) -> Self { + Self { + writer: StreamWriter::new(stream_id, max_data_len), + reader: StreamReader::new(stream_id), + stream_id, + } + } + + pub fn write(&mut self, data: &[u8]) -> Result, BufferError> { + self.writer.write(data) + } + + /// Close the write side, returning a bare EOF frame. Send after prior + /// write output has flowed through the channel. + pub fn close_writer(&mut self) -> StreamDataMessage { + self.writer.close_simple() + } + + /// Close the write side with the stricter drain contract — see + /// [`StreamWriter::close`]. + pub fn drain_and_close_writer(&mut self) -> DrainClose { + self.writer.close() + } + + pub fn feed_reader(&mut self, msg: &StreamDataMessage) -> bool { + self.reader.feed(msg) + } + + pub fn read(&mut self, size: usize) -> Option> { + self.reader.read(size) + } + + pub fn read_all(&mut self) -> Option> { + self.reader.read_all() + } + + pub fn is_done(&self) -> bool { + self.reader.is_done() + } + + pub fn is_writer_closed(&self) -> bool { + self.writer.is_closed() + } + + pub fn stream_id(&self) -> u16 { + self.stream_id + } + + pub fn available(&self) -> usize { + self.reader.available() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_reader_basic() { + let mut reader = StreamReader::new(1); + assert!(!reader.is_eof()); + assert!(reader.read(100).is_none()); + + let msg = StreamDataMessage::new(1, b"hello".to_vec(), false); + assert!(reader.feed(&msg)); + assert_eq!(reader.available(), 5); + + let data = reader.read(3).unwrap(); + assert_eq!(data, b"hel"); + assert_eq!(reader.available(), 2); + } + + #[test] + fn test_reader_eof() { + let mut reader = StreamReader::new(1); + + let msg1 = StreamDataMessage::new(1, b"data".to_vec(), false); + reader.feed(&msg1); + + let msg2 = StreamDataMessage::new(1, Vec::new(), true); + reader.feed(&msg2); + + assert!(reader.is_eof()); + let data = reader.read(100).unwrap(); + assert_eq!(data, b"data"); + + // Once the buffer is drained, further reads must yield an explicit EOF marker. + let eof = reader.read(100).unwrap(); + assert!(eof.is_empty()); + assert!(reader.is_done()); + } + + #[test] + fn test_reader_wrong_stream() { + let mut reader = StreamReader::new(1); + let msg = StreamDataMessage::new(2, b"wrong".to_vec(), false); + assert!(!reader.feed(&msg)); + assert_eq!(reader.available(), 0); + } + + #[test] + fn test_writer_basic() { + let mut writer = StreamWriter::new(1, 10); + + let msgs = writer.write(b"hello world, this is a test").unwrap(); + // 27-byte input split at 10 bytes per frame must produce multiple messages. + assert!(msgs.len() >= 2); + + for msg in &msgs { + assert_eq!(msg.stream_id, 1); + assert!(!msg.eof); + } + } + + #[test] + fn test_writer_close() { + let mut writer = StreamWriter::new(1, 100); + let drain = writer.close(); + assert!(drain.eof_message.eof); + assert!(drain.eof_message.data.is_empty()); + assert!(writer.is_closed()); + assert!(writer.write(b"after close").is_err()); + } + + #[test] + fn test_writer_close_simple() { + let mut writer = StreamWriter::new(1, 100); + let eof_msg = writer.close_simple(); + assert!(eof_msg.eof); + assert!(eof_msg.data.is_empty()); + assert!(writer.is_closed()); + } + + #[test] + fn test_roundtrip() { + let mut writer = StreamWriter::new(42, 50); + let mut reader = StreamReader::new(42); + + let data = b"Hello, this is a complete stream test with some data!"; + let msgs = writer.write(data).unwrap(); + let eof = writer.close_simple(); + + for msg in &msgs { + reader.feed(msg); + } + reader.feed(&eof); + + let received = reader.read_all().unwrap(); + assert_eq!(received, data); + assert!(reader.is_eof()); + } + + #[test] + fn test_writer_compression_roundtrip() { + // Decompression lives in StreamDataMessage::unpack, so the roundtrip must + // go through pack/unpack — feeding the writer's output directly would skip it. + use crate::channel_message::MessageBase; + + let mut writer = StreamWriter::new(1, 500); + let mut reader = StreamReader::new(1); + + let data = b"AAAA".repeat(500); + let msgs = writer.write(&data).unwrap(); + + let any_compressed = msgs.iter().any(|m| m.compressed); + assert!(any_compressed, "Expected at least one compressed message"); + + for msg in &msgs { + let packed = msg.pack(); + let mut received_msg = StreamDataMessage::new(0, Vec::new(), false); + received_msg.unpack(&packed).unwrap(); + reader.feed(&received_msg); + } + + let received = reader.read_all().unwrap(); + assert_eq!(received, data); + } + + #[test] + fn test_writer_small_data_no_compression() { + // bzip2 overhead dominates below 32 bytes, so short inputs must be sent raw. + let mut writer = StreamWriter::new(1, 500); + + let data = b"tiny"; + let msgs = writer.write(data).unwrap(); + assert_eq!(msgs.len(), 1); + assert!(!msgs[0].compressed); + assert_eq!(msgs[0].data, b"tiny"); + } + + #[test] + fn test_writer_empty_write() { + let mut writer = StreamWriter::new(1, 100); + let msgs = writer.write(b"").unwrap(); + assert!(msgs.is_empty()); + } + + #[test] + fn test_drain_close_semantics() { + let mut writer = StreamWriter::new(1, 100); + let _msgs = writer.write(b"some data").unwrap(); + let drain = writer.close(); + assert!(drain.eof_message.eof); + assert!(drain.eof_message.data.is_empty()); + } + + #[test] + fn test_channel_buffer_write_read() { + let stream_id = 7; + let mut buf = ChannelBuffer::new(stream_id, 100); + + assert_eq!(buf.stream_id(), 7); + assert!(!buf.is_done()); + assert!(!buf.is_writer_closed()); + + let msgs = buf.write(b"hello buffer").unwrap(); + assert!(!msgs.is_empty()); + + for msg in &msgs { + assert!(buf.feed_reader(msg)); + } + + assert_eq!(buf.available(), 12); + + let data = buf.read_all().unwrap(); + assert_eq!(data, b"hello buffer"); + } + + #[test] + fn test_channel_buffer_roundtrip() { + let mut buf = ChannelBuffer::new(99, 20); + + let input = b"This is a channel buffer roundtrip test with enough data to split"; + let msgs = buf.write(input).unwrap(); + let eof_msg = buf.close_writer(); + assert!(buf.is_writer_closed()); + + for msg in &msgs { + buf.feed_reader(msg); + } + buf.feed_reader(&eof_msg); + + let output = buf.read_all().unwrap(); + assert_eq!(output, input); + assert!(buf.is_done()); + } + + #[test] + fn test_channel_buffer_partial_read() { + let mut buf = ChannelBuffer::new(5, 100); + + let msgs = buf.write(b"abcdefghij").unwrap(); + for msg in &msgs { + buf.feed_reader(msg); + } + + let partial = buf.read(5).unwrap(); + assert_eq!(partial, b"abcde"); + assert_eq!(buf.available(), 5); + + let rest = buf.read_all().unwrap(); + assert_eq!(rest, b"fghij"); + } + + #[test] + fn test_channel_buffer_no_data() { + // Reads before any frames arrive must distinguish "wait" (None) from EOF. + let mut buf = ChannelBuffer::new(1, 100); + assert!(buf.read(10).is_none()); + assert!(buf.read_all().is_none()); + } + + #[test] + fn test_channel_buffer_close_then_write_fails() { + let mut buf = ChannelBuffer::new(1, 100); + buf.close_writer(); + assert!(buf.write(b"after close").is_err()); + } + + #[test] + fn test_channel_buffer_drain_and_close() { + let mut buf = ChannelBuffer::new(1, 100); + let _msgs = buf.write(b"data to drain").unwrap(); + let drain = buf.drain_and_close_writer(); + assert!(drain.eof_message.eof); + assert!(buf.is_writer_closed()); + } +} diff --git a/crates/rns-protocol/src/channel.rs b/crates/rns-protocol/src/channel.rs new file mode 100644 index 0000000..e2f720b --- /dev/null +++ b/crates/rns-protocol/src/channel.rs @@ -0,0 +1,1184 @@ +use std::collections::{HashMap, VecDeque}; +use std::time::{Duration, Instant}; + +use crate::channel_message::{ + ChannelMessageError, MessageBase, MessageState, SYSTEM_MESSAGE_TYPE_MIN, +}; + +// Flow-control constants, matching the Python Channel reference. + +pub const WINDOW_INITIAL: usize = 2; +pub const WINDOW_MIN: usize = 2; +pub const WINDOW_MIN_LIMIT_SLOW: usize = 2; +pub const WINDOW_MIN_LIMIT_MEDIUM: usize = 5; +pub const WINDOW_MIN_LIMIT_FAST: usize = 16; +pub const WINDOW_MAX_SLOW: usize = 5; +pub const WINDOW_MAX_MEDIUM: usize = 12; +pub const WINDOW_MAX_FAST: usize = 48; +/// Upper ceiling on `window_max` across all tiers; also sizes pre-allocated guard regions. +pub const WINDOW_MAX: usize = WINDOW_MAX_FAST; +/// Consecutive rounds at a tier's RTT before `window_max` is promoted to that tier. +pub const FAST_RATE_THRESHOLD: usize = 10; +/// RTT at or below which a link is considered "fast" (seconds). +pub const RTT_FAST: f64 = 0.18; +/// RTT at or below which a link is considered "medium" (seconds). +pub const RTT_MEDIUM: f64 = 0.75; +/// RTT above which a fresh window starts at a single slot. +pub const RTT_SLOW: f64 = 1.45; +/// Minimum gap `shrink()` will leave between `window_max` and `window_min`. +pub const WINDOW_FLEXIBILITY: usize = 4; + +pub const SEQ_MAX: u16 = 0xFFFF; +pub const SEQ_MODULUS: u32 = 0x10000; + +/// Envelope header: `msgtype(2) || sequence(2) || length(2)`. +pub const ENVELOPE_HEADER_SIZE: usize = 6; + +/// Retransmissions an envelope may absorb before the channel is torn down. +pub const MAX_TRIES: usize = 5; + +/// Floor for the `rtt * 2.5` term used as the base of the retransmit backoff. +pub const MIN_TIMEOUT_BASE: f64 = 0.025; + +/// One outgoing or incoming channel frame. +/// +/// Wire format: `msgtype(2 BE) || sequence(2 BE) || length(2 BE) || data`. +#[derive(Debug, Clone)] +pub struct Envelope { + pub msg_type: u16, + pub sequence: u16, + pub raw: Vec, + pub packed: bool, + pub tries: usize, + pub state: MessageState, + last_sent: Option, +} + +impl Envelope { + /// Serialize `msg` into a fresh envelope at the given sequence number. + pub fn pack(msg: &dyn MessageBase, sequence: u16) -> Self { + let data = msg.pack(); + let msg_type = msg.msg_type(); + let length = data.len() as u16; + + let mut raw = Vec::with_capacity(ENVELOPE_HEADER_SIZE + data.len()); + raw.extend_from_slice(&msg_type.to_be_bytes()); + raw.extend_from_slice(&sequence.to_be_bytes()); + raw.extend_from_slice(&length.to_be_bytes()); + raw.extend_from_slice(&data); + + Self { + msg_type, + sequence, + raw, + packed: true, + tries: 0, + state: MessageState::New, + last_sent: None, + } + } + + /// Parse an envelope from the wire. + /// + /// Python Reticulum ignores the declared length while unpacking and hands + /// all bytes after the six-byte header to the message decoder. + pub fn unpack(raw: &[u8]) -> Result { + if raw.len() < ENVELOPE_HEADER_SIZE { + return Err(ChannelMessageError::TooShort); + } + + let msg_type = u16::from_be_bytes([raw[0], raw[1]]); + let sequence = u16::from_be_bytes([raw[2], raw[3]]); + + Ok(Self { + msg_type, + sequence, + raw: raw.to_vec(), + packed: true, + tries: 0, + state: MessageState::New, + last_sent: None, + }) + } + + pub fn payload(&self) -> &[u8] { + if self.raw.len() > ENVELOPE_HEADER_SIZE { + &self.raw[ENVELOPE_HEADER_SIZE..] + } else { + &[] + } + } +} + +/// Flow-control window state for a single channel. +/// +/// Holds both fast- and medium-tier counters so a link's window size tracks +/// sustained RTT rather than any single measurement. +#[derive(Debug, Clone)] +pub struct ChannelWindow { + pub window: usize, + pub window_min: usize, + pub window_max: usize, + pub window_flexibility: usize, + pub fast_rate_rounds: usize, + pub medium_rate_rounds: usize, +} + +impl ChannelWindow { + /// Build a window sized to the initial `rtt`. Links slower than + /// `RTT_SLOW` start pinned at a single slot with zero flexibility so we + /// don't spray bursts onto a marginal path. + pub fn new(rtt: f64) -> Self { + if rtt > RTT_SLOW { + Self { + window: 1, + window_min: 1, + window_max: 1, + window_flexibility: 1, + fast_rate_rounds: 0, + medium_rate_rounds: 0, + } + } else { + Self { + window: WINDOW_INITIAL, + window_min: WINDOW_MIN, + window_max: WINDOW_MAX_SLOW, + window_flexibility: WINDOW_FLEXIBILITY, + fast_rate_rounds: 0, + medium_rate_rounds: 0, + } + } + } + + /// Record a successful delivery at `rtt` and open the window one notch. + /// + /// Only after `FAST_RATE_THRESHOLD` *consecutive* rounds at the same tier + /// does the ceiling (`window_max`) get promoted — a single fast RTT can't + /// unlock the fast tier. Any measurement that falls out of a tier resets + /// that tier's counter. + pub fn grow(&mut self, rtt: f64) { + if self.window < self.window_max { + self.window += 1; + } + + if rtt == 0.0 { + return; + } + + if rtt > RTT_FAST { + self.fast_rate_rounds = 0; + + if rtt > RTT_MEDIUM { + self.medium_rate_rounds = 0; + } else { + self.medium_rate_rounds += 1; + if self.window_max < WINDOW_MAX_MEDIUM + && self.medium_rate_rounds == FAST_RATE_THRESHOLD + { + self.window_max = WINDOW_MAX_MEDIUM; + self.window_min = WINDOW_MIN_LIMIT_MEDIUM; + } + } + } else { + self.fast_rate_rounds += 1; + if self.window_max < WINDOW_MAX_FAST && self.fast_rate_rounds == FAST_RATE_THRESHOLD { + self.window_max = WINDOW_MAX_FAST; + self.window_min = WINDOW_MIN_LIMIT_FAST; + } + } + } + + /// Pull the window in on retransmit. Also walks `window_max` downwards so + /// long-term packet loss actually demotes the link tier, stopping at the + /// configured `window_flexibility` gap above `window_min`. + pub fn shrink(&mut self) { + if self.window > self.window_min { + self.window -= 1; + + if self.window_max > (self.window_min + self.window_flexibility) { + self.window_max -= 1; + } + } + } +} + +/// Handler for inbound messages on a channel. +/// +/// Invoked with `(msg_type, payload)`. Return `true` to consume the message +/// (subsequent handlers are skipped) or `false` to fall through. +pub type MessageCallback = Box bool + Send>; + +/// Sequenced, reliable message pipe over a Reticulum link. +/// +/// The channel is passive: the owning runtime calls `send`/`receive`/ +/// `timeout`/`delivered` to step the state machine. When one or more message +/// types are registered, inbound envelopes carrying an unregistered type are +/// rejected rather than silently dropped. +pub struct Channel { + next_tx_sequence: u16, + next_rx_sequence: u16, + tx_ring: VecDeque, + rx_ring: VecDeque, + pub window: ChannelWindow, + pub active: bool, + initial_rtt: f64, + /// When non-empty, only these types are accepted on `receive`. + registered_types: Vec, + /// Called in registration order on each delivered message; the first + /// handler that returns `true` stops the chain. + message_handlers: Vec, +} + +impl Channel { + pub fn new(rtt: f64) -> Self { + Self { + next_tx_sequence: 0, + next_rx_sequence: 0, + tx_ring: VecDeque::new(), + rx_ring: VecDeque::new(), + window: ChannelWindow::new(rtt), + active: true, + initial_rtt: rtt, + registered_types: Vec::new(), + message_handlers: Vec::new(), + } + } + + /// Register a user-visible type (`< 0xF000`) for reception. + /// Types at or above `SYSTEM_MESSAGE_TYPE_MIN` must go through + /// [`Self::register_system_type`] to prevent applications from stomping on + /// reserved IDs. + pub fn register_message_type(&mut self, msg_type: u16) -> Result<(), ChannelError> { + if msg_type >= SYSTEM_MESSAGE_TYPE_MIN { + return Err(ChannelError::InvalidMessageType(msg_type)); + } + if !self.registered_types.contains(&msg_type) { + self.registered_types.push(msg_type); + } + Ok(()) + } + + /// Register a reserved system type (`>= 0xF000`) for reception. + pub fn register_system_type(&mut self, msg_type: u16) { + if !self.registered_types.contains(&msg_type) { + self.registered_types.push(msg_type); + } + } + + /// Append `handler` to the end of the callback chain. + pub fn add_message_handler(&mut self, handler: MessageCallback) { + self.message_handlers.push(handler); + } + + pub fn clear_message_handlers(&mut self) { + self.message_handlers.clear(); + } + + fn run_callbacks(&self, msg_type: u16, payload: &[u8]) -> bool { + for handler in &self.message_handlers { + if handler(msg_type, payload) { + 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) + } + + /// True when the channel has window headroom to accept a new outbound message. + pub fn is_ready_to_send(&self) -> bool { + if !self.active { + return false; + } + let outstanding = self + .tx_ring + .iter() + .filter(|e| e.state != MessageState::Delivered) + .count(); + outstanding < self.window.window + } + + /// 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. + pub fn send(&mut self, msg: &dyn MessageBase) -> Result, ChannelError> { + self.send_tracked(msg).map(|(_, raw)| raw) + } + + /// As [`Self::send`], but also returns the assigned sequence number. + pub fn send_tracked(&mut self, msg: &dyn MessageBase) -> Result<(u16, Vec), ChannelError> { + if !self.active { + return Err(ChannelError::ChannelClosed); + } + if !self.is_ready_to_send() { + return Err(ChannelError::NotReady); + } + + 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); + envelope.state = MessageState::Sent; + envelope.tries = 1; + envelope.last_sent = Some(Instant::now()); + + let raw = envelope.raw.clone(); + self.tx_ring.push_back(envelope); + Ok((seq, raw)) + } + + /// Mark a TX envelope as acknowledged and drain any in-order delivered + /// frames off the front of the ring, then open the window. + pub fn delivered(&mut self, sequence: u16, rtt: f64) { + if let Some(env) = self.tx_ring.iter_mut().find(|e| e.sequence == sequence) { + env.state = MessageState::Delivered; + } + while self + .tx_ring + .front() + .is_some_and(|e| e.state == MessageState::Delivered) + { + self.tx_ring.pop_front(); + } + self.window.grow(rtt); + } + + /// Bump the try count for `sequence`. Returns the envelope bytes to + /// retransmit, or an error once `MAX_TRIES` has been exceeded (the channel + /// is marked inactive at that point). + pub fn timeout(&mut self, sequence: u16) -> Result>, ChannelError> { + if let Some(env) = self.tx_ring.iter_mut().find(|e| e.sequence == sequence) { + env.tries += 1; + if env.tries > MAX_TRIES { + self.active = false; + return Err(ChannelError::MaxRetriesExceeded); + } + env.last_sent = Some(Instant::now()); + self.window.shrink(); + return Ok(Some(env.raw.clone())); + } + Ok(None) + } + + /// Return the sequences whose delivery proof timers have expired. + pub fn timed_out_sequences(&self) -> Vec { + self.tx_ring + .iter() + .filter(|env| { + env.state != MessageState::Delivered + && env + .last_sent + .is_some_and(|sent| sent.elapsed() >= self.timeout_duration(env.tries)) + }) + .map(|env| env.sequence) + .collect() + } + + /// Duration until the next outstanding envelope should be retransmitted. + pub fn next_timeout_duration(&self) -> Option { + self.tx_ring + .iter() + .filter(|env| env.state != MessageState::Delivered) + .filter_map(|env| { + let sent = env.last_sent?; + let timeout = self.timeout_duration(env.tries); + Some(timeout.saturating_sub(sent.elapsed())) + }) + .min() + } + + /// Process an inbound envelope and return every newly in-order + /// `(msg_type, payload)` tuple freed by its arrival. Empty payloads are + /// 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)>, ChannelError> { + let envelope = Envelope::unpack(raw).map_err(|_| ChannelError::InvalidEnvelope)?; + + if !self.is_type_registered(envelope.msg_type) { + return Err(ChannelError::UnknownMessageType(envelope.msg_type)); + } + + if !self.is_acceptable_sequence(envelope.sequence) { + return Ok(Vec::new()); + } + + self.emplace_envelope(envelope); + + let mut delivered = Vec::new(); + loop { + let found = self + .rx_ring + .iter() + .position(|e| e.sequence == self.next_rx_sequence); + if let Some(idx) = found { + let env = self.rx_ring.remove(idx).unwrap(); + let payload = env.payload().to_vec(); + + self.run_callbacks(env.msg_type, &payload); + + delivered.push((env.msg_type, payload)); + self.next_rx_sequence = ((self.next_rx_sequence as u32 + 1) % SEQ_MODULUS) as u16; + } else { + break; + } + } + + Ok(delivered) + } + + /// Match Python's receive guard: future sequence numbers are buffered + /// without a window-distance cap, while old sequence numbers are only + /// accepted when the current receive window wraps past zero. + fn is_acceptable_sequence(&self, seq: u16) -> bool { + if seq >= self.next_rx_sequence { + return true; + } + + let window_overflow = + ((self.next_rx_sequence as u32 + WINDOW_MAX as u32) % SEQ_MODULUS) as u16; + window_overflow < self.next_rx_sequence && seq <= window_overflow + } + + /// Insert `envelope` into the reorder buffer in ascending sequence order + /// (accounting for wraparound), ignoring duplicates. + fn emplace_envelope(&mut self, envelope: Envelope) { + if self.rx_ring.iter().any(|e| e.sequence == envelope.sequence) { + return; + } + let pos = self.rx_ring.iter().position(|e| { + let diff_new = if envelope.sequence >= self.next_rx_sequence { + (envelope.sequence - self.next_rx_sequence) as u32 + } else { + SEQ_MODULUS - self.next_rx_sequence as u32 + envelope.sequence as u32 + }; + let diff_existing = if e.sequence >= self.next_rx_sequence { + (e.sequence - self.next_rx_sequence) as u32 + } else { + SEQ_MODULUS - self.next_rx_sequence as u32 + e.sequence as u32 + }; + diff_new < diff_existing + }); + match pos { + Some(idx) => self.rx_ring.insert(idx, envelope), + None => self.rx_ring.push_back(envelope), + } + } + + /// Count of TX envelopes not yet marked `Delivered`. + pub fn outstanding_count(&self) -> usize { + self.tx_ring + .iter() + .filter(|e| e.state != MessageState::Delivered) + .count() + } + + /// Retransmit timeout: `1.5^(tries - 1) * max(rtt * 2.5, MIN_TIMEOUT_BASE) + /// * (outstanding + 1.5)` seconds, using the RTT captured at construction. + pub fn compute_timeout(&self, tries: usize) -> f64 { + let rtt = self.initial_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; + backoff * base * outstanding + } + + fn timeout_duration(&self, tries: usize) -> Duration { + Duration::from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE)) + } + + /// Mark the channel inactive and drop every buffered envelope and + /// handler. Idempotent. + pub fn shutdown(&mut self) { + self.active = false; + self.tx_ring.clear(); + self.rx_ring.clear(); + self.message_handlers.clear(); + } + + /// Convert a link MDU into the payload budget per envelope: subtract the + /// header and cap at `0xFFFF` (the length field is a `u16`). + pub fn channel_mdu(link_mdu: usize) -> usize { + let mdu = link_mdu.saturating_sub(ENVELOPE_HEADER_SIZE); + mdu.min(0xFFFF) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ChannelError { + #[error("channel is closed")] + ChannelClosed, + #[error("channel not ready to send")] + NotReady, + #[error("max retries exceeded")] + MaxRetriesExceeded, + #[error("invalid envelope")] + InvalidEnvelope, + #[error("unknown message type: 0x{0:04X}")] + UnknownMessageType(u16), + #[error("invalid message type: 0x{0:04X} (reserved for system use)")] + InvalidMessageType(u16), +} + +/// A [`Channel`] paired with its link ID and (optionally) link session keys, +/// so the caller can hand raw bytes in and out without threading the +/// encryption layer through themselves. +pub struct LinkChannel { + channel: Channel, + link_id: [u8; 16], + session_keys: Option, + outbound_packet_hashes: HashMap<[u8; 32], u16>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PreparedChannelData { + pub sequence: u16, + pub data: Vec, +} + +impl LinkChannel { + /// Plain-text channel (no transport-side encryption). + pub fn new(link_id: [u8; 16], rtt: f64) -> Self { + Self { + channel: Channel::new(rtt), + link_id, + session_keys: None, + outbound_packet_hashes: HashMap::new(), + } + } + + /// Channel that transparently encrypts outbound frames and decrypts + /// inbound ones with the supplied link session keys. + pub fn new_encrypted( + link_id: [u8; 16], + rtt: f64, + keys: rns_link::key_derivation::LinkKeys, + ) -> Self { + Self { + channel: Channel::new(rtt), + link_id, + session_keys: Some(keys), + outbound_packet_hashes: HashMap::new(), + } + } + + /// Pack `msg`, encrypt with the session keys if present, and return the + /// wire bytes. + pub fn prepare_send(&mut self, msg: &dyn MessageBase) -> Result, ChannelError> { + self.prepare_send_tracked(msg).map(|prepared| prepared.data) + } + + /// As [`Self::prepare_send`], but also returns the channel sequence number + /// so the caller can map the final packet hash back to the channel window. + pub fn prepare_send_tracked( + &mut self, + msg: &dyn MessageBase, + ) -> Result { + let (sequence, raw) = self.channel.send_tracked(msg)?; + if let Some(ref keys) = self.session_keys { + let data = rns_link::encryption::link_encrypt(keys, &raw) + .map_err(|_| ChannelError::ChannelClosed)?; + Ok(PreparedChannelData { sequence, data }) + } else { + Ok(PreparedChannelData { + sequence, + data: raw, + }) + } + } + + /// Decrypt if session keys are present, then hand the payload to the + /// underlying channel and return any newly deliverable messages. + pub fn receive_data(&mut self, raw: &[u8]) -> Result)>, ChannelError> { + let plaintext = if let Some(ref keys) = self.session_keys { + rns_link::encryption::link_decrypt(keys, raw) + .map_err(|_| ChannelError::ChannelClosed)? + } else { + raw.to_vec() + }; + self.channel.receive(&plaintext) + } + + pub fn delivered(&mut self, sequence: u16, rtt: f64) { + self.channel.delivered(sequence, rtt); + } + + pub fn track_outbound_packet_hash(&mut self, packet_hash: [u8; 32], sequence: u16) { + self.outbound_packet_hashes.insert(packet_hash, sequence); + } + + pub fn delivered_by_packet_hash(&mut self, packet_hash: &[u8; 32], rtt: f64) -> Option { + let sequence = self.outbound_packet_hashes.remove(packet_hash)?; + self.delivered(sequence, rtt); + Some(sequence) + } + + pub fn is_ready_to_send(&self) -> bool { + self.channel.is_ready_to_send() + } + + pub fn link_id(&self) -> &[u8; 16] { + &self.link_id + } + + pub fn shutdown(&mut self) { + self.channel.shutdown(); + } + + pub fn is_active(&self) -> bool { + self.channel.active + } + + pub fn timeout(&mut self, sequence: u16) -> Result>, ChannelError> { + let Some(raw) = self.channel.timeout(sequence)? else { + return Ok(None); + }; + if let Some(ref keys) = self.session_keys { + let data = rns_link::encryption::link_encrypt(keys, &raw) + .map_err(|_| ChannelError::ChannelClosed)?; + Ok(Some(data)) + } else { + Ok(Some(raw)) + } + } + + pub fn outstanding_count(&self) -> usize { + self.channel.outstanding_count() + } + + pub fn timed_out_sequences(&self) -> Vec { + self.channel.timed_out_sequences() + } + + pub fn next_timeout_duration(&self) -> Option { + self.channel.next_timeout_duration() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TestMessage { + data: Vec, + } + + impl TestMessage { + fn new(data: &[u8]) -> Self { + Self { + data: data.to_vec(), + } + } + } + + impl MessageBase for TestMessage { + fn msg_type(&self) -> u16 { + 0x0001 + } + fn pack(&self) -> Vec { + self.data.clone() + } + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + self.data = raw.to_vec(); + Ok(()) + } + } + + #[test] + fn test_envelope_pack_unpack() { + let msg = TestMessage::new(b"hello channel"); + let env = Envelope::pack(&msg, 42); + + assert_eq!(env.msg_type, 0x0001); + assert_eq!(env.sequence, 42); + + let env2 = Envelope::unpack(&env.raw).unwrap(); + assert_eq!(env2.msg_type, 0x0001); + assert_eq!(env2.sequence, 42); + assert_eq!(env2.payload(), b"hello channel"); + } + + #[test] + fn test_envelope_length_field_is_not_enforced_on_unpack() { + let msg = TestMessage::new(b"test"); + let mut env = Envelope::pack(&msg, 0); + + // Python reads the length field but gives the full post-header payload + // to the message decoder, even when the declared length is wrong. + env.raw[4] = 0xFF; + env.raw[5] = 0xFF; + + let result = Envelope::unpack(&env.raw).unwrap(); + assert_eq!(result.payload(), b"test"); + + env.raw[4] = 0x00; + env.raw[5] = 0x01; + + let result = Envelope::unpack(&env.raw).unwrap(); + assert_eq!(result.payload(), b"test"); + } + + #[test] + fn test_envelope_too_short() { + assert!(Envelope::unpack(&[0, 1, 2]).is_err()); + } + + #[test] + fn test_channel_send_receive() { + let mut tx_channel = Channel::new(0.1); + let mut rx_channel = Channel::new(0.1); + + let msg = TestMessage::new(b"hello"); + let raw = tx_channel.send(&msg).unwrap(); + + let delivered = rx_channel.receive(&raw).unwrap(); + assert_eq!(delivered.len(), 1); + assert_eq!(delivered[0].0, 0x0001); + assert_eq!(delivered[0].1, b"hello"); + } + + #[test] + fn test_channel_ordering() { + let mut tx = Channel::new(0.1); + let mut rx = Channel::new(0.1); + + let msg1 = TestMessage::new(b"first"); + let msg2 = TestMessage::new(b"second"); + let msg3 = TestMessage::new(b"third"); + + let raw1 = tx.send(&msg1).unwrap(); + let raw2 = tx.send(&msg2).unwrap(); + + // Receive seq 1 before seq 0; it must buffer rather than deliver. + let d2 = rx.receive(&raw2).unwrap(); + assert!(d2.is_empty()); + + // Once seq 0 arrives, both messages drain in order. + let d1 = rx.receive(&raw1).unwrap(); + assert_eq!(d1.len(), 2); + assert_eq!(d1[0].1, b"first"); + assert_eq!(d1[1].1, b"second"); + + tx.delivered(0, 0.1); + tx.delivered(1, 0.1); + + let raw3 = tx.send(&msg3).unwrap(); + let d3 = rx.receive(&raw3).unwrap(); + assert_eq!(d3.len(), 1); + assert_eq!(d3[0].1, b"third"); + } + + #[test] + fn test_channel_flow_control() { + let mut ch = Channel::new(0.1); + assert!(ch.is_ready_to_send()); + + let msg = TestMessage::new(b"a"); + // `WINDOW_INITIAL` = 2 slots, so two sends saturate the window. + ch.send(&msg).unwrap(); + ch.send(&msg).unwrap(); + + assert!(!ch.is_ready_to_send()); + + ch.delivered(0, 0.1); + assert!(ch.is_ready_to_send()); + } + + #[test] + fn test_channel_max_retries() { + let mut ch = Channel::new(0.1); + let msg = TestMessage::new(b"retry"); + ch.send(&msg).unwrap(); + + for _ in 0..MAX_TRIES - 1 { + let result = ch.timeout(0); + assert!(result.is_ok()); + } + // Crossing MAX_TRIES must tear the channel down. + let result = ch.timeout(0); + assert!(result.is_err()); + assert!(!ch.active); + } + + #[test] + fn test_duplicate_rejection() { + let mut tx = Channel::new(0.1); + let mut rx = Channel::new(0.1); + + let msg = TestMessage::new(b"once"); + let raw = tx.send(&msg).unwrap(); + + let d1 = rx.receive(&raw).unwrap(); + assert_eq!(d1.len(), 1); + + // Replay of the same envelope must not re-deliver. + let d2 = rx.receive(&raw).unwrap(); + assert!(d2.is_empty()); + } + + #[test] + fn test_window_growth_fast() { + let mut w = ChannelWindow::new(0.1); + assert_eq!(w.window, WINDOW_INITIAL); + assert_eq!(w.window_max, WINDOW_MAX_SLOW); + + for _ in 0..FAST_RATE_THRESHOLD { + w.grow(0.05); + } + assert_eq!(w.window_max, WINDOW_MAX_FAST); + assert_eq!(w.window_min, WINDOW_MIN_LIMIT_FAST); + } + + #[test] + fn test_window_growth_medium() { + let mut w = ChannelWindow::new(0.1); + assert_eq!(w.window_max, WINDOW_MAX_SLOW); + + for _ in 0..FAST_RATE_THRESHOLD { + w.grow(0.5); + } + assert_eq!(w.window_max, WINDOW_MAX_MEDIUM); + assert_eq!(w.window_min, WINDOW_MIN_LIMIT_MEDIUM); + // Moving into the medium tier must zero out the fast counter. + assert_eq!(w.fast_rate_rounds, 0); + } + + #[test] + fn test_window_growth_slow_resets_counters() { + let mut w = ChannelWindow::new(0.1); + + // Build up fast rounds + for _ in 0..5 { + w.grow(0.05); + } + assert_eq!(w.fast_rate_rounds, 5); + + // Slow RTT resets both counters + w.grow(1.0); + assert_eq!(w.fast_rate_rounds, 0); + assert_eq!(w.medium_rate_rounds, 0); + } + + #[test] + fn test_window_shrink_reduces_window_max() { + // Shrinking must pull the ceiling down, not just the instantaneous window. + let mut w = ChannelWindow::new(0.1); + w.window = 5; + w.window_max = WINDOW_MAX_SLOW + WINDOW_FLEXIBILITY + 2; + let old_max = w.window_max; + + w.shrink(); + assert_eq!(w.window, 4); + assert_eq!(w.window_max, old_max - 1); + } + + #[test] + fn test_window_shrink_respects_flexibility() { + let mut w = ChannelWindow::new(0.1); + w.window = 4; + w.window_max = w.window_min + w.window_flexibility; // exactly at flexibility limit + + w.shrink(); + assert_eq!(w.window, 3); + // Dropping window_max further would violate the flexibility floor. + assert_eq!(w.window_max, w.window_min + w.window_flexibility); + } + + #[test] + fn test_window_slow_rtt_init() { + // RTT past RTT_SLOW must start pinned at a single slot with no flex. + let w = ChannelWindow::new(2.0); + assert_eq!(w.window, 1); + assert_eq!(w.window_max, 1); + assert_eq!(w.window_min, 1); + assert_eq!(w.window_flexibility, 1); + } + + #[test] + fn test_channel_shutdown() { + let mut ch = Channel::new(0.1); + let msg = TestMessage::new(b"test"); + ch.send(&msg).unwrap(); + + ch.shutdown(); + assert!(!ch.active); + assert!(ch.send(&msg).is_err()); + } + + #[test] + fn test_channel_mdu_computation() { + assert_eq!(Channel::channel_mdu(464), 464 - ENVELOPE_HEADER_SIZE); + assert_eq!(Channel::channel_mdu(415), 415 - ENVELOPE_HEADER_SIZE); + // link_mdu smaller than the envelope header must not underflow. + assert_eq!(Channel::channel_mdu(3), 0); + // Length field is u16, so values past 0xFFFF must saturate. + assert_eq!(Channel::channel_mdu(0x20000), 0xFFFF); + } + + #[test] + fn test_sequence_wrapping() { + let mut ch = Channel::new(0.1); + ch.next_tx_sequence = SEQ_MAX; + let msg = TestMessage::new(b"wrap"); + let _raw = ch.send(&msg).unwrap(); + assert_eq!(ch.next_tx_sequence, 0); + } + + #[test] + fn test_envelope_zero_length() { + // An empty payload is a valid envelope, not an error. + let msg = TestMessage::new(b""); + let env = Envelope::pack(&msg, 0); + let env2 = Envelope::unpack(&env.raw).unwrap(); + assert_eq!(env2.payload(), b""); + assert_eq!(env2.msg_type, 0x0001); + } + + #[test] + fn test_unknown_message_type_rejected() { + // Once any type is registered, the whitelist is enforced. + let mut ch = Channel::new(0.1); + ch.register_message_type(0x0001).unwrap(); + + let mut raw = Vec::new(); + raw.extend_from_slice(&0x0002u16.to_be_bytes()); + raw.extend_from_slice(&0x0000u16.to_be_bytes()); + raw.extend_from_slice(&0x0004u16.to_be_bytes()); + raw.extend_from_slice(b"test"); + + let result = ch.receive(&raw); + assert!(matches!( + result, + Err(ChannelError::UnknownMessageType(0x0002)) + )); + } + + #[test] + fn test_registered_type_accepted() { + let mut ch = Channel::new(0.1); + ch.register_message_type(0x0001).unwrap(); + + let mut raw = Vec::new(); + raw.extend_from_slice(&0x0001u16.to_be_bytes()); + raw.extend_from_slice(&0x0000u16.to_be_bytes()); + raw.extend_from_slice(&0x0004u16.to_be_bytes()); + raw.extend_from_slice(b"test"); + + let result = ch.receive(&raw); + assert!(result.is_ok()); + } + + #[test] + fn test_no_registered_types_allows_all() { + // With an empty registry the channel must not filter inbound frames. + let mut ch = Channel::new(0.1); + + let mut raw = Vec::new(); + raw.extend_from_slice(&0x1234u16.to_be_bytes()); + raw.extend_from_slice(&0x0000u16.to_be_bytes()); + raw.extend_from_slice(&0x0004u16.to_be_bytes()); + raw.extend_from_slice(b"test"); + + let result = ch.receive(&raw); + assert!(result.is_ok()); + } + + #[test] + fn test_system_type_registration() { + let mut ch = Channel::new(0.1); + // User types in the system range must be rejected via the public API. + assert!(ch.register_message_type(0xFF00).is_err()); + // The internal register_system_type bypasses the range check. + ch.register_system_type(0xFF00); + assert!(ch.registered_types.contains(&0xFF00)); + } + + #[test] + fn test_multiple_handlers() { + // Handlers run in registration order until one returns true, so the + // third handler here must never see the frame. + use std::sync::{ + Arc, + atomic::{AtomicU32, Ordering}, + }; + + let mut ch = Channel::new(0.1); + let counter = Arc::new(AtomicU32::new(0)); + + let c1 = counter.clone(); + ch.add_message_handler(Box::new(move |_msg_type, _payload| { + c1.fetch_add(1, Ordering::SeqCst); + false + })); + + let c2 = counter.clone(); + ch.add_message_handler(Box::new(move |_msg_type, _payload| { + c2.fetch_add(10, Ordering::SeqCst); + true + })); + + let c3 = counter.clone(); + ch.add_message_handler(Box::new(move |_msg_type, _payload| { + c3.fetch_add(100, Ordering::SeqCst); + false + })); + + let msg = TestMessage::new(b"multi"); + let raw = ch.send(&msg).unwrap(); + + let mut rx = Channel::new(0.1); + let counter2 = counter.clone(); + let c4 = counter2.clone(); + rx.add_message_handler(Box::new(move |_msg_type, _payload| { + c4.fetch_add(1, Ordering::SeqCst); + false + })); + let c5 = counter2.clone(); + rx.add_message_handler(Box::new(move |_msg_type, _payload| { + c5.fetch_add(10, Ordering::SeqCst); + true + })); + let c6 = counter2.clone(); + rx.add_message_handler(Box::new(move |_msg_type, _payload| { + c6.fetch_add(100, Ordering::SeqCst); + false + })); + + rx.receive(&raw).unwrap(); + assert_eq!(counter2.load(Ordering::SeqCst), 11); + } + + #[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); + + assert_eq!(*tx_lc.link_id(), link_id); + assert!(tx_lc.is_active()); + assert!(tx_lc.is_ready_to_send()); + + let msg = TestMessage::new(b"link channel test"); + let raw = tx_lc.prepare_send(&msg).unwrap(); + + let delivered = rx_lc.receive_data(&raw).unwrap(); + assert_eq!(delivered.len(), 1); + assert_eq!(delivered[0].0, 0x0001); + assert_eq!(delivered[0].1, b"link channel test"); + } + + #[test] + fn test_link_channel_roundtrip() { + 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); + + // Send two messages + let msg1 = TestMessage::new(b"first"); + let msg2 = TestMessage::new(b"second"); + + let raw1 = tx_lc.prepare_send(&msg1).unwrap(); + let raw2 = tx_lc.prepare_send(&msg2).unwrap(); + + let d1 = rx_lc.receive_data(&raw1).unwrap(); + assert_eq!(d1.len(), 1); + assert_eq!(d1[0].1, b"first"); + + let d2 = rx_lc.receive_data(&raw2).unwrap(); + assert_eq!(d2.len(), 1); + assert_eq!(d2[0].1, b"second"); + + tx_lc.delivered(0, 0.1); + tx_lc.delivered(1, 0.1); + assert_eq!(tx_lc.outstanding_count(), 0); + } + + #[test] + fn test_link_channel_shutdown() { + let link_id = [0xCC; 16]; + let mut lc = LinkChannel::new(link_id, 0.1); + + assert!(lc.is_active()); + lc.shutdown(); + assert!(!lc.is_active()); + + let msg = TestMessage::new(b"after shutdown"); + assert!(lc.prepare_send(&msg).is_err()); + } + + #[test] + fn test_link_channel_timeout() { + let link_id = [0xDD; 16]; + let mut lc = LinkChannel::new(link_id, 0.1); + + let msg = TestMessage::new(b"timeout test"); + lc.prepare_send(&msg).unwrap(); + + // An unacknowledged envelope must be handed back for resend. + let resend = lc.timeout(0).unwrap(); + assert!(resend.is_some()); + } + + #[test] + fn test_encrypted_link_channel_roundtrip() { + use rns_crypto::x25519::X25519PrivateKey; + use rns_link::constants::MODE_AES256_CBC; + use rns_link::key_derivation::LinkKeys; + + let prv_a = X25519PrivateKey::generate(); + let pub_a = prv_a.public_key(); + let prv_b = X25519PrivateKey::generate(); + let pub_b = prv_b.public_key(); + let link_id = [0xEE; 16]; + + let keys_a = LinkKeys::derive(&prv_a, &pub_b, &link_id, MODE_AES256_CBC).unwrap(); + let keys_b = LinkKeys::derive(&prv_b, &pub_a, &link_id, MODE_AES256_CBC).unwrap(); + + 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); + + let msg = TestMessage::new(b"encrypted hello"); + let raw = tx_lc.prepare_send(&msg).unwrap(); + + // Encrypted output must not match the plaintext envelope produced + // by a non-encrypted channel carrying the same message. + let plain_msg = TestMessage::new(b"encrypted hello"); + let mut plain_ch = LinkChannel::new(link_id, 0.1); + let plain_raw = plain_ch.prepare_send(&plain_msg).unwrap(); + assert_ne!(raw, plain_raw); + + let delivered = rx_lc.receive_data(&raw).unwrap(); + assert_eq!(delivered.len(), 1); + assert_eq!(delivered[0].1, b"encrypted hello"); + } + + #[test] + fn test_mismatched_keys_fail() { + use rns_crypto::x25519::X25519PrivateKey; + use rns_link::constants::MODE_AES256_CBC; + use rns_link::key_derivation::LinkKeys; + + let prv_a = X25519PrivateKey::generate(); + let pub_b = X25519PrivateKey::generate().public_key(); + let link_id = [0xFF; 16]; + + let keys_a = LinkKeys::derive(&prv_a, &pub_b, &link_id, MODE_AES256_CBC).unwrap(); + + // Keys derived from an unrelated pair must not decrypt A's output. + let prv_c = X25519PrivateKey::generate(); + let pub_d = X25519PrivateKey::generate().public_key(); + let keys_wrong = LinkKeys::derive(&prv_c, &pub_d, &link_id, MODE_AES256_CBC).unwrap(); + + 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_wrong); + + let msg = TestMessage::new(b"secret"); + let raw = tx_lc.prepare_send(&msg).unwrap(); + + assert!(rx_lc.receive_data(&raw).is_err()); + } +} diff --git a/crates/rns-protocol/src/channel_message.rs b/crates/rns-protocol/src/channel_message.rs new file mode 100644 index 0000000..4f811e5 --- /dev/null +++ b/crates/rns-protocol/src/channel_message.rs @@ -0,0 +1,50 @@ +/// Base trait for channel messages. +/// +/// All channel messages must define a MSGTYPE (< 0xF000 for user messages), +/// and implement pack/unpack for serialization. +pub trait MessageBase: Send { + /// Unique message type identifier. + /// Must be < 0xF000 for user messages, >= 0xF000 for system messages. + fn msg_type(&self) -> u16; + + /// Serialize the message payload. + fn pack(&self) -> Vec; + + /// Deserialize from raw bytes. + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError>; +} + +/// Reserved message type namespace for system messages. +pub const SYSTEM_MESSAGE_TYPE_MIN: u16 = 0xF000; + +/// System message type for stream data (Buffer). +pub const SMT_STREAM_DATA: u16 = 0xFF00; + +/// Message lifecycle state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MessageState { + New, + Sent, + Delivered, + Failed, +} + +#[derive(Debug, thiserror::Error)] +pub enum ChannelMessageError { + #[error("message unpack failed")] + UnpackFailed, + #[error("invalid message type")] + InvalidType, + #[error("message too short")] + TooShort, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_system_message_range() { + const { assert!(SMT_STREAM_DATA >= SYSTEM_MESSAGE_TYPE_MIN) }; + } +} diff --git a/crates/rns-protocol/src/compression.rs b/crates/rns-protocol/src/compression.rs new file mode 100644 index 0000000..7866297 --- /dev/null +++ b/crates/rns-protocol/src/compression.rs @@ -0,0 +1,101 @@ +use std::io::{Read, Write}; + +/// Maximum size for auto-compression (64 MiB). +pub const AUTO_COMPRESS_MAX_SIZE: usize = 67_108_864; + +/// Compress `data` with bzip2 at the default level. +pub fn bz2_compress(data: &[u8]) -> Result, CompressionError> { + let mut encoder = bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::default()); + encoder + .write_all(data) + .map_err(|_| CompressionError::CompressFailed)?; + encoder + .finish() + .map_err(|_| CompressionError::CompressFailed) +} + +/// Decompress bzip2 `data`, failing once the output would exceed `max_size`. +/// +/// Decoding in chunks lets us stop early on a decompression bomb rather than +/// allocating the full expanded buffer. +pub fn bz2_decompress(data: &[u8], max_size: usize) -> Result, CompressionError> { + let mut decoder = bzip2::read::BzDecoder::new(data); + let mut output = Vec::new(); + + let mut buf = [0u8; 8192]; + loop { + let n = decoder + .read(&mut buf) + .map_err(|_| CompressionError::DecompressFailed)?; + if n == 0 { + break; + } + output.extend_from_slice(&buf[..n]); + if output.len() > max_size { + return Err(CompressionError::DecompressedTooLarge); + } + } + + Ok(output) +} + +/// Compress opportunistically: return the bzip2 output only when it actually +/// shrinks the buffer. The boolean reports which variant was chosen so the +/// caller can set the `compressed` wire flag. +pub fn try_compress(data: &[u8]) -> (Vec, bool) { + if data.len() > AUTO_COMPRESS_MAX_SIZE { + return (data.to_vec(), false); + } + match bz2_compress(data) { + Ok(compressed) if compressed.len() < data.len() => (compressed, true), + _ => (data.to_vec(), false), + } +} + +#[derive(Debug, thiserror::Error)] +pub enum CompressionError { + #[error("bz2 compression failed")] + CompressFailed, + #[error("bz2 decompression failed")] + DecompressFailed, + #[error("decompressed data exceeds size limit")] + DecompressedTooLarge, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_compress_decompress_roundtrip() { + let data = b"Hello, this is test data for compression!".repeat(100); + let compressed = bz2_compress(&data).unwrap(); + assert!(compressed.len() < data.len()); + let decompressed = bz2_decompress(&compressed, data.len() * 2).unwrap(); + assert_eq!(decompressed, data); + } + + #[test] + fn test_decompress_size_limit() { + let data = vec![0u8; 10000]; + let compressed = bz2_compress(&data).unwrap(); + let result = bz2_decompress(&compressed, 100); + assert!(result.is_err()); + } + + #[test] + fn test_try_compress_beneficial() { + let data = b"AAAA".repeat(1000); + let (result, was_compressed) = try_compress(&data); + assert!(was_compressed); + assert!(result.len() < data.len()); + } + + #[test] + fn test_try_compress_not_beneficial() { + // Short, incompressible input must still return without panicking. + let data: Vec = (0..100).map(|i| (i * 37 + 13) as u8).collect(); + let (_result, was_compressed) = try_compress(&data); + let _ = was_compressed; + } +} diff --git a/crates/rns-protocol/src/lib.rs b/crates/rns-protocol/src/lib.rs new file mode 100644 index 0000000..c50d859 --- /dev/null +++ b/crates/rns-protocol/src/lib.rs @@ -0,0 +1,12 @@ +//! Higher-level protocol layers over Links: resource transfer, channels, +//! buffers, and stream I/O. Python reference: `RNS/Resource.py`, +//! `RNS/Channel.py`, `RNS/Buffer.py`. + +pub mod buffer; +pub mod channel; +pub mod channel_message; +pub mod compression; +pub mod resource; +pub mod resource_adv; +pub mod rnsh; +pub mod stream_data; diff --git a/crates/rns-protocol/src/resource.rs b/crates/rns-protocol/src/resource.rs new file mode 100644 index 0000000..28a5ac6 --- /dev/null +++ b/crates/rns-protocol/src/resource.rs @@ -0,0 +1,4384 @@ +use std::collections::HashSet; +use std::time::{Duration, Instant}; + +use rns_crypto::sha::full_hash; + +use crate::compression; + +/// Lifecycle state of a resource transfer. `Rejected` is tagged 0x09 — not +/// 0x00 — so it is wire-distinguishable from `None`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ResourceState { + None = 0x00, + Queued = 0x01, + Advertised = 0x02, + Transferring = 0x03, + AwaitingProof = 0x04, + Assembling = 0x05, + Complete = 0x06, + Failed = 0x07, + Corrupt = 0x08, + Rejected = 0x09, +} + +pub const WINDOW_INITIAL: usize = 4; +pub const WINDOW_MIN: usize = 2; +pub const WINDOW_MAX_SLOW: usize = 10; +pub const WINDOW_MAX_VERY_SLOW: usize = 4; +pub const WINDOW_MAX_FAST: usize = 75; +pub const WINDOW_MAX: usize = 75; +pub const FAST_RATE_THRESHOLD: usize = 4; +pub const VERY_SLOW_RATE_THRESHOLD: usize = 2; +/// bytes/sec — transfer rate above which the window is promoted to fast tier. +pub const RATE_FAST: usize = 6250; +/// bytes/sec — rate below which the window is demoted to the very-slow tier. +pub const RATE_VERY_SLOW: usize = 250; +pub const WINDOW_FLEXIBILITY: usize = 4; +pub const MAPHASH_LEN: usize = 4; +/// Only the low 4 bytes of the resource's random tag ship on the wire (in the +/// advertisement's `r` field) and feed the map-hash calculation. +pub const RANDOM_HASH_SIZE: usize = 4; +pub const SDU: usize = rns_wire::constants::MDU; +/// Largest payload that fits a single-segment resource (1 MiB - 1). +pub const MAX_EFFICIENT_SIZE: usize = 1_048_575; +/// Largest metadata block that a 3-byte length prefix can encode. +pub const METADATA_MAX_SIZE: usize = 16_777_215; +pub const MAX_RETRIES: usize = 16; +pub const MAX_ADV_RETRIES: usize = 4; +pub const SENDER_GRACE_TIME: f64 = 10.0; +pub const PROCESSING_GRACE: f64 = 1.0; +pub const PART_TIMEOUT_FACTOR: f64 = 4.0; +pub const PART_TIMEOUT_FACTOR_AFTER_RTT: f64 = 2.0; +pub const PROOF_TIMEOUT_FACTOR: f64 = 3.0; +pub const RETRY_GRACE_TIME: f64 = 0.25; +pub const PER_RETRY_DELAY: f64 = 0.5; +/// HMU-wait multiplier in the watchdog timeout (Python `Resource.HMU_WAIT_FACTOR`). +/// Applied only when mid-HMU-wait or with no outstanding parts. +pub const HMU_WAIT_FACTOR: f64 = 3.5; +/// Cold-start byte count for the first `update_eifr` call (≈one link handshake); +/// drops out once a real `req_data_rtt_rate` sample arrives. +pub const EIFR_COLD_START_BYTES: usize = 600; +pub const WATCHDOG_MAX_SLEEP: f64 = 1.0; +pub const HASHMAP_IS_NOT_EXHAUSTED: u8 = 0x00; +pub const HASHMAP_IS_EXHAUSTED: u8 = 0xFF; + +/// Link-resource encryption hook applied before chunking payload data. +pub type ResourceEncryptor<'a> = dyn Fn(&[u8]) -> Vec + 'a; +/// Link-resource decryption hook applied after reassembling payload data. +pub type ResourceDecryptor<'a> = dyn Fn(&[u8]) -> Result, ResourceError> + 'a; + +/// Bitfield encoded in the advertisement's `f` field. +/// +/// Wire layout (bit 0 = LSB): +/// 0: encrypted, 1: compressed, 2: split, +/// 3: is_request, 4: is_response, 5: has_metadata. +#[derive(Debug, Clone, Copy, Default)] +pub struct ResourceFlags { + pub encrypted: bool, + pub compressed: bool, + pub split: bool, + pub is_request: bool, + pub is_response: bool, + pub has_metadata: bool, +} + +impl ResourceFlags { + pub fn to_byte(&self) -> u8 { + let mut f = 0u8; + if self.encrypted { + f |= 0x01; + } + if self.compressed { + f |= 0x02; + } + if self.split { + f |= 0x04; + } + if self.is_request { + f |= 0x08; + } + if self.is_response { + f |= 0x10; + } + if self.has_metadata { + f |= 0x20; + } + f + } + + pub fn from_byte(b: u8) -> Self { + Self { + encrypted: b & 0x01 != 0, + compressed: b & 0x02 != 0, + split: b & 0x04 != 0, + is_request: b & 0x08 != 0, + is_response: b & 0x10 != 0, + has_metadata: b & 0x20 != 0, + } + } +} + +/// `SHA-256(data || random_hash)[..MAPHASH_LEN]` — identifies a part slot in the hashmap. +pub fn get_map_hash(data: &[u8], random_hash: &[u8]) -> [u8; MAPHASH_LEN] { + let mut input = Vec::with_capacity(data.len() + random_hash.len()); + input.extend_from_slice(data); + input.extend_from_slice(random_hash); + let hash = full_hash(&input); + let mut result = [0u8; MAPHASH_LEN]; + result.copy_from_slice(&hash[..MAPHASH_LEN]); + result +} + +/// `SHA-256(data || random_hash)` — the advertised resource identifier. +pub fn compute_resource_hash(data: &[u8], random_hash: &[u8]) -> [u8; 32] { + let mut input = Vec::with_capacity(data.len() + random_hash.len()); + input.extend_from_slice(data); + input.extend_from_slice(random_hash); + full_hash(&input) +} + +/// `SHA-256(data || resource_hash)` — value a valid delivery proof must reproduce. +pub fn compute_expected_proof(data: &[u8], resource_hash: &[u8; 32]) -> [u8; 32] { + let mut input = Vec::with_capacity(data.len() + 32); + input.extend_from_slice(data); + input.extend_from_slice(resource_hash); + full_hash(&input) +} + +/// Decode a sender-to-receiver hashmap update: +/// `resource_hash(32) || msgpack([segment_index, hashmap_bytes])`. +pub fn parse_hashmap_update(data: &[u8]) -> Result<([u8; 32], usize, Vec), ResourceError> { + if data.len() < 32 { + return Err(ResourceError::Corrupt); + } + let mut resource_hash = [0u8; 32]; + resource_hash.copy_from_slice(&data[..32]); + + let value = rmpv::decode::read_value(&mut &data[32..]).map_err(|_| ResourceError::Corrupt)?; + let rmpv::Value::Array(items) = value else { + return Err(ResourceError::Corrupt); + }; + if items.len() != 2 { + return Err(ResourceError::Corrupt); + } + let segment = items[0].as_u64().ok_or(ResourceError::Corrupt)? as usize; + let hashmap = items[1].as_slice().ok_or(ResourceError::Corrupt)?.to_vec(); + Ok((resource_hash, segment, hashmap)) +} + +/// Flow control window state for resource transfer. +#[derive(Debug, Clone)] +pub struct WindowState { + pub window: usize, + pub window_min: usize, + pub window_max: usize, + pub fast_rate_rounds: usize, + pub very_slow_rate_rounds: usize, +} + +impl WindowState { + pub fn new() -> Self { + Self { + window: WINDOW_INITIAL, + window_min: WINDOW_MIN, + window_max: WINDOW_MAX_SLOW, + fast_rate_rounds: 0, + very_slow_rate_rounds: 0, + } + } + + /// Grow the window once a whole batch has arrived. Must be called before + /// the next request batch is dispatched so the new slots are visible to + /// the batch-size calculation. + /// + /// Also slides `window_min` up when the window has outgrown its + /// flexibility band, and promotes the ceiling for sustained fast or + /// very-slow links. + 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) { + self.window_min += 1; + } + } + + // Only a run of consecutive fast/very-slow rounds promotes the + // ceiling, so one lucky RTT cannot stretch the window irrevocably. + if rate > RATE_FAST { + self.fast_rate_rounds += 1; + self.very_slow_rate_rounds = 0; + if self.fast_rate_rounds >= FAST_RATE_THRESHOLD { + self.window_max = WINDOW_MAX_FAST; + } + } else if rate < RATE_VERY_SLOW { + self.very_slow_rate_rounds += 1; + self.fast_rate_rounds = 0; + if self.very_slow_rate_rounds >= VERY_SLOW_RATE_THRESHOLD { + self.window_max = WINDOW_MAX_VERY_SLOW; + if self.window > self.window_max { + self.window = self.window_max; + } + } + } else { + self.fast_rate_rounds = 0; + self.very_slow_rate_rounds = 0; + } + } + + /// Shrink the window after a timeout. Both the instantaneous `window` + /// and the ceiling `window_max` contract, and the flexibility band + /// between them is kept within `WINDOW_FLEXIBILITY - 1`. + pub fn shrink(&mut self) { + if self.window > self.window_min { + self.window -= 1; + } + if self.window_max > self.window_min { + self.window_max -= 1; + } + if self.window_max - self.window > WINDOW_FLEXIBILITY - 1 { + self.window_max -= 1; + } + } +} + +impl Default for WindowState { + fn default() -> Self { + Self::new() + } +} + +/// A sender-side resource for outbound transfer. +pub struct OutboundResource { + pub state: ResourceState, + pub data: Vec, + pub random_hash: [u8; RANDOM_HASH_SIZE], + pub resource_hash: [u8; 32], + pub expected_proof: [u8; 32], + pub flags: ResourceFlags, + pub parts: Vec>, + pub map_hashes: Vec<[u8; MAPHASH_LEN]>, + pub total_size: usize, + pub advertisement_data_size: usize, + pub segment_index: usize, + pub total_segments: usize, + /// Request id for request/response resources (`q` in the advertisement). + pub request_id: Option>, + /// Shared hash addressing every segment of the original payload. `Some` + /// for segments emitted by `MultiSegmentOutbound`, `None` otherwise (the + /// wire `original_hash` then equals `resource_hash`). + pub original_hash: Option<[u8; 32]>, + pub window: WindowState, + pub retries: usize, + pub sdu: usize, + /// Optional payload metadata. When set it is prepended to the resource + /// data as `length(3 BE) || metadata` before compression. + pub metadata: Option>, + /// Size of the packed metadata block (length prefix included). + pub metadata_size: usize, +} + +impl OutboundResource { + /// Build a single-segment outbound resource. Payloads above + /// `MAX_EFFICIENT_SIZE` must use `MultiSegmentOutbound`. `encrypt_fn` is + /// applied to the assembled blob after compression, before chunking. + pub fn new( + data: Vec, + auto_compress: bool, + encrypt_fn: Option<&ResourceEncryptor<'_>>, + ) -> Result { + Self::with_options(data, auto_compress, None, None, encrypt_fn) + } + + // Cap retries when uniform data keeps producing colliding map hashes — see + // `with_options_inner` for the retry loop. + const MAX_COLLISION_RETRIES: usize = 5; + + /// Extended constructor with optional metadata and a custom SDU. + /// + /// `metadata` is framed as `length(3 BE) || bytes` and prepended to the + /// data before compression/encryption, matching the Python layout. + /// + /// `link_sdu` lets callers override the default SDU when the link has + /// negotiated a non-standard MTU. + pub fn with_options( + data: Vec, + auto_compress: bool, + metadata: Option>, + link_sdu: Option, + encrypt_fn: Option<&ResourceEncryptor<'_>>, + ) -> Result { + Self::with_options_inner(data, auto_compress, metadata, link_sdu, encrypt_fn, 0) + } + + // Shared body for `new`/`with_options`; re-entered on map-hash collisions + // with `collision_retries` bumped one step, up to MAX_COLLISION_RETRIES. + fn with_options_inner( + data: Vec, + auto_compress: bool, + metadata: Option>, + link_sdu: Option, + encrypt_fn: Option<&ResourceEncryptor<'_>>, + collision_retries: usize, + ) -> Result { + let (packed_metadata, metadata_size, has_metadata) = if let Some(ref meta) = metadata { + if meta.len() > METADATA_MAX_SIZE { + return Err(ResourceError::MetadataTooLarge); + } + let len = meta.len(); + let mut packed = Vec::with_capacity(3 + len); + // 3-byte big-endian length prefix. + packed.push(((len >> 16) & 0xFF) as u8); + packed.push(((len >> 8) & 0xFF) as u8); + packed.push((len & 0xFF) as u8); + packed.extend_from_slice(meta); + let size = packed.len(); + (Some(packed), size, true) + } else { + (None, 0, false) + }; + + if metadata_size + data.len() > MAX_EFFICIENT_SIZE { + return Err(ResourceError::TooLarge); + } + + let random_hash: [u8; RANDOM_HASH_SIZE] = + rns_crypto::random::random_bytes(RANDOM_HASH_SIZE) + .try_into() + .unwrap(); + + let full_data = if let Some(ref meta) = packed_metadata { + let mut full = Vec::with_capacity(meta.len() + data.len()); + full.extend_from_slice(meta); + full.extend_from_slice(&data); + full + } else { + data.clone() + }; + + let (processed_data, compressed) = + if auto_compress && full_data.len() <= compression::AUTO_COMPRESS_MAX_SIZE { + compression::try_compress(&full_data) + } else { + (full_data.clone(), false) + }; + + let mut blob = Vec::with_capacity(RANDOM_HASH_SIZE + processed_data.len()); + blob.extend_from_slice(&random_hash); + blob.extend_from_slice(&processed_data); + + // Encrypt after compression/padding so the link keys protect the + // whole blob before it is chunked. + let blob = if let Some(ref enc) = encrypt_fn { + enc(&blob) + } else { + blob + }; + + // Hashes are computed over plaintext (metadata + data) so a receiver + // can verify them against the reassembled payload regardless of + // whether the link session was encrypted. + let resource_hash = compute_resource_hash(&full_data, &random_hash); + let expected_proof = compute_expected_proof(&full_data, &resource_hash); + + let sdu = link_sdu.unwrap_or(SDU); + + let parts: Vec> = blob.chunks(sdu).map(|c| c.to_vec()).collect(); + + // Uniform data can produce map-hash collisions. When detected we + // regenerate `random_hash` and retry up to MAX_COLLISION_RETRIES; if + // they persist (e.g. identical payload chunks) we proceed with the + // best result rather than looping forever. + let mut map_hashes = Vec::with_capacity(parts.len()); + let mut collision_guard: HashSet<[u8; MAPHASH_LEN]> = HashSet::with_capacity(parts.len()); + let mut has_collision = false; + + for part in &parts { + let mh = get_map_hash(part, &random_hash); + if !collision_guard.insert(mh) { + has_collision = true; + } + map_hashes.push(mh); + } + + if has_collision && collision_retries < Self::MAX_COLLISION_RETRIES { + return Self::with_options_inner( + data, + auto_compress, + metadata, + link_sdu, + encrypt_fn, + collision_retries + 1, + ); + } + + let total_size = blob.len(); + let flags = ResourceFlags { + encrypted: encrypt_fn.is_some(), + compressed, + split: false, + is_request: false, + is_response: false, + has_metadata, + }; + + Ok(Self { + state: ResourceState::None, + data, + random_hash, + resource_hash, + expected_proof, + flags, + parts, + map_hashes, + total_size, + advertisement_data_size: full_data.len(), + segment_index: 1, + total_segments: 1, + request_id: None, + original_hash: None, + window: WindowState::new(), + retries: 0, + sdu, + metadata: packed_metadata, + metadata_size, + }) + } + + /// Check a received delivery proof. Proofs ship as + /// `dest_hash(32) || proof_hash(32)`; only the last 32 bytes are compared. + pub fn validate_proof(&mut self, proof_data: &[u8]) -> bool { + if proof_data.len() < 64 { + return false; + } + let received_proof = &proof_data[32..64]; + if received_proof == self.expected_proof { + self.state = ResourceState::Complete; + true + } else { + false + } + } + + pub fn get_part(&self, index: usize) -> Option<&[u8]> { + self.parts.get(index).map(|p| p.as_slice()) + } + + pub fn num_parts(&self) -> usize { + self.parts.len() + } + + /// Respond to an HMU / resource-request from the receiver. Returns the + /// part indices to (re)send; an exhausted HMU transitions the sender + /// into `AwaitingProof` and returns an empty vector. + pub fn handle_hmu(&mut self, plaintext: &[u8]) -> Vec { + if plaintext.is_empty() { + return Vec::new(); + } + let exhausted = plaintext[0] == HASHMAP_IS_EXHAUSTED; + let data = &plaintext[1..]; + + if exhausted { + self.state = ResourceState::AwaitingProof; + self.window.grow(0); + return Vec::new(); + } + + // A non-exhausted request carries the map-hash of the last part the + // receiver has. We send the window's worth of parts that follow it. + if data.len() >= MAPHASH_LEN { + let mut mh = [0u8; MAPHASH_LEN]; + mh.copy_from_slice(&data[..MAPHASH_LEN]); + for (i, map_hash) in self.map_hashes.iter().enumerate() { + if *map_hash == mh { + let start = i + 1; + let end = (start + self.window.window).min(self.num_parts()); + return (start..end).collect(); + } + } + } + Vec::new() + } + + /// Mark the resource as rejected in response to a cancel from the receiver. + pub fn handle_cancel(&mut self) { + self.state = ResourceState::Rejected; + } +} + +/// A receiver-side resource for inbound transfer. +pub struct InboundResource { + pub state: ResourceState, + pub parts: Vec>>, + pub total_parts: usize, + pub random_hash: [u8; RANDOM_HASH_SIZE], + pub resource_hash: [u8; 32], + pub flags: ResourceFlags, + pub total_size: usize, + pub data_size: usize, + pub consecutive_completed: usize, + pub window: WindowState, + pub map_hashes: Vec<[u8; MAPHASH_LEN]>, + pub sdu: usize, + /// Metadata extracted at `assemble()` time when `flags.has_metadata` was set. + pub metadata: Option>, +} + +impl InboundResource { + /// Construct from an incoming advertisement with the default SDU. + pub fn new( + total_parts: usize, + total_size: usize, + data_size: usize, + random_hash: [u8; RANDOM_HASH_SIZE], + resource_hash: [u8; 32], + flags: ResourceFlags, + initial_map_hashes: Vec<[u8; MAPHASH_LEN]>, + ) -> Result { + Self::with_sdu( + total_parts, + total_size, + data_size, + random_hash, + resource_hash, + flags, + initial_map_hashes, + None, + ) + } + + /// Extended constructor that lets callers supply a non-default SDU when + /// the underlying link has negotiated a custom MTU. + // Mirrors Resource ADV fields after decoding; these values are validated + // together because they describe one advertised transfer. + #[allow(clippy::too_many_arguments)] + pub fn with_sdu( + total_parts: usize, + total_size: usize, + data_size: usize, + random_hash: [u8; RANDOM_HASH_SIZE], + resource_hash: [u8; 32], + flags: ResourceFlags, + initial_map_hashes: Vec<[u8; MAPHASH_LEN]>, + link_sdu: Option, + ) -> Result { + // `total_size` is post-encryption: max plaintext + random_hash + + // TOKEN_OVERHEAD + worst-case PKCS7 pad. + const MAX_AES_BLOCK_PAD: usize = 16; + let max_total_size = + MAX_EFFICIENT_SIZE + RANDOM_HASH_SIZE + rns_crypto::TOKEN_OVERHEAD + MAX_AES_BLOCK_PAD; + if total_size > max_total_size { + return Err(ResourceError::TooLarge); + } + + Ok(Self { + state: ResourceState::Transferring, + parts: vec![None; total_parts], + total_parts, + random_hash, + resource_hash, + flags, + total_size, + data_size, + consecutive_completed: 0, + window: WindowState::new(), + map_hashes: initial_map_hashes, + sdu: link_sdu.unwrap_or(SDU), + metadata: None, + }) + } + + /// Try to slot `data` into the current window by map-hash match. Returns + /// true when the part was accepted into a previously-empty slot. + pub fn receive_part(&mut self, data: Vec) -> bool { + let mh = get_map_hash(&data, &self.random_hash); + + 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::(), + random_hash = %self.random_hash.iter().map(|b| format!("{:02x}", b)).collect::(), + random_len = self.random_hash.len(), + "resource part map hash" + ); + if !self.map_hashes.is_empty() { + tracing::trace!( + hash_0 = %format!( + "{:02x}{:02x}{:02x}{:02x}", + self.map_hashes[0][0], self.map_hashes[0][1], self.map_hashes[0][2], self.map_hashes[0][3] + ), + num_hashes = self.map_hashes.len(), + "resource part expected hash" + ); + } + + // Only scan inside the current receive window — late-arrivals beyond + // it are dropped so replay cannot back-fill completed slots. + let search_start = self.consecutive_completed; + let search_end = (self.consecutive_completed + self.window.window).min(self.total_parts); + + for i in search_start..search_end { + if i < self.map_hashes.len() && self.map_hashes[i] == mh && self.parts[i].is_none() { + self.parts[i] = Some(data); + self.update_consecutive(); + return true; + } + } + + false + } + + fn update_consecutive(&mut self) { + while self.consecutive_completed < self.total_parts { + if self.parts[self.consecutive_completed].is_some() { + self.consecutive_completed += 1; + } else { + break; + } + } + } + + pub fn is_complete(&self) -> bool { + self.consecutive_completed == self.total_parts + } + + /// Reassemble the received parts into the original payload. + /// + /// Steps: concatenate parts → optional decrypt → strip random hash → + /// decompress (bounded by `MAX_EFFICIENT_SIZE` to stop decompression + /// bombs) → verify hash → split off metadata if `flags.has_metadata`. + /// The extracted metadata is stashed in `self.metadata` and the return + /// value is the payload only. + pub fn assemble( + &mut self, + decrypt_fn: Option<&ResourceDecryptor<'_>>, + ) -> Result, ResourceError> { + if !self.is_complete() { + return Err(ResourceError::Incomplete); + } + + self.state = ResourceState::Assembling; + + let mut stream = Vec::with_capacity(self.total_size); + for part in &self.parts { + stream.extend_from_slice(part.as_ref().ok_or(ResourceError::Incomplete)?); + } + + let stream = if let Some(ref dec) = decrypt_fn { + dec(&stream)? + } else { + stream + }; + + if stream.len() < RANDOM_HASH_SIZE { + self.state = ResourceState::Corrupt; + return Err(ResourceError::Corrupt); + } + let data = &stream[RANDOM_HASH_SIZE..]; + + let final_data = if self.flags.compressed { + compression::bz2_decompress(data, MAX_EFFICIENT_SIZE) + .map_err(|_| ResourceError::DecompressionFailed)? + } else { + data.to_vec() + }; + + let calculated_hash = compute_resource_hash(&final_data, &self.random_hash); + if calculated_hash != self.resource_hash { + self.state = ResourceState::Corrupt; + return Err(ResourceError::HashMismatch); + } + + let payload = if self.flags.has_metadata { + if final_data.len() < 3 { + self.state = ResourceState::Corrupt; + return Err(ResourceError::InvalidMetadata { + declared: 0, + available: final_data.len(), + }); + } + let metadata_size = ((final_data[0] as usize) << 16) + | ((final_data[1] as usize) << 8) + | (final_data[2] as usize); + if final_data.len() < 3 + metadata_size { + self.state = ResourceState::Corrupt; + return Err(ResourceError::InvalidMetadata { + declared: metadata_size, + available: final_data.len().saturating_sub(3), + }); + } + self.metadata = Some(final_data[3..3 + metadata_size].to_vec()); + final_data[3 + metadata_size..].to_vec() + } else { + final_data + }; + + self.state = ResourceState::Complete; + Ok(payload) + } + + /// Build the 64-byte delivery proof (`resource_hash(32) || expected_proof(32)`). + pub fn generate_proof(&self, data: &[u8]) -> Vec { + let proof = compute_expected_proof(data, &self.resource_hash); + let mut proof_data = Vec::with_capacity(64); + proof_data.extend_from_slice(&self.resource_hash); + proof_data.extend_from_slice(&proof); + proof_data + } + + pub fn received_count(&self) -> usize { + self.parts.iter().filter(|p| p.is_some()).count() + } + + /// Fraction of parts received, in `0.0..=1.0`. + pub fn progress(&self) -> f64 { + if self.total_parts == 0 { + return 1.0; + } + self.received_count() as f64 / self.total_parts as f64 + } + + /// Fail the transfer and drop any buffered parts so we stop holding the + /// memory for a transfer that will never complete. + pub fn handle_cancel(&mut self) { + self.state = ResourceState::Failed; + for part in &mut self.parts { + *part = None; + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ResourceError { + #[error("resource too large")] + TooLarge, + #[error("resource transfer incomplete")] + Incomplete, + #[error("resource data corrupt")] + Corrupt, + #[error("resource decrypt failed")] + DecryptFailed, + #[error("resource hash mismatch")] + HashMismatch, + #[error("decompression failed")] + DecompressionFailed, + #[error("invalid metadata prefix: declared {declared} bytes, available {available} bytes")] + InvalidMetadata { declared: usize, available: usize }, + #[error("invalid advertisement")] + InvalidAdvertisement, + #[error("map hash collision persists after retries")] + MapHashCollision, + #[error("metadata exceeds maximum size")] + MetadataTooLarge, + /// Caller wrote bytes for a segment slot that already contains data. + /// Surfaces sender-side retransmits at the runtime so they can be logged + /// distinctly from genuine bounds violations. + #[error("segment already received")] + DuplicateSegment, +} + +/// Upper bound on the combined size of all segments (128 MiB - 1). +pub const MAX_RESOURCE_SIZE: usize = 134_217_727; + +/// Max segments per split resource. Caps the ADV's `l` field so a peer +/// can't force allocation of `u32::MAX` slot vectors. Runtime callers must +/// validate `total_segments <= MAX_SEGMENTS` before constructing a coordinator. +pub const MAX_SEGMENTS: usize = 128; + +/// Sender-side coordinator for a resource split across multiple segments. +/// Each segment owns a standalone `OutboundResource`; see +/// `MultiSegmentInbound` for the receive side. +pub struct MultiSegmentOutbound { + pub original_hash: [u8; 32], + pub segments: Vec, + pub total_segments: usize, + pub data_size: usize, +} + +impl MultiSegmentOutbound { + /// Split `data` into `MAX_EFFICIENT_SIZE`-sized chunks, each wrapped in + /// its own `OutboundResource` with `flags.split = true` and the correct + /// `segment_index` / `total_segments` pair. + pub fn new(data: Vec, auto_compress: bool) -> Result { + Self::with_encrypt(data, auto_compress, None) + } + + /// Variant of [`Self::new`] that applies `encrypt_fn` per segment so + /// part payloads are protected while ADVs remain addressable. + pub fn with_encrypt( + data: Vec, + auto_compress: bool, + encrypt_fn: Option<&ResourceEncryptor<'_>>, + ) -> Result { + Self::with_options(data, auto_compress, None, None, false, encrypt_fn) + } + + /// Split a resource while preserving per-resource metadata and request + /// flags. Metadata rides on the first segment and reduces that segment's + /// payload budget so no segment exceeds `MAX_EFFICIENT_SIZE`. + pub fn with_options( + data: Vec, + auto_compress: bool, + metadata: Option>, + request_id: Option>, + is_response: bool, + encrypt_fn: Option<&ResourceEncryptor<'_>>, + ) -> Result { + 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, Option>)> = 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 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); + } + + Ok(Self { + original_hash, + segments, + total_segments, + data_size, + }) + } + + pub fn get_segment(&self, index: usize) -> Option<&OutboundResource> { + self.segments.get(index) + } + + pub fn get_segment_mut(&mut self, index: usize) -> Option<&mut OutboundResource> { + self.segments.get_mut(index) + } + + pub fn num_segments(&self) -> usize { + self.segments.len() + } + + /// True once every segment has received its delivery proof. + pub fn is_complete(&self) -> bool { + self.segments + .iter() + .all(|s| s.state == ResourceState::Complete) + } + + /// Mark every still-active segment as `Failed` and report how many were + /// newly transitioned. Emitting per-segment cancel packets is left to + /// the engine, which observes `Failed` on its next tick. Already-failed + /// or already-complete segments are skipped. + pub fn cancel_all(&mut self) -> usize { + let mut cancelled = 0; + for segment in &mut self.segments { + if !matches!( + segment.state, + ResourceState::Failed | ResourceState::Complete + ) { + segment.state = ResourceState::Failed; + cancelled += 1; + } + } + cancelled + } +} + +/// 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 +/// `set_segment_data` (runtime, where `InboundTransfer` owns the segment). +pub struct MultiSegmentInbound { + pub original_hash: [u8; 32], + pub total_segments: usize, + pub segments: Vec>, + pub assembled_segments: Vec>>, + pub data_size: usize, + /// First non-None metadata observed across the segment stream. Rust's + /// `MultiSegmentOutbound` attaches no per-segment metadata, but Python + /// peers may. + pub metadata: Option>, +} + +impl MultiSegmentInbound { + /// Allocate slots for `total_segments` segments; seed with the + /// `original_hash` advertised by the sender for the full payload. + pub fn new(total_segments: usize, original_hash: [u8; 32]) -> Self { + Self { + original_hash, + total_segments, + segments: (0..total_segments).map(|_| None).collect(), + assembled_segments: (0..total_segments).map(|_| None).collect(), + data_size: 0, + metadata: None, + } + } + + /// Attach an inbound resource. `segment_index` is 1-based (as it appears + /// on the wire) and silently ignored when out of range. + pub fn set_segment(&mut self, segment_index: usize, resource: InboundResource) { + if segment_index >= 1 && segment_index <= self.total_segments { + self.segments[segment_index - 1] = Some(resource); + } + } + + /// Assemble the segment at `segment_index` (1-based) and stash the + /// bytes for later `reassemble()`. + pub fn assemble_segment( + &mut self, + segment_index: usize, + decrypt_fn: Option<&ResourceDecryptor<'_>>, + ) -> Result<(), ResourceError> { + if segment_index < 1 || segment_index > self.total_segments { + return Err(ResourceError::InvalidAdvertisement); + } + let idx = segment_index - 1; + if let Some(ref mut resource) = self.segments[idx] { + let data = resource.assemble(decrypt_fn)?; + self.assembled_segments[idx] = Some(data); + Ok(()) + } else { + Err(ResourceError::Incomplete) + } + } + + /// Runtime ingest of an assembled segment at 1-based `segment_index`. + /// Errors: `InvalidAdvertisement` for out-of-range index; + /// `DuplicateSegment` on overwrite (slot already accepted). + pub fn set_segment_data( + &mut self, + segment_index: usize, + data: Vec, + ) -> Result<(), ResourceError> { + if segment_index < 1 || segment_index > self.total_segments { + return Err(ResourceError::InvalidAdvertisement); + } + let idx = segment_index - 1; + if self.assembled_segments[idx].is_some() { + return Err(ResourceError::DuplicateSegment); + } + self.data_size = self.data_size.saturating_add(data.len()); + self.assembled_segments[idx] = Some(data); + Ok(()) + } + + /// Record metadata for the reassembled payload; first non-None wins. + pub fn set_metadata(&mut self, meta: Vec) { + if self.metadata.is_none() { + self.metadata = Some(meta); + } + } + + pub fn is_complete(&self) -> bool { + self.assembled_segments.iter().all(|s| s.is_some()) + } + + /// Concatenate every assembled segment into the original payload. + pub fn reassemble(&self) -> Result, ResourceError> { + if !self.is_complete() { + return Err(ResourceError::Incomplete); + } + let mut result = Vec::new(); + for seg in &self.assembled_segments { + result.extend_from_slice(seg.as_ref().ok_or(ResourceError::Incomplete)?); + } + Ok(result) + } + + pub fn assembled_count(&self) -> usize { + self.assembled_segments + .iter() + .filter(|s| s.is_some()) + .count() + } + + /// Fraction of segments assembled so far, in `0.0..=1.0`. + pub fn progress(&self) -> f64 { + if self.total_segments == 0 { + return 1.0; + } + self.assembled_count() as f64 / self.total_segments as f64 + } +} + +/// Either side of a single-segment resource transfer, tagged with the owning +/// link's ID and optionally its session keys for transparent encryption. +pub struct LinkResource { + pub link_id: [u8; 16], + pub outbound: Option, + pub inbound: Option, + pub session_keys: Option, +} + +impl LinkResource { + /// Build an outbound resource for sending over a plaintext link. + pub fn new_outbound( + link_id: [u8; 16], + data: Vec, + auto_compress: bool, + ) -> Result { + let outbound = OutboundResource::new(data, auto_compress, None)?; + Ok(Self { + link_id, + outbound: Some(outbound), + inbound: None, + session_keys: None, + }) + } + + /// Build an outbound resource whose reassembled blob is encrypted with + /// the supplied link session keys before chunking. + pub fn new_outbound_encrypted( + link_id: [u8; 16], + data: Vec, + auto_compress: bool, + keys: rns_link::key_derivation::LinkKeys, + ) -> Result { + let encrypt_fn = |plaintext: &[u8]| -> Vec { + rns_link::encryption::link_encrypt(&keys, plaintext) + .unwrap_or_else(|_| plaintext.to_vec()) + }; + let outbound = OutboundResource::new(data, auto_compress, Some(&encrypt_fn))?; + Ok(Self { + link_id, + outbound: Some(outbound), + inbound: None, + session_keys: Some(keys), + }) + } + + /// Create for receiving data over a link. + // Same advertised resource field set as `InboundResource::with_sdu`, plus + // the link id that owns the transfer. + #[allow(clippy::too_many_arguments)] + pub fn new_inbound( + link_id: [u8; 16], + total_parts: usize, + total_size: usize, + data_size: usize, + random_hash: [u8; RANDOM_HASH_SIZE], + resource_hash: [u8; 32], + flags: ResourceFlags, + map_hashes: Vec<[u8; MAPHASH_LEN]>, + ) -> Result { + let inbound = InboundResource::new( + total_parts, + total_size, + data_size, + random_hash, + resource_hash, + flags, + map_hashes, + )?; + Ok(Self { + link_id, + outbound: None, + inbound: Some(inbound), + session_keys: None, + }) + } + + /// Per-part transport encryption for outbound transfers. Returns the + /// ciphertext when the link carries session keys, otherwise the + /// untouched plaintext. + pub fn next_part(&self, index: usize) -> Option> { + let part = self.outbound.as_ref()?.get_part(index)?; + if let Some(ref keys) = self.session_keys { + rns_link::encryption::link_encrypt(keys, part).ok() + } else { + Some(part.to_vec()) + } + } + + /// Inbound counterpart of `next_part`. Decryption failures silently + /// drop the part (returning false) so the caller can simply retry. + pub fn receive_part(&mut self, data: Vec) -> bool { + let plaintext = if let Some(ref keys) = self.session_keys { + match rns_link::encryption::link_decrypt(keys, &data) { + Ok(pt) => pt, + Err(_) => return false, + } + } else { + data + }; + if let Some(ref mut inbound) = self.inbound { + inbound.receive_part(plaintext) + } else { + false + } + } + + pub fn is_complete(&self) -> bool { + self.inbound.as_ref().is_some_and(|i| i.is_complete()) + } + + /// Reassemble the inbound resource, applying session-key decryption when + /// keys were provided at construction. + pub fn assemble(&mut self) -> Result, ResourceError> { + let decrypt_fn: Option>> = + if let Some(ref keys) = self.session_keys { + let keys = keys.clone(); + Some(Box::new(move |ciphertext: &[u8]| { + rns_link::encryption::link_decrypt(&keys, ciphertext) + .map_err(|_| ResourceError::Corrupt) + })) + } else { + None + }; + self.inbound + .as_mut() + .ok_or(ResourceError::Incomplete)? + .assemble(decrypt_fn.as_deref()) + } + + /// Inbound progress in `0.0..=1.0`. Outbound transfers report 0.0 + /// because progress is tracked at the engine layer via HMU feedback. + pub fn progress(&self) -> f64 { + if let Some(ref inbound) = self.inbound { + inbound.progress() + } else { + 0.0 + } + } + + pub fn num_parts(&self) -> usize { + if let Some(ref outbound) = self.outbound { + outbound.num_parts() + } else if let Some(ref inbound) = self.inbound { + inbound.total_parts + } else { + 0 + } + } + + pub fn validate_proof(&mut self, proof_data: &[u8]) -> bool { + if let Some(ref mut outbound) = self.outbound { + outbound.validate_proof(proof_data) + } else { + false + } + } +} + +/// Side-effect requested by the transfer engine on its caller. +#[derive(Debug, Clone, PartialEq)] +pub enum TransferAction { + None, + SendAdvertisement(Vec), + /// `(part_index, part_data)`. + SendPart(usize, Vec), + SendProof(Vec), + /// Hashmap update frame from receiver to sender. + SendHmu(Vec), + /// Receiver-to-sender request for specific parts. Payload layout: + /// `exhausted_flag || optional last_map_hash || resource_hash || requested_part_hashes...`. + SendRequest(Vec), + Complete, + /// Transfer aborted with a diagnostic reason. + Failed(String), + /// `ICL` (initiator cancel) or `RCL` (receiver cancel), plus resource hash. + SendCancel(CancelType, [u8; 32]), +} + +/// Cancel message types. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CancelType { + /// Initiator (sender) cancel. + Icl, + /// Receiver cancel. + Rcl, +} + +/// Sender-side resource transfer state machine with windowed flow control. +/// Driven by the owning runtime via `tick()`; never spawns its own tasks. +pub struct OutboundTransfer { + pub resource: OutboundResource, + pub cursor: usize, + pub confirmed_parts: Vec, + pub window_cursor: usize, + pub retries: usize, + pub last_part_sent: Option, + pub started_at: Instant, + pub rtt: Duration, + pub awaiting_hmu: bool, + pub advertised: bool, + pub window_max_sent: usize, + /// Lowest `consecutive_completed` height the receiver has reported. + /// Scopes the search range when servicing RESOURCE_REQ lookups. + pub receiver_min_consecutive_height: usize, + pub sent_parts: usize, + req_hashlist: HashSet<[u8; 32]>, +} + +impl OutboundTransfer { + pub fn new(data: Vec, auto_compress: bool, rtt: Duration) -> Result { + let resource = OutboundResource::new(data, auto_compress, None)?; + Ok(Self::from_resource(resource, rtt)) + } + + /// Pre-encrypt the blob with link session keys before chunking. Parts + /// emitted from this transfer are already ciphertext and must be sent + /// raw (context=Resource, no additional link-layer encryption). + pub fn new_encrypted( + data: Vec, + auto_compress: bool, + rtt: Duration, + keys: rns_link::key_derivation::LinkKeys, + ) -> Result { + let encrypt_fn = |plaintext: &[u8]| -> Vec { + rns_link::encryption::link_encrypt(&keys, plaintext) + .unwrap_or_else(|_| plaintext.to_vec()) + }; + let resource = OutboundResource::new(data, auto_compress, Some(&encrypt_fn))?; + Ok(Self::from_resource(resource, rtt)) + } + + /// Build a transfer from a pre-constructed resource (e.g. one with + /// metadata attached via [`OutboundResource::with_options`]). + pub fn from_prebuilt(resource: OutboundResource, rtt: Duration) -> Self { + Self::from_resource(resource, rtt) + } + + fn from_resource(resource: OutboundResource, rtt: Duration) -> Self { + let num_parts = resource.num_parts(); + Self { + resource, + cursor: 0, + confirmed_parts: vec![false; num_parts], + window_cursor: 0, + retries: 0, + last_part_sent: None, + started_at: Instant::now(), + rtt, + awaiting_hmu: false, + advertised: false, + window_max_sent: 0, + receiver_min_consecutive_height: 0, + sent_parts: 0, + req_hashlist: HashSet::new(), + } + } + + /// Advance the transfer state machine one step and emit the side-effect + /// the caller should perform. Safe to poll idle. + pub fn tick(&mut self) -> TransferAction { + if self.resource.state == ResourceState::Complete { + return TransferAction::Complete; + } + if self.resource.state == ResourceState::Failed { + return TransferAction::Failed("transfer failed".to_string()); + } + + if !self.advertised { + self.advertised = true; + self.resource.state = ResourceState::Advertised; + return TransferAction::SendAdvertisement(self.create_advertisement()); + } + + if self.awaiting_hmu { + if let Some(last) = self.last_part_sent { + let timeout = self.part_timeout(); + if last.elapsed() > timeout { + self.retries += 1; + if self.retries > MAX_RETRIES { + self.resource.state = ResourceState::Failed; + return TransferAction::Failed("max retries exceeded".to_string()); + } + // Back off before resending the window. + self.awaiting_hmu = false; + self.resource.window.shrink(); + } + } + return TransferAction::None; + } + + if self.cursor < self.resource.num_parts() { + let window_end = + (self.cursor + self.resource.window.window).min(self.resource.num_parts()); + + if self.window_cursor < window_end { + let part_idx = self.window_cursor; + self.window_cursor += 1; + + if !self.confirmed_parts[part_idx] { + let part_data = self.resource.get_part(part_idx).map(|p| p.to_vec()); + if let Some(part_data) = part_data { + self.last_part_sent = Some(Instant::now()); + self.resource.state = ResourceState::Transferring; + + if self.window_cursor >= window_end { + // Last part in the window is now in flight; stop + // sending and wait for the receiver's HMU. + self.awaiting_hmu = true; + self.window_max_sent = window_end; + } + + return TransferAction::SendPart(part_idx, part_data); + } + } else { + return self.tick(); + } + } + } + + if self.all_confirmed() { + self.resource.state = ResourceState::AwaitingProof; + } + + TransferAction::None + } + + /// Consume a hashmap-update frame from the receiver. + /// + /// Wire layout: + /// exhausted_flag(1) = 0xFF (complete) or 0x00 (incomplete) + /// [last_map_hash(4)] — only when exhausted + /// resource_hash(32) + /// requested_hashes(N * MAPHASH_LEN) — hashes the receiver still needs + /// + /// When not exhausted, parts in the sent window whose hash is *not* in + /// the requested set are marked confirmed. + pub fn handle_hmu(&mut self, hmu_data: &[u8]) { + if hmu_data.is_empty() { + return; + } + + let exhausted = hmu_data[0] == HASHMAP_IS_EXHAUSTED; + let mut offset = 1; + + // If exhausted, skip the last_map_hash(4) + if exhausted { + offset += MAPHASH_LEN; + } + + // Skip resource_hash(32) — we already know which resource this is + if hmu_data.len() < offset + 32 { + // Malformed HMU, not enough data for resource_hash + return; + } + offset += 32; + + // When not exhausted: the remaining data contains hashes of parts + // the receiver still NEEDS. We mark everything else as confirmed. + if !exhausted { + // Parse the set of requested (needed) hashes + let requested_data = &hmu_data[offset..]; + let mut requested_set: HashSet<[u8; MAPHASH_LEN]> = HashSet::new(); + for chunk in requested_data.chunks_exact(MAPHASH_LEN) { + let mut mh = [0u8; MAPHASH_LEN]; + mh.copy_from_slice(chunk); + requested_set.insert(mh); + } + + // Parts within the sent window that are NOT in the requested set + // are confirmed as received. + let window_start = self.cursor; + let window_end = self + .window_max_sent + .max((self.cursor + self.resource.window.window).min(self.resource.num_parts())); + + let mut newly_confirmed = 0; + for i in window_start..window_end { + if i < self.resource.map_hashes.len() + && !self.confirmed_parts[i] + && !requested_set.contains(&self.resource.map_hashes[i]) + { + self.confirmed_parts[i] = true; + newly_confirmed += 1; + } + } + + // Advance cursor past confirmed parts + while self.cursor < self.resource.num_parts() && self.confirmed_parts[self.cursor] { + self.cursor += 1; + } + + // Reset window cursor for next batch — start by resending requested parts + self.window_cursor = self.cursor; + self.awaiting_hmu = false; + + // Grow window on successful delivery + if newly_confirmed > 0 { + let elapsed = self.started_at.elapsed().as_secs_f64(); + let rate = if elapsed > 0.0 { + (newly_confirmed * SDU) as f64 / elapsed + } else { + 0.0 + }; + self.resource.window.grow(rate as usize); + self.retries = 0; + } + } else { + // Exhausted: receiver has all parts. Confirm everything. + for i in 0..self.confirmed_parts.len() { + self.confirmed_parts[i] = true; + } + self.cursor = self.resource.num_parts(); + self.window_cursor = self.cursor; + self.awaiting_hmu = false; + + // Transition to awaiting proof + self.resource.state = ResourceState::AwaitingProof; + self.resource.window.grow(0); + } + } + + /// Sender-side handler for a RESOURCE_REQ built by the receiver's + /// `request_next()`. + /// + /// Wire layout: + /// exhausted_flag(1) = 0xFF (needs more hashmap) / 0x00 (normal) + /// [last_map_hash(MAPHASH_LEN)] — only when exhausted + /// resource_hash(32) + /// requested_hashes(N * MAPHASH_LEN) + /// + /// Returns the parts to retransmit and — when the receiver's hashmap is + /// exhausted — an HMU carrying the next hashmap segment. + pub fn handle_request_packet( + &mut self, + packet_hash: [u8; 32], + request_data: &[u8], + ) -> Vec { + if self.req_hashlist.contains(&packet_hash) { + return Vec::new(); + } + self.req_hashlist.insert(packet_hash); + self.handle_request(request_data) + } + + pub fn handle_request(&mut self, request_data: &[u8]) -> Vec { + if request_data.is_empty() || self.resource.state == ResourceState::Failed { + return Vec::new(); + } + + // Refine the RTT estimate using the elapsed time since startup. + let elapsed = self.started_at.elapsed(); + if self.rtt == Duration::ZERO || elapsed < self.rtt { + self.rtt = elapsed; + } + + if self.resource.state != ResourceState::Transferring { + self.resource.state = ResourceState::Transferring; + } + + self.retries = 0; + + let wants_more_hashmap = request_data[0] == HASHMAP_IS_EXHAUSTED; + let pad = if wants_more_hashmap { + 1 + MAPHASH_LEN + } else { + 1 + }; + + // Skip past the flag (+ optional last_map_hash) and the 32-byte resource_hash. + let hash_offset = pad + 32; + if request_data.len() < hash_offset { + return Vec::new(); + } + + let requested_hashes_data = &request_data[hash_offset..]; + + let mut requested_map_hashes: Vec<[u8; MAPHASH_LEN]> = Vec::new(); + for chunk in requested_hashes_data.chunks_exact(MAPHASH_LEN) { + let mut mh = [0u8; MAPHASH_LEN]; + mh.copy_from_slice(chunk); + requested_map_hashes.push(mh); + } + + // 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 search_start = self.receiver_min_consecutive_height; + let search_end = (search_start + guard_size).min(self.resource.num_parts()); + + let mut actions: Vec = Vec::new(); + let mut sent_count = 0; + + for i in search_start..search_end { + if i < self.resource.map_hashes.len() + && requested_map_hashes.contains(&self.resource.map_hashes[i]) + && let Some(part_data) = self.resource.get_part(i) + { + actions.push(TransferAction::SendPart(i, part_data.to_vec())); + sent_count += 1; + } + } + + self.last_part_sent = Some(Instant::now()); + + if wants_more_hashmap && request_data.len() > MAPHASH_LEN { + let mut last_map_hash = [0u8; MAPHASH_LEN]; + last_map_hash.copy_from_slice(&request_data[1..1 + MAPHASH_LEN]); + + // Locate the part following the receiver's last received hash. + let mut part_index = search_start; + for i in search_start..search_end { + part_index = i + 1; + if i < self.resource.map_hashes.len() + && self.resource.map_hashes[i] == last_map_hash + { + break; + } + } + + // Clamp the receiver's reported height to the trailing window + // so a stale report cannot rewind the search range. + self.receiver_min_consecutive_height = if part_index > WINDOW_MAX { + part_index - 1 - WINDOW_MAX + } else { + 0 + }; + + let hashmap_max_len = + crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU); + + // Python cancels if an exhausted request cursor is not aligned to + // a hashmap segment boundary. + if hashmap_max_len > 0 && !part_index.is_multiple_of(hashmap_max_len) { + self.resource.state = ResourceState::Failed; + actions.push(TransferAction::SendCancel( + CancelType::Icl, + self.resource.resource_hash, + )); + return actions; + } + + if let Some(segment) = part_index.checked_div(hashmap_max_len) { + let hashmap_start = segment * hashmap_max_len; + let hashmap_end = ((segment + 1) * hashmap_max_len).min(self.resource.num_parts()); + + let mut hashmap_bytes = Vec::new(); + for i in hashmap_start..hashmap_end { + if i < self.resource.map_hashes.len() { + hashmap_bytes.extend_from_slice(&self.resource.map_hashes[i]); + } + } + + // HMU wire layout: resource_hash(32) || msgpack([segment, hashmap]). + let hmu_payload = { + use rmpv::Value; + let arr = Value::Array(vec![ + Value::Integer((segment as u64).into()), + Value::Binary(hashmap_bytes), + ]); + let mut buf = Vec::new(); + buf.extend_from_slice(&self.resource.resource_hash); + rmpv::encode::write_value(&mut buf, &arr) + .expect("msgpack encode should succeed"); + buf + }; + + actions.push(TransferAction::SendHmu(hmu_payload)); + } + } + + if sent_count > 0 { + let total_sent = self.confirmed_parts.iter().filter(|&&c| c).count() + sent_count; + if total_sent >= self.resource.num_parts() { + self.resource.state = ResourceState::AwaitingProof; + } + } + + actions + } + + pub fn handle_cancel(&mut self) { + self.resource.state = ResourceState::Failed; + } + + /// Check a delivery proof; transitions to `Complete` on match. + pub fn handle_proof(&mut self, proof_data: &[u8]) -> bool { + self.resource.validate_proof(proof_data) + } + + pub fn all_confirmed(&self) -> bool { + self.confirmed_parts.iter().all(|&c| c) + } + + /// Retransmit timeout, scaled by retry count and capped at 30s to keep + /// a pathologically slow link from stalling a transfer forever. + fn part_timeout(&self) -> Duration { + let base = self.rtt.as_secs_f64() * PART_TIMEOUT_FACTOR_AFTER_RTT; + let timeout = base.max(0.025) * (self.retries as f64 + 1.5); + Duration::from_secs_f64(timeout.min(30.0)) + } + + /// Build the msgpack-encoded advertisement that precedes the transfer. + fn create_advertisement(&self) -> Vec { + use rmpv::Value; + + let mut adv = crate::resource_adv::ResourceAdvertisement::new( + self.resource.total_size, + self.resource.advertisement_data_size, + self.resource.num_parts(), + self.resource.resource_hash, + self.resource.random_hash.to_vec(), + self.resource.flags, + &self.resource.map_hashes, + rns_wire::constants::ENCRYPTED_MDU, + ); + // `ResourceAdvertisement::new` defaults to single-segment metadata + // (`segment_index = 1`, `total_segments = 1`, `original_hash = + // resource_hash`). For a segment of a `MultiSegmentOutbound`, propagate + // the actual segmentation metadata so the receiver's coordinator can + // reassemble — without this the wire ADV would announce each segment + // as an independent single-segment resource. + if self.resource.flags.split { + adv.segment_index = self.resource.segment_index; + adv.total_segments = self.resource.total_segments; + if let Some(oh) = self.resource.original_hash { + adv.original_hash = oh; + } + } + adv.request_id = self.resource.request_id.clone(); + + let q_val = match &adv.request_id { + Some(id) => Value::Binary(id.clone()), + None => Value::Nil, + }; + + let pairs: Vec<(Value, Value)> = vec![ + ( + Value::String("t".into()), + Value::Integer(adv.transfer_size.into()), + ), + ( + Value::String("d".into()), + Value::Integer(adv.data_size.into()), + ), + ( + Value::String("n".into()), + Value::Integer(adv.num_parts.into()), + ), + ( + Value::String("h".into()), + Value::Binary(adv.resource_hash.to_vec()), + ), + ( + Value::String("r".into()), + Value::Binary(adv.random_hash.to_vec()), + ), + ( + Value::String("o".into()), + Value::Binary(adv.original_hash.to_vec()), + ), + ( + Value::String("i".into()), + Value::Integer(adv.segment_index.into()), + ), + ( + Value::String("l".into()), + Value::Integer(adv.total_segments.into()), + ), + (Value::String("q".into()), q_val), + ( + Value::String("f".into()), + Value::Integer(adv.flags.to_byte().into()), + ), + ( + Value::String("m".into()), + Value::Binary(adv.hashmap.clone()), + ), + ]; + + let value = Value::Map(pairs); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &value).expect("msgpack encode failed"); + buf + } + + /// Fraction of parts confirmed, in `0.0..=1.0`. + pub fn progress(&self) -> f64 { + let confirmed = self.confirmed_parts.iter().filter(|&&c| c).count(); + if self.resource.num_parts() == 0 { + return 1.0; + } + confirmed as f64 / self.resource.num_parts() as f64 + } +} + +/// Receiver-side resource transfer state machine. Accepts parts, emits HMUs +/// and RESOURCE_REQs, and produces the delivery proof once every part is in. +pub struct InboundTransfer { + pub resource: InboundResource, + pub parts_since_hmu: usize, + pub started_at: Instant, + pub accepted: bool, + pub rtt: Duration, + /// Parts that have been requested but not yet arrived. + pub outstanding_parts: usize, + pub last_activity: Instant, + pub req_sent: Option, + pub req_resp: Option, + pub retries_left: usize, + pub waiting_for_hmu: bool, + /// Number of map hashes received from the sender so far. + pub hashmap_height: usize, + /// Current part timeout multiplier. Starts at `PART_TIMEOUT_FACTOR` and + /// relaxes to `PART_TIMEOUT_FACTOR_AFTER_RTT` once the first RTT sample + /// lands so we don't retry too aggressively before we know the link. + pub part_timeout_factor: f64, + + /// Total bytes received this transfer. Python `rtt_rxd_bytes`. + pub rtt_rxd_bytes: usize, + /// Byte counter snapshot taken every `request_next()` so the next + /// completed round can compute a delta. Python + /// `rtt_rxd_bytes_at_part_req`. + pub rtt_rxd_bytes_at_part_req: usize, + /// Last measured bytes/sec over the completed window. Python + /// `req_data_rtt_rate`. Zero means "no sample yet" and forces the + /// EIFR fallback chain. + pub req_data_rtt_rate: f64, + /// Most recent effective inflight rate, in bits/sec. Python `eifr`. + /// `None` until `update_eifr()` runs at least once. + pub eifr: Option, + /// Previous non-zero EIFR sample — seeded from the link's history on + /// link-level ports, or left `None` on fresh receivers. Python + /// `previous_eifr`. + pub previous_eifr: Option, +} + +impl InboundTransfer { + /// Create from a received advertisement. + // Mirrors the received Resource ADV fields and the measured RTT used for + // flow-control state. + #[allow(clippy::too_many_arguments)] + pub fn from_advertisement( + total_parts: usize, + total_size: usize, + data_size: usize, + random_hash: [u8; RANDOM_HASH_SIZE], + resource_hash: [u8; 32], + flags: ResourceFlags, + map_hashes: Vec<[u8; MAPHASH_LEN]>, + rtt: Duration, + ) -> Result { + let hashmap_height = map_hashes.len(); + let resource = InboundResource::new( + total_parts, + total_size, + data_size, + random_hash, + resource_hash, + flags, + map_hashes, + )?; + + let now = Instant::now(); + Ok(Self { + resource, + parts_since_hmu: 0, + started_at: now, + accepted: true, + rtt, + outstanding_parts: 0, + last_activity: now, + req_sent: None, + req_resp: None, + retries_left: MAX_RETRIES, + waiting_for_hmu: false, + hashmap_height, + part_timeout_factor: PART_TIMEOUT_FACTOR, + rtt_rxd_bytes: 0, + rtt_rxd_bytes_at_part_req: 0, + req_data_rtt_rate: 0.0, + eifr: None, + previous_eifr: None, + }) + } + + /// Seed `previous_eifr` from a prior transfer on the same link. Mirrors + /// Python's `resource.previous_eifr = link.get_last_resource_eifr()` at + /// advertisement time. Higher layers call this once after construction + /// when they know the link's last observed rate. + pub fn seed_previous_eifr(&mut self, bits_per_sec: f64) { + if bits_per_sec > 0.0 { + self.previous_eifr = Some(bits_per_sec); + } + } + + /// Refresh `self.eifr` in bits/sec, preferring the last measured + /// `req_data_rtt_rate` (bytes/sec → bits/sec), falling back to the + /// last `previous_eifr`, and finally to a cold-start estimate + /// `EIFR_COLD_START_BYTES * 8 / rtt`. + pub fn update_eifr(&mut self) { + let rtt_secs = self.rtt.as_secs_f64().max(0.001); + + let rate = if self.req_data_rtt_rate > 0.0 { + self.req_data_rtt_rate * 8.0 + } else if let Some(prev) = self.previous_eifr { + prev + } else { + (EIFR_COLD_START_BYTES as f64 * 8.0) / rtt_secs + }; + + self.eifr = Some(rate); + // Keep `previous_eifr` warm with the most recent non-zero rate so + // a later transfer on the same link can seed from it (Python's + // `link.expected_rate = self.eifr` maps here). + if rate > 0.0 { + self.previous_eifr = Some(rate); + } + } + + /// Accept a data part and decide what to send next. + /// + /// Flow: receive → decrement outstanding → if the window drained → grow + /// the window using the observed byte rate → request the next batch. + /// Completion emits `Complete`; runtimes answer with PROOF/RESOURCE_PRF. + #[tracing::instrument( + level = "trace", + name = "resource.receive_part", + skip_all, + fields( + resource_hash = %hex::encode(&self.resource.resource_hash[..8]), + part_len = data.len(), + ), + )] + pub fn receive_part(&mut self, data: Vec) -> TransferAction { + self.last_activity = Instant::now(); + self.retries_left = MAX_RETRIES; + + // Track cumulative received bytes so update_eifr can compute a + // measured rate over each completed request round. + let payload_len = data.len(); + + // The first reply after a request gives us an RTT sample; once we + // have it we can relax the initial timeout multiplier. + if self.req_resp.is_none() { + self.req_resp = Some(self.last_activity); + if let Some(sent) = self.req_sent { + let rtt = self.last_activity.duration_since(sent); + self.rtt = rtt; + self.part_timeout_factor = PART_TIMEOUT_FACTOR_AFTER_RTT; + } + } + + if self.resource.receive_part(data) { + self.parts_since_hmu += 1; + self.rtt_rxd_bytes = self.rtt_rxd_bytes.saturating_add(payload_len); + + if self.outstanding_parts > 0 { + self.outstanding_parts -= 1; + } + + if self.resource.is_complete() { + self.parts_since_hmu = 0; + return TransferAction::Complete; + } + + if self.outstanding_parts == 0 { + // Window drained — compute req_data_rtt_rate from the byte + // delta since last request, refresh EIFR, then grow the + // window. Mirrors Python Resource.py:896-903. + if let Some(sent_at) = self.req_sent { + let rtt = self.last_activity.duration_since(sent_at).as_secs_f64(); + if rtt > 0.0 { + let req_transferred = self + .rtt_rxd_bytes + .saturating_sub(self.rtt_rxd_bytes_at_part_req); + self.req_data_rtt_rate = req_transferred as f64 / rtt; + self.update_eifr(); + self.rtt_rxd_bytes_at_part_req = self.rtt_rxd_bytes; + } + } + + let elapsed = self.started_at.elapsed().as_secs_f64(); + let received = self.resource.received_count(); + let rate = if elapsed > 0.0 { + (received * SDU) as f64 / elapsed + } else { + 0.0 + }; + self.resource.window.grow(rate as usize); + + return self.request_next(); + } + } + + TransferAction::None + } + + /// Emit a RESOURCE_REQ covering the missing parts in the current window. + /// Called when the window has drained, when the watchdog fires, or after + /// an HMU refreshes the hashmap. See `handle_request` on the sender for + /// the wire layout. + pub fn request_next(&mut self) -> TransferAction { + if self.resource.state == ResourceState::Failed { + return TransferAction::None; + } + + if self.waiting_for_hmu { + return TransferAction::None; + } + + self.outstanding_parts = 0; + let mut hashmap_exhausted = HASHMAP_IS_NOT_EXHAUSTED; + let mut requested_hashes = Vec::new(); + + let search_start = self.resource.consecutive_completed; + let search_size = self.resource.window.window; + let search_end = (search_start + search_size).min(self.resource.total_parts); + + let mut count = 0; + for pn in search_start..search_end { + if self.resource.parts[pn].is_none() { + if pn < self.resource.map_hashes.len() { + requested_hashes.extend_from_slice(&self.resource.map_hashes[pn]); + self.outstanding_parts += 1; + count += 1; + } else { + // We're missing a hash for a part we still need — ask + // the sender for the next hashmap segment. + hashmap_exhausted = HASHMAP_IS_EXHAUSTED; + } + } + + if count >= self.resource.window.window || hashmap_exhausted == HASHMAP_IS_EXHAUSTED { + break; + } + } + + let mut request_data = Vec::new(); + + request_data.push(hashmap_exhausted); + if hashmap_exhausted == HASHMAP_IS_EXHAUSTED { + if self.hashmap_height > 0 { + let last_idx = self.hashmap_height - 1; + if last_idx < self.resource.map_hashes.len() { + request_data.extend_from_slice(&self.resource.map_hashes[last_idx]); + } + } + self.waiting_for_hmu = true; + } + + request_data.extend_from_slice(&self.resource.resource_hash); + request_data.extend_from_slice(&requested_hashes); + + self.last_activity = Instant::now(); + self.req_sent = Some(self.last_activity); + self.req_resp = None; + // Snapshot the byte counter so the next round's completion can + // compute the delta over this window. Python Resource.py:964. + self.rtt_rxd_bytes_at_part_req = self.rtt_rxd_bytes; + + TransferAction::SendRequest(request_data) + } + + /// Receiver-side stall watchdog. Polled by the transfer driver; returns + /// a retry request, a fatal failure, or `None`. + /// + /// Timeout formula (Python `Resource.__watchdog_job`): + /// `part_timeout_factor * expected_tof_remaining` + /// `+ expected_hmu_wait_remaining` + /// `+ RETRY_GRACE_TIME + extra_wait` + /// where + /// `expected_tof_remaining = outstanding_parts * sdu * 8 / eifr` + /// `expected_hmu_wait_remaining = sdu * 8 * HMU_WAIT_FACTOR / eifr` + /// (only when `waiting_for_hmu || outstanding_parts == 0`) + /// `extra_wait = retries_used * PER_RETRY_DELAY` + /// + /// The pre-RTT-sample branch (`req_data_rtt_rate == 0`) uses the + /// cold-start form `part_timeout_factor * (3*sdu / eifr) + grace`, + /// which lengthens the window on slow links where we haven't measured + /// a rate yet. + pub fn check_timeout(&mut self) -> TransferAction { + if self.resource.state != ResourceState::Transferring { + return TransferAction::None; + } + + if self.resource.is_complete() { + return TransferAction::None; + } + + let now = Instant::now(); + let elapsed = now.duration_since(self.last_activity).as_secs_f64(); + + let retries_used = MAX_RETRIES.saturating_sub(self.retries_left); + let extra_wait = retries_used as f64 * PER_RETRY_DELAY; + + self.update_eifr(); + // update_eifr always assigns Some(_) as long as rtt_secs > 0; a + // pathological zero-rtt would leave it None. Fall back to a + // 1 bps floor so the arithmetic below cannot divide by zero. + let eifr = self.eifr.unwrap_or(1.0).max(1.0); + let sdu_f = self.resource.sdu as f64; + + let expected_hmu_wait_remaining = if self.waiting_for_hmu || self.outstanding_parts == 0 { + (sdu_f * 8.0 * HMU_WAIT_FACTOR) / eifr + } else { + 0.0 + }; + let expected_tof_remaining = (self.outstanding_parts as f64 * sdu_f * 8.0) / eifr; + + let timeout = if self.req_data_rtt_rate > 0.0 { + self.part_timeout_factor * expected_tof_remaining + + expected_hmu_wait_remaining + + RETRY_GRACE_TIME + + extra_wait + } else { + // Pre-sample: mirror Python's 604 — `3*sdu / eifr` is the + // envelope for the next three parts to arrive at the cold- + // start rate, scaled by the same timeout factor. + self.part_timeout_factor * ((3.0 * sdu_f) / eifr) + RETRY_GRACE_TIME + extra_wait + }; + + if elapsed > timeout { + if self.retries_left > 0 { + self.resource.window.shrink(); + self.retries_left -= 1; + self.waiting_for_hmu = false; + return self.request_next(); + } else { + self.resource.state = ResourceState::Failed; + return TransferAction::Failed("resource transfer timed out".to_string()); + } + } + + TransferAction::None + } + + /// Merge a hashmap-update segment from the sender into our local + /// map_hashes and immediately request the parts it unlocks. + /// + /// Wire layout: + /// resource_hash(32) || msgpack([segment_index, hashmap_bytes]) + pub fn hashmap_update(&mut self, segment: usize, hashmap_data: &[u8]) -> TransferAction { + if self.resource.state == ResourceState::Failed { + return TransferAction::None; + } + + 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 + let hashes_count = hashmap_data.len() / MAPHASH_LEN; + for i in 0..hashes_count { + let idx = i + segment * hashmap_max_len; + let start = i * MAPHASH_LEN; + let end = start + MAPHASH_LEN; + if end <= hashmap_data.len() { + let mut mh = [0u8; MAPHASH_LEN]; + mh.copy_from_slice(&hashmap_data[start..end]); + + // Extend the map_hashes vector if needed + while self.resource.map_hashes.len() <= idx { + self.resource.map_hashes.push([0u8; MAPHASH_LEN]); + } + + // Only increment hashmap_height if this is a new hash + if self.resource.map_hashes[idx] == [0u8; MAPHASH_LEN] { + self.hashmap_height += 1; + } + self.resource.map_hashes[idx] = mh; + } + } + + self.waiting_for_hmu = false; + + // Now request the next batch of parts using the updated hashmap + self.request_next() + } + + /// Encode the receiver-side HMU frame. See `handle_hmu` on the sender for + /// the wire layout. + pub fn create_hmu(&self) -> Vec { + let is_complete = self.resource.is_complete(); + let exhausted = if is_complete { + HASHMAP_IS_EXHAUSTED + } else { + HASHMAP_IS_NOT_EXHAUSTED + }; + + let mut hmu = Vec::new(); + hmu.push(exhausted); + + // If exhausted (complete), include the last map hash + if is_complete && let Some(last_mh) = self.resource.map_hashes.last() { + hmu.extend_from_slice(last_mh); + } + + // Include the resource hash for identification + hmu.extend_from_slice(&self.resource.resource_hash); + + // Include hashes of parts we still NEED (not received) + if !is_complete { + let search_start = self.resource.consecutive_completed; + let search_end = + (search_start + self.resource.window.window).min(self.resource.total_parts); + + for i in search_start..search_end { + if i < self.resource.map_hashes.len() && self.resource.parts[i].is_none() { + hmu.extend_from_slice(&self.resource.map_hashes[i]); + } + } + } + + hmu + } + + /// Assemble the received data and generate proof. + /// Returns (assembled_data, proof_data) on success. + /// An optional `decrypt_fn` is passed through to `InboundResource::assemble()`. + /// + /// The proof is computed over the full decompressed blob (metadata + /// header + payload) to match Python Resource.py:744, where + /// `self.data` still holds the metadata-inclusive bytes when + /// `prove()` runs. `assemble()` strips metadata from the value it + /// returns to callers, so we reconstruct the pre-strip bytes here + /// before hashing. + pub fn complete( + &mut self, + decrypt_fn: Option<&ResourceDecryptor<'_>>, + ) -> Result<(Vec, Vec), ResourceError> { + let data = self.resource.assemble(decrypt_fn)?; + let proof_input: Vec = if self.resource.flags.has_metadata { + if let Some(ref meta) = self.resource.metadata { + let mut full = Vec::with_capacity(3 + meta.len() + data.len()); + let len = meta.len(); + full.push(((len >> 16) & 0xFF) as u8); + full.push(((len >> 8) & 0xFF) as u8); + full.push((len & 0xFF) as u8); + full.extend_from_slice(meta); + full.extend_from_slice(&data); + full + } else { + data.clone() + } + } else { + data.clone() + }; + let proof = self.resource.generate_proof(&proof_input); + Ok((data, proof)) + } + + /// Handle a cancel message from the sender. + pub fn handle_cancel(&mut self) { + self.resource.state = ResourceState::Failed; + } + + /// Create a receiver cancel message. + pub fn cancel(&mut self) -> TransferAction { + self.resource.state = ResourceState::Failed; + TransferAction::SendCancel(CancelType::Rcl, self.resource.resource_hash) + } + + /// Progress as fraction. + pub fn progress(&self) -> f64 { + self.resource.progress() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_resource_flags_roundtrip() { + let flags = ResourceFlags { + encrypted: true, + compressed: true, + split: false, + is_request: true, + is_response: false, + has_metadata: true, + }; + let byte = flags.to_byte(); + let flags2 = ResourceFlags::from_byte(byte); + assert_eq!(flags.encrypted, flags2.encrypted); + assert_eq!(flags.compressed, flags2.compressed); + assert_eq!(flags.split, flags2.split); + assert_eq!(flags.is_request, flags2.is_request); + assert_eq!(flags.is_response, flags2.is_response); + assert_eq!(flags.has_metadata, flags2.has_metadata); + } + + #[test] + fn test_rejected_distinct_from_none() { + // Rejected and None must have distinct wire tags. + assert_ne!(ResourceState::Rejected as u8, ResourceState::None as u8); + } + + #[test] + fn test_map_hash() { + let data = b"test part data"; + let random = [0xAA, 0xBB, 0xCC, 0xDD]; + let mh = get_map_hash(data, &random); + assert_eq!(mh.len(), MAPHASH_LEN); + + // Same input produces same hash + let mh2 = get_map_hash(data, &random); + assert_eq!(mh, mh2); + + // Different data produces different hash + let mh3 = get_map_hash(b"different data", &random); + assert_ne!(mh, mh3); + } + + #[test] + fn test_resource_hash_and_proof() { + let data = b"resource data for hashing"; + let random = [0x01, 0x02, 0x03, 0x04]; + + let rh = compute_resource_hash(data, &random); + let proof = compute_expected_proof(data, &rh); + + // Proof should be deterministic + let proof2 = compute_expected_proof(data, &rh); + assert_eq!(proof, proof2); + + // Different data = different proof + let rh2 = compute_resource_hash(b"other", &random); + let proof3 = compute_expected_proof(b"other", &rh2); + assert_ne!(proof, proof3); + } + + #[test] + fn test_outbound_resource_creation() { + let data = b"Hello, this is a test resource!".to_vec(); + let resource = OutboundResource::new(data.clone(), false, None).unwrap(); + + assert_eq!(resource.state, ResourceState::None); + assert!(!resource.parts.is_empty()); + assert_eq!(resource.map_hashes.len(), resource.parts.len()); + assert_eq!(resource.total_segments, 1); + } + + #[test] + fn test_outbound_too_large() { + let data = vec![0u8; MAX_EFFICIENT_SIZE + 1]; + assert!(OutboundResource::new(data, false, None).is_err()); + } + + #[test] + fn test_inbound_receive_and_assemble() { + // Create outbound resource + let data = b"Test data for transfer!".to_vec(); + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + + // Create inbound resource from the outbound's metadata + let mut inbound = InboundResource::new( + outbound.num_parts(), + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + outbound.map_hashes.clone(), + ) + .unwrap(); + + // Feed parts + for part in &outbound.parts { + assert!(inbound.receive_part(part.clone())); + } + + assert!(inbound.is_complete()); + + // Assemble + let assembled = inbound.assemble(None).unwrap(); + assert_eq!(assembled, data); + } + + /// Parts arriving out-of-order must still reassemble correctly as long + /// as they fall inside the receive window. Exercises the search loop in + /// `receive_part` slotting by map-hash match rather than positional + /// order. This is the normal case for a reliable network that can + /// reorder — we should never require strictly sequential delivery. + #[test] + fn test_inbound_out_of_order_parts_assemble() { + // 1.2 KiB -> 3 parts (all inside the initial WINDOW_INITIAL=4 window). + let data: Vec = (0..1200).map(|i| (i % 251) as u8).collect(); + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + assert_eq!(outbound.num_parts(), 3, "test needs exactly 3 parts"); + + let mut inbound = InboundResource::new( + outbound.num_parts(), + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + outbound.map_hashes.clone(), + ) + .unwrap(); + + // Deliver 2, 0, 1 — all indices inside the initial window, + // none in positional order. + for idx in [2usize, 0, 1] { + assert!( + inbound.receive_part(outbound.parts[idx].clone()), + "out-of-order part {idx} should be accepted inside window" + ); + } + + assert!(inbound.is_complete()); + let assembled = inbound.assemble(None).unwrap(); + assert_eq!(assembled, data, "reassembled data matches despite reorder"); + } + + /// A duplicate delivery of a part already accepted must be a no-op + /// (returns false) and must not corrupt the partially-built buffer. + /// Catches the replay/retransmit class that can occur when ACKs are + /// lost and the sender resends. + #[test] + fn test_inbound_duplicate_part_is_noop() { + let data = b"duplicate probe".to_vec(); + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + let mut inbound = InboundResource::new( + outbound.num_parts(), + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + outbound.map_hashes.clone(), + ) + .unwrap(); + + let first_part = outbound.parts[0].clone(); + assert!(inbound.receive_part(first_part.clone()), "first delivery"); + assert!( + !inbound.receive_part(first_part.clone()), + "duplicate must be rejected" + ); + + // Remaining parts still accept normally, and the final buffer is correct. + for part in &outbound.parts[1..] { + assert!(inbound.receive_part(part.clone())); + } + assert!(inbound.is_complete()); + assert_eq!(inbound.assemble(None).unwrap(), data); + } + + #[test] + fn test_proof_validation() { + let data = b"Proof test data".to_vec(); + let mut outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + outbound.state = ResourceState::AwaitingProof; + + // Simulate receiver generating proof + let inbound = InboundResource::new( + outbound.num_parts(), + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags::default(), + outbound.map_hashes.clone(), + ) + .unwrap(); + + let proof_data = inbound.generate_proof(&data); + assert!(outbound.validate_proof(&proof_data)); + assert_eq!(outbound.state, ResourceState::Complete); + } + + #[test] + fn test_window_grow_shrink() { + let mut ws = WindowState::new(); + let initial = ws.window; + + ws.grow(RATE_FAST + 1); + assert_eq!(ws.window, initial + 1); + + ws.shrink(); + assert_eq!(ws.window, initial); + } + + #[test] + fn test_progress() { + let inbound = InboundResource::new( + 10, + 1000, + 1000, + [0; 4], + [0; 32], + ResourceFlags::default(), + vec![[0; 4]; 10], + ) + .unwrap(); + + assert_eq!(inbound.progress(), 0.0); + } + + #[test] + fn test_metadata_roundtrip() { + // Metadata must survive a pack → transmit → assemble cycle. + let data = b"Resource payload data".to_vec(); + let metadata = b"some metadata content".to_vec(); + + let outbound = + OutboundResource::with_options(data.clone(), false, Some(metadata.clone()), None, None) + .unwrap(); + + assert!(outbound.flags.has_metadata); + assert!(outbound.metadata.is_some()); + assert_eq!(outbound.metadata_size, 3 + metadata.len()); + + let mut inbound = InboundResource::new( + outbound.num_parts(), + outbound.total_size, + data.len() + outbound.metadata_size, + outbound.random_hash, + outbound.resource_hash, + outbound.flags, + outbound.map_hashes.clone(), + ) + .unwrap(); + + for part in &outbound.parts { + assert!(inbound.receive_part(part.clone())); + } + + assert!(inbound.is_complete()); + + let assembled_data = inbound.assemble(None).unwrap(); + assert_eq!(assembled_data, data); + assert!(inbound.metadata.is_some()); + assert_eq!(inbound.metadata.unwrap(), metadata); + } + + #[test] + fn test_metadata_too_large() { + let data = b"small".to_vec(); + let metadata = vec![0u8; METADATA_MAX_SIZE + 1]; + let result = OutboundResource::with_options(data, false, Some(metadata), None, None); + assert!(matches!(result, Err(ResourceError::MetadataTooLarge))); + } + + #[test] + fn test_no_metadata_flag_unset() { + let outbound = OutboundResource::new(b"test".to_vec(), false, None).unwrap(); + assert!(!outbound.flags.has_metadata); + assert!(outbound.metadata.is_none()); + assert_eq!(outbound.metadata_size, 0); + } + + #[test] + fn test_custom_sdu() { + let data = vec![0u8; 500]; + let custom_sdu = 100; + let outbound = + OutboundResource::with_options(data.clone(), false, None, Some(custom_sdu), None) + .unwrap(); + + assert_eq!(outbound.sdu, custom_sdu); + // 500B data + 4B random hash at SDU=100 -> at least 5 parts. + assert!(outbound.num_parts() >= 5); + + // Every non-final part must be packed to the full SDU. + for (i, part) in outbound.parts.iter().enumerate() { + if i < outbound.parts.len() - 1 { + assert_eq!(part.len(), custom_sdu); + } + } + } + + #[test] + fn test_window_grow_before_send_order() { + // The window must be grown before the next request batch is sized, so + // the extra slot is visible in the batch that actually uses it. + let mut ws = WindowState::new(); + let initial_window = ws.window; + + ws.grow(RATE_FAST + 1); + assert_eq!(ws.window, initial_window + 1); + + let request_window = ws.window; + assert_eq!(request_window, initial_window + 1); + } + + #[test] + fn test_window_min_adjusts_with_flexibility() { + let mut ws = WindowState::new(); + let initial_min = ws.window_min; + + for _ in 0..(WINDOW_FLEXIBILITY + 2) { + ws.window_max = WINDOW_MAX_FAST; + ws.grow(RATE_FAST + 1); + } + + // Once the window outgrows its flexibility band, `window_min` slides up. + assert!(ws.window_min > initial_min); + } + + #[test] + fn test_link_resource_outbound_creation() { + let link_id = [0xAA; 16]; + let data = b"Hello, LinkResource!".to_vec(); + let lr = LinkResource::new_outbound(link_id, data, false).unwrap(); + + assert_eq!(lr.link_id, link_id); + assert!(lr.outbound.is_some()); + assert!(lr.inbound.is_none()); + assert!(lr.num_parts() > 0); + } + + #[test] + fn test_link_resource_outbound_parts() { + let link_id = [0xBB; 16]; + let data = b"Part iteration test data".to_vec(); + let lr = LinkResource::new_outbound(link_id, data, false).unwrap(); + + // Should be able to get part 0 + let part = lr.next_part(0); + assert!(part.is_some()); + + // Out-of-bounds should return None + let none_part = lr.next_part(9999); + assert!(none_part.is_none()); + } + + #[test] + fn test_link_resource_outbound_too_large() { + let link_id = [0xCC; 16]; + let data = vec![0u8; MAX_EFFICIENT_SIZE + 1]; + let result = LinkResource::new_outbound(link_id, data, false); + assert!(result.is_err()); + } + + #[test] + fn test_link_resource_inbound_transfer() { + let link_id = [0xDD; 16]; + let data = b"Transfer test data".to_vec(); + + // Create outbound to get the metadata + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + + // Create inbound LinkResource from outbound metadata + let mut lr = LinkResource::new_inbound( + link_id, + outbound.num_parts(), + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + outbound.map_hashes.clone(), + ) + .unwrap(); + + assert!(!lr.is_complete()); + assert_eq!(lr.progress(), 0.0); + + // Feed all parts + for part in &outbound.parts { + assert!(lr.receive_part(part.clone())); + } + + assert!(lr.is_complete()); + + // Assemble + let assembled = lr.assemble().unwrap(); + assert_eq!(assembled, data); + } + + #[test] + fn test_link_resource_progress() { + let link_id = [0xEE; 16]; + let lr_out = LinkResource::new_outbound(link_id, b"test".to_vec(), false).unwrap(); + // Outbound progress is 0.0 (not tracked the same way) + assert_eq!(lr_out.progress(), 0.0); + } + + #[test] + fn test_link_resource_receive_part_no_inbound() { + let link_id = [0xFF; 16]; + let mut lr = LinkResource::new_outbound(link_id, b"data".to_vec(), false).unwrap(); + // Receiving a part on an outbound-only resource should return false + assert!(!lr.receive_part(vec![1, 2, 3])); + } + + #[test] + fn test_outbound_transfer_creation() { + let transfer = OutboundTransfer::new( + b"test transfer data".to_vec(), + false, + Duration::from_millis(100), + ) + .unwrap(); + + assert!(!transfer.advertised); + assert_eq!(transfer.cursor, 0); + assert_eq!(transfer.retries, 0); + assert_eq!(transfer.resource.state, ResourceState::None); + } + + #[test] + fn test_outbound_transfer_advertise_then_send() { + let mut transfer = OutboundTransfer::new( + b"hello transfer".to_vec(), + false, + Duration::from_millis(100), + ) + .unwrap(); + + // First tick should send advertisement + let action = transfer.tick(); + assert!(matches!(action, TransferAction::SendAdvertisement(_))); + assert!(transfer.advertised); + + // Subsequent ticks should send parts + let action = transfer.tick(); + assert!(matches!(action, TransferAction::SendPart(0, _))); + } + + #[test] + fn test_outbound_transfer_hmu_handling() { + let data = b"small data".to_vec(); + let mut transfer = + OutboundTransfer::new(data.clone(), false, Duration::from_millis(100)).unwrap(); + + // Send advertisement + transfer.tick(); + + // Collect all parts sent + let num_parts = transfer.resource.num_parts(); + for _ in 0..num_parts { + transfer.tick(); + } + + // Wire format: exhausted_flag(1) + last_map_hash(4) + resource_hash(32). + let mut hmu = vec![HASHMAP_IS_EXHAUSTED]; + if let Some(last_mh) = transfer.resource.map_hashes.last() { + hmu.extend_from_slice(last_mh); + } + hmu.extend_from_slice(&transfer.resource.resource_hash); + transfer.handle_hmu(&hmu); + + assert!(transfer.all_confirmed()); + } + + #[test] + fn test_inbound_transfer_receive_and_complete() { + let data = b"test data for inbound transfer".to_vec(); + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Feed all parts + for part in &outbound.parts { + inbound.receive_part(part.clone()); + } + + assert!(inbound.resource.is_complete()); + + // Complete and verify + let (assembled, proof) = inbound.complete(None).unwrap(); + assert_eq!(assembled, data); + assert_eq!(proof.len(), 64); // resource_hash(32) + expected_proof(32) + } + + #[test] + fn test_inbound_transfer_hmu_generation() { + let data = vec![0u8; 2000]; // Multiple parts + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + assert!(outbound.num_parts() > 1); + + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Feed parts and check that completion does not emit a final HMU. + for part in &outbound.parts { + let action = inbound.receive_part(part.clone()); + if inbound.resource.is_complete() { + assert!(matches!(action, TransferAction::Complete)); + } + } + + assert!(inbound.resource.is_complete()); + } + + #[test] + fn test_transfer_cancel() { + let mut transfer = + OutboundTransfer::new(b"data".to_vec(), false, Duration::from_millis(100)).unwrap(); + + transfer.handle_cancel(); + assert_eq!(transfer.resource.state, ResourceState::Failed); + } + + #[test] + fn test_inbound_cancel() { + let outbound = OutboundResource::new(b"data".to_vec(), false, None).unwrap(); + let mut inbound = InboundTransfer::from_advertisement( + outbound.num_parts(), + outbound.total_size, + 4, + outbound.random_hash, + outbound.resource_hash, + ResourceFlags::default(), + outbound.map_hashes.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + let action = inbound.cancel(); + assert!(matches!( + action, + TransferAction::SendCancel(CancelType::Rcl, rh) if rh == outbound.resource_hash + )); + assert_eq!(inbound.resource.state, ResourceState::Failed); + } + + #[test] + fn test_transfer_progress() { + let transfer = + OutboundTransfer::new(b"data".to_vec(), false, Duration::from_millis(100)).unwrap(); + assert_eq!(transfer.progress(), 0.0); + } + + #[test] + fn test_full_transfer_roundtrip() { + // Simulate a complete transfer: sender → receiver + let data = b"Full transfer test with enough data to exercise the engine.".to_vec(); + + let mut sender = + OutboundTransfer::new(data.clone(), false, Duration::from_millis(50)).unwrap(); + + // Step 1: Sender advertises + let adv_action = sender.tick(); + assert!(matches!(adv_action, TransferAction::SendAdvertisement(_))); + + // Step 2: Receiver accepts advertisement + let mut receiver = InboundTransfer::from_advertisement( + sender.resource.num_parts(), + sender.resource.total_size, + data.len(), + sender.resource.random_hash, + sender.resource.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + sender.resource.map_hashes.clone(), + Duration::from_millis(50), + ) + .unwrap(); + + // Step 3: Sender sends parts, receiver receives them + let num_parts = sender.resource.num_parts(); + for _ in 0..num_parts { + let action = sender.tick(); + if let TransferAction::SendPart(_idx, part_data) = action { + let recv_action = receiver.receive_part(part_data); + + // If receiver sends HMU, sender processes it + if let TransferAction::SendHmu(hmu) = recv_action { + sender.handle_hmu(&hmu); + } + } + } + + // Step 4: Receiver completes and sends proof + assert!(receiver.resource.is_complete()); + let (assembled, proof) = receiver.complete(None).unwrap(); + assert_eq!(assembled, data); + + // Step 5: Sender validates proof + assert!(sender.handle_proof(&proof)); + assert_eq!(sender.resource.state, ResourceState::Complete); + } + + /// Helper: run a full sender→receiver transfer for the given data and verify integrity. + fn run_transfer_roundtrip(data: Vec) { + let data_len = data.len(); + let mut sender = + OutboundTransfer::new(data.clone(), true, Duration::from_millis(50)).unwrap(); + + // Advertise + let action = sender.tick(); + assert!(matches!(action, TransferAction::SendAdvertisement(_))); + + // Create receiver + let mut receiver = InboundTransfer::from_advertisement( + sender.resource.num_parts(), + sender.resource.total_size, + data_len, + sender.resource.random_hash, + sender.resource.resource_hash, + ResourceFlags { + compressed: sender.resource.flags.compressed, + ..Default::default() + }, + sender.resource.map_hashes.clone(), + Duration::from_millis(50), + ) + .unwrap(); + + // Transfer loop: send parts, handle HMUs + let mut iterations = 0; + let max_iterations = sender.resource.num_parts() * 3 + 10; + while !receiver.resource.is_complete() && iterations < max_iterations { + let action = sender.tick(); + match action { + TransferAction::SendPart(_idx, part_data) => { + let recv_action = receiver.receive_part(part_data); + if let TransferAction::SendHmu(hmu) = recv_action { + sender.handle_hmu(&hmu); + } + } + // Sender is waiting for HMU; generate one if receiver has progress. + TransferAction::None if receiver.resource.consecutive_completed > 0 => { + let hmu = receiver.create_hmu(); + sender.handle_hmu(&hmu); + } + _ => {} + } + iterations += 1; + } + + assert!( + receiver.resource.is_complete(), + "transfer incomplete after {} iterations ({} of {} parts received for {} byte payload)", + iterations, + receiver.resource.received_count(), + receiver.resource.total_parts, + data_len, + ); + + // Assemble and verify + let (assembled, proof) = receiver.complete(None).unwrap(); + assert_eq!(assembled.len(), data_len); + assert_eq!(assembled, data); + + // Validate proof + assert!(sender.handle_proof(&proof)); + assert_eq!(sender.resource.state, ResourceState::Complete); + } + + #[test] + fn test_transfer_size_class_01_tiny() { + // 1 byte — single part, minimal resource + run_transfer_roundtrip(vec![0x42]); + } + + #[test] + fn test_transfer_size_class_02_small() { + // 256 bytes — still single part + run_transfer_roundtrip(vec![0xAB; 256]); + } + + #[test] + fn test_transfer_size_class_03_medium() { + // 1 KB — likely 2-3 parts + run_transfer_roundtrip(vec![0xCD; 1024]); + } + + #[test] + fn test_transfer_size_class_04_large() { + // 10 KB — many parts, exercises windowing + run_transfer_roundtrip(vec![0xEF; 10 * 1024]); + } + + #[test] + fn test_transfer_size_class_05_multi_part() { + // 100 KB — heavy multi-part transfer + run_transfer_roundtrip(vec![0x77; 100 * 1024]); + } + + #[test] + fn test_transfer_size_class_06_half_max() { + // 512 KB + run_transfer_roundtrip(vec![0x99; 512 * 1024]); + } + + #[test] + fn test_transfer_size_class_07_near_max() { + // 1 MB - 1 = MAX_EFFICIENT_SIZE + run_transfer_roundtrip(vec![0xBB; MAX_EFFICIENT_SIZE]); + } + + #[test] + fn test_transfer_over_max_rejected() { + // MAX_EFFICIENT_SIZE + 1 should fail + let result = OutboundTransfer::new( + vec![0; MAX_EFFICIENT_SIZE + 1], + false, + Duration::from_millis(50), + ); + assert!(result.is_err()); + } + + #[test] + fn test_transfer_with_compression() { + // Highly compressible data should compress well + let data = vec![0x00; 10_000]; + let mut sender = + OutboundTransfer::new(data.clone(), true, Duration::from_millis(50)).unwrap(); + // Compressed size should be smaller than original + assert!(sender.resource.total_size < data.len() + RANDOM_HASH_SIZE + 100); + + // Still verify the full roundtrip works + sender.tick(); // advertise + let mut receiver = InboundTransfer::from_advertisement( + sender.resource.num_parts(), + sender.resource.total_size, + data.len(), + sender.resource.random_hash, + sender.resource.resource_hash, + ResourceFlags { + compressed: sender.resource.flags.compressed, + ..Default::default() + }, + sender.resource.map_hashes.clone(), + Duration::from_millis(50), + ) + .unwrap(); + + for part in &sender.resource.parts { + receiver.receive_part(part.clone()); + } + assert!(receiver.resource.is_complete()); + let (assembled, _proof) = receiver.complete(None).unwrap(); + assert_eq!(assembled, data); + } + + #[test] + fn test_transfer_random_data_integrity() { + // Random data that won't compress — tests raw transfer integrity + let data: Vec = rns_crypto::random::random_bytes(5000); + run_transfer_roundtrip(data); + } + + #[test] + fn test_outbound_resource_handle_cancel() { + let data = b"cancel test data".to_vec(); + let mut resource = OutboundResource::new(data, false, None).unwrap(); + assert_ne!(resource.state, ResourceState::Rejected); + resource.handle_cancel(); + assert_eq!(resource.state, ResourceState::Rejected); + } + + #[test] + fn test_inbound_resource_handle_cancel() { + let data = b"cancel inbound test".to_vec(); + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + let mut inbound = InboundResource::new( + outbound.num_parts(), + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags::default(), + outbound.map_hashes.clone(), + ) + .unwrap(); + assert_ne!(inbound.state, ResourceState::Failed); + inbound.handle_cancel(); + assert_eq!(inbound.state, ResourceState::Failed); + } + + #[test] + fn test_outbound_resource_handle_hmu_empty() { + let data = b"hmu test".to_vec(); + let mut resource = OutboundResource::new(data, false, None).unwrap(); + let result = resource.handle_hmu(&[]); + assert!(result.is_empty()); + } + + #[test] + fn test_outbound_resource_handle_hmu_exhausted() { + let data = b"hmu exhausted test".to_vec(); + let mut resource = OutboundResource::new(data, false, None).unwrap(); + resource.state = ResourceState::Transferring; + let result = resource.handle_hmu(&[HASHMAP_IS_EXHAUSTED]); + assert!(result.is_empty()); + assert_eq!(resource.state, ResourceState::AwaitingProof); + } + + #[test] + fn test_multi_segment_outbound_splits_data() { + let data = vec![0xAB; MAX_EFFICIENT_SIZE + 1000]; + let multi = MultiSegmentOutbound::new(data.clone(), false).unwrap(); + + assert_eq!(multi.total_segments, 2); + assert_eq!(multi.num_segments(), 2); + assert_eq!(multi.data_size, data.len()); + assert!(!multi.is_complete()); + + // Verify segment flags + for (i, seg) in multi.segments.iter().enumerate() { + assert!(seg.flags.split); + assert_eq!(seg.segment_index, i + 1); + assert_eq!(seg.total_segments, 2); + } + + // First segment should have MAX_EFFICIENT_SIZE bytes + assert_eq!(multi.segments[0].data.len(), MAX_EFFICIENT_SIZE); + // Second segment has the remainder + assert_eq!(multi.segments[1].data.len(), 1000); + } + + #[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_cancel_all_fans_out() { + // Python parity: head-cancel must tear down every follow-on segment. + // We use a 3-segment resource and verify all transition to Failed. + let data = vec![0x42; MAX_EFFICIENT_SIZE * 2 + 500]; + let mut multi = MultiSegmentOutbound::new(data, false).unwrap(); + assert_eq!(multi.num_segments(), 3); + + let cancelled = multi.cancel_all(); + assert_eq!(cancelled, 3, "all three segments should be cancelled"); + for seg in &multi.segments { + assert_eq!(seg.state, ResourceState::Failed); + } + + // Idempotent: a second cancel returns 0 since all are already Failed. + let cancelled_again = multi.cancel_all(); + assert_eq!( + cancelled_again, 0, + "already-failed segments must not be re-counted" + ); + } + + #[test] + fn test_multi_segment_cancel_all_skips_complete() { + // A segment already marked Complete must not be flipped to Failed — + // cancellation only tears down still-active transfers. + let data = vec![0x33; MAX_EFFICIENT_SIZE + 200]; + let mut multi = MultiSegmentOutbound::new(data, false).unwrap(); + multi.segments[0].state = ResourceState::Complete; + + let cancelled = multi.cancel_all(); + assert_eq!(cancelled, 1, "only the active segment should be cancelled"); + assert_eq!(multi.segments[0].state, ResourceState::Complete); + assert_eq!(multi.segments[1].state, ResourceState::Failed); + } + + #[test] + fn test_multi_segment_outbound_single_exact() { + // Data exactly at MAX_EFFICIENT_SIZE should be one segment + let data = vec![0xCD; MAX_EFFICIENT_SIZE]; + let multi = MultiSegmentOutbound::new(data, false).unwrap(); + assert_eq!(multi.total_segments, 1); + assert_eq!(multi.num_segments(), 1); + assert!(multi.segments[0].flags.split); + } + + #[test] + fn test_multi_segment_inbound_reassembly() { + // Simulate: outbound splits into 2 segments, inbound reassembles + let seg1_data = vec![0xAA; 100]; + let seg2_data = vec![0xBB; 50]; + + let original_hash = [0x11; 32]; + let mut inbound = MultiSegmentInbound::new(2, original_hash); + + assert_eq!(inbound.total_segments, 2); + assert!(!inbound.is_complete()); + assert_eq!(inbound.assembled_count(), 0); + + // Create outbound resources for each segment to get proper inbound metadata + let out1 = OutboundResource::new(seg1_data.clone(), false, None).unwrap(); + let in1 = InboundResource::new( + out1.num_parts(), + out1.total_size, + seg1_data.len(), + out1.random_hash, + out1.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + out1.map_hashes.clone(), + ) + .unwrap(); + inbound.set_segment(1, in1); + + let out2 = OutboundResource::new(seg2_data.clone(), false, None).unwrap(); + let in2 = InboundResource::new( + out2.num_parts(), + out2.total_size, + seg2_data.len(), + out2.random_hash, + out2.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + out2.map_hashes.clone(), + ) + .unwrap(); + inbound.set_segment(2, in2); + + // Feed parts to segment 1 + for part in &out1.parts { + inbound.segments[0] + .as_mut() + .unwrap() + .receive_part(part.clone()); + } + inbound.assemble_segment(1, None).unwrap(); + assert_eq!(inbound.assembled_count(), 1); + + // Feed parts to segment 2 + for part in &out2.parts { + inbound.segments[1] + .as_mut() + .unwrap() + .receive_part(part.clone()); + } + inbound.assemble_segment(2, None).unwrap(); + assert_eq!(inbound.assembled_count(), 2); + + // Reassemble + assert!(inbound.is_complete()); + let result = inbound.reassemble().unwrap(); + assert_eq!(&result[..100], &seg1_data[..]); + assert_eq!(&result[100..], &seg2_data[..]); + } + + #[test] + fn test_multi_segment_inbound_progress() { + let inbound = MultiSegmentInbound::new(4, [0; 32]); + assert_eq!(inbound.progress(), 0.0); + assert_eq!(inbound.assembled_count(), 0); + } + + #[test] + fn test_multi_segment_inbound_incomplete_reassembly() { + let inbound = MultiSegmentInbound::new(2, [0; 32]); + assert!(inbound.reassemble().is_err()); + } + + /// Runtime ingest path: feed assembled bytes directly via + /// `set_segment_data` and verify reassembly + reported `data_size`. + #[test] + fn test_multi_segment_set_segment_data_in_order() { + let mut inbound = MultiSegmentInbound::new(3, [0xAB; 32]); + assert_eq!(inbound.assembled_count(), 0); + + inbound.set_segment_data(1, vec![1u8; 10]).unwrap(); + inbound.set_segment_data(2, vec![2u8; 20]).unwrap(); + assert!(!inbound.is_complete()); + assert_eq!(inbound.assembled_count(), 2); + + inbound.set_segment_data(3, vec![3u8; 30]).unwrap(); + assert!(inbound.is_complete()); + assert_eq!(inbound.data_size, 60); + + let blob = inbound.reassemble().unwrap(); + assert_eq!(blob.len(), 60); + assert_eq!(&blob[..10], &[1u8; 10]); + assert_eq!(&blob[10..30], &[2u8; 20]); + assert_eq!(&blob[30..], &[3u8; 30]); + } + + /// Out-of-order ingest: segment 3 arrives before segment 1. Reassembly + /// must still produce the canonical ordering. + #[test] + fn test_multi_segment_set_segment_data_out_of_order() { + let mut inbound = MultiSegmentInbound::new(3, [0; 32]); + inbound.set_segment_data(3, vec![0xCC; 5]).unwrap(); + inbound.set_segment_data(1, vec![0xAA; 5]).unwrap(); + inbound.set_segment_data(2, vec![0xBB; 5]).unwrap(); + + let blob = inbound.reassemble().unwrap(); + assert_eq!( + &blob, + &[ + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xCC, 0xCC, 0xCC, 0xCC, + 0xCC + ] + ); + } + + /// Sender retransmit (or any duplicate ADV) must not silently overwrite + /// an already-accepted slot — surfaces as `DuplicateSegment` so the + /// runtime can log + ignore. + #[test] + fn test_multi_segment_set_segment_data_rejects_duplicate() { + let mut inbound = MultiSegmentInbound::new(2, [0; 32]); + inbound.set_segment_data(1, vec![0xAA; 4]).unwrap(); + let err = inbound.set_segment_data(1, vec![0xBB; 4]).unwrap_err(); + assert!(matches!(err, ResourceError::DuplicateSegment)); + // Original bytes must survive the rejection. + inbound.set_segment_data(2, vec![0xCC; 4]).unwrap(); + let blob = inbound.reassemble().unwrap(); + assert_eq!(&blob[..4], &[0xAA; 4]); + assert_eq!(&blob[4..], &[0xCC; 4]); + } + + /// Out-of-range indices (`0` and `> total_segments`) must surface as + /// `InvalidAdvertisement`, distinct from the duplicate path. + #[test] + fn test_multi_segment_set_segment_data_rejects_out_of_range() { + let mut inbound = MultiSegmentInbound::new(2, [0; 32]); + let err_zero = inbound.set_segment_data(0, vec![0; 1]).unwrap_err(); + let err_over = inbound.set_segment_data(3, vec![0; 1]).unwrap_err(); + assert!(matches!(err_zero, ResourceError::InvalidAdvertisement)); + assert!(matches!(err_over, ResourceError::InvalidAdvertisement)); + } + + /// `set_metadata` is first-non-None-wins: subsequent calls must not + /// overwrite metadata already recorded. + #[test] + fn test_multi_segment_set_metadata_first_wins() { + let mut inbound = MultiSegmentInbound::new(2, [0; 32]); + assert!(inbound.metadata.is_none()); + inbound.set_metadata(b"first".to_vec()); + inbound.set_metadata(b"second".to_vec()); + assert_eq!(inbound.metadata.as_deref(), Some(&b"first"[..])); + } + + /// Regression: the receiver's `total_size` cap previously rejected any + /// max-plaintext resource (`MAX_EFFICIENT_SIZE`) once link-encrypted, + /// because it didn't account for `random_hash + IV + HMAC + PKCS7 pad` + /// overhead on top of the plaintext. After the fix the receiver must + /// accept the worst-case encrypted blob built around a max-plaintext + /// payload. This is what made multi-segment transfers unrecievable in + /// practice — every chunk hits the post-encryption ceiling. + #[test] + fn test_inbound_resource_accepts_max_plaintext_encrypted_size() { + const MAX_AES_BLOCK_PAD: usize = 16; + let worst_case = + MAX_EFFICIENT_SIZE + RANDOM_HASH_SIZE + rns_crypto::TOKEN_OVERHEAD + MAX_AES_BLOCK_PAD; + + let map_hashes = vec![[0u8; MAPHASH_LEN]; 1]; + let r = InboundResource::new( + 1, + worst_case, + MAX_EFFICIENT_SIZE, + [0u8; RANDOM_HASH_SIZE], + [0u8; 32], + ResourceFlags { + encrypted: true, + ..Default::default() + }, + map_hashes, + ); + assert!( + r.is_ok(), + "receiver must accept worst-case encrypted total_size for a MAX_EFFICIENT_SIZE plaintext" + ); + + // One byte over the cap must still be rejected. + let r2 = InboundResource::new( + 1, + worst_case + 1, + MAX_EFFICIENT_SIZE + 1, + [0u8; RANDOM_HASH_SIZE], + [0u8; 32], + ResourceFlags::default(), + vec![[0u8; MAPHASH_LEN]; 1], + ); + assert!(matches!(r2, Err(ResourceError::TooLarge))); + } + + /// Wire roundtrip: a segment of a `MultiSegmentOutbound`, when ticked + /// through `OutboundTransfer`, must produce an ADV that preserves + /// `segment_index`, `total_segments`, `original_hash`, and `flags.split` + /// after pack/unpack. Without the propagation in `create_advertisement`, + /// the wire ADV defaults to single-segment values and the receiver + /// coordinator never sees the segment as part of a split resource. + #[test] + fn test_multi_segment_outbound_advertisement_carries_split_metadata() { + let original = vec![0x77; MAX_EFFICIENT_SIZE + 200]; + let multi = MultiSegmentOutbound::new(original, false).unwrap(); + assert_eq!(multi.total_segments, 2); + + for (i, segment) in multi.segments.iter().enumerate() { + let expected_idx = i + 1; + assert!(segment.flags.split, "segment {expected_idx} flags.split"); + assert_eq!(segment.segment_index, expected_idx); + assert_eq!(segment.total_segments, 2); + assert_eq!(segment.original_hash, Some(multi.original_hash)); + } + + let segment_one = &multi.segments[0]; + let mut transfer = OutboundTransfer::from_prebuilt( + OutboundResource { + state: segment_one.state, + data: segment_one.data.clone(), + random_hash: segment_one.random_hash, + resource_hash: segment_one.resource_hash, + expected_proof: segment_one.expected_proof, + flags: segment_one.flags, + parts: segment_one.parts.clone(), + map_hashes: segment_one.map_hashes.clone(), + total_size: segment_one.total_size, + advertisement_data_size: segment_one.advertisement_data_size, + segment_index: segment_one.segment_index, + total_segments: segment_one.total_segments, + request_id: segment_one.request_id.clone(), + original_hash: segment_one.original_hash, + window: WindowState::new(), + retries: 0, + sdu: segment_one.sdu, + metadata: segment_one.metadata.clone(), + metadata_size: segment_one.metadata_size, + }, + Duration::from_millis(500), + ); + + let action = transfer.tick(); + let adv_bytes = match action { + TransferAction::SendAdvertisement(b) => b, + other => panic!("expected SendAdvertisement, got {other:?}"), + }; + + let parsed = + crate::resource_adv::ResourceAdvertisement::unpack(&adv_bytes).expect("unpack adv"); + assert_eq!(parsed.segment_index, 1); + assert_eq!(parsed.total_segments, 2); + assert_eq!(parsed.original_hash, multi.original_hash); + assert_eq!(parsed.resource_hash, segment_one.resource_hash); + assert!(parsed.flags.split); + } + + #[test] + fn test_multi_segment_roundtrip() { + // End-to-end: large data → split → transfer → reassemble + let original = vec![0x42; MAX_EFFICIENT_SIZE + 500]; + let multi_out = MultiSegmentOutbound::new(original.clone(), false).unwrap(); + assert_eq!(multi_out.total_segments, 2); + + let mut multi_in = + MultiSegmentInbound::new(multi_out.total_segments, multi_out.original_hash); + + for (seg_idx, out_seg) in multi_out.segments.iter().enumerate() { + let in_res = InboundResource::new( + out_seg.num_parts(), + out_seg.total_size, + out_seg.data.len(), + out_seg.random_hash, + out_seg.resource_hash, + ResourceFlags { + compressed: false, + split: true, + ..Default::default() + }, + out_seg.map_hashes.clone(), + ) + .unwrap(); + multi_in.set_segment(seg_idx + 1, in_res); + + // Feed all parts for this segment + for part in &out_seg.parts { + multi_in.segments[seg_idx] + .as_mut() + .unwrap() + .receive_part(part.clone()); + } + multi_in.assemble_segment(seg_idx + 1, None).unwrap(); + } + + assert!(multi_in.is_complete()); + let reassembled = multi_in.reassemble().unwrap(); + assert_eq!(reassembled, original); + } + + #[test] + fn test_multi_segment_with_metadata_roundtrip() { + let original = vec![0xA7; MAX_EFFICIENT_SIZE + 500]; + let metadata = b"\x81\xa4name\xa8file.bin".to_vec(); + let multi_out = MultiSegmentOutbound::with_options( + original.clone(), + false, + Some(metadata.clone()), + None, + false, + None, + ) + .unwrap(); + assert_eq!(multi_out.total_segments, 2); + assert!(multi_out.segments[0].flags.has_metadata); + let advertised_data_size = original.len() + multi_out.segments[0].metadata_size; + assert!( + multi_out + .segments + .iter() + .all(|segment| segment.advertisement_data_size == advertised_data_size) + ); + assert!( + multi_out.segments[0].metadata_size + multi_out.segments[0].data.len() + <= MAX_EFFICIENT_SIZE + ); + assert!(!multi_out.segments[1].flags.has_metadata); + + let total_segments = multi_out.total_segments; + let original_hash = multi_out.original_hash; + let mut multi_in = MultiSegmentInbound::new(total_segments, original_hash); + + for mut segment in multi_out.segments { + let mut inbound = InboundTransfer::from_advertisement( + segment.num_parts(), + segment.total_size, + segment.data.len(), + segment.random_hash, + segment.resource_hash, + segment.flags, + segment.map_hashes.clone(), + Duration::from_millis(500), + ) + .unwrap(); + for part in &segment.parts { + let _ = inbound.receive_part(part.clone()); + } + assert!(inbound.resource.is_complete()); + let (payload, proof) = inbound.complete(None).unwrap(); + assert!(segment.validate_proof(&proof)); + if let Some(meta) = inbound.resource.metadata.clone() { + multi_in.set_metadata(meta); + } + multi_in + .set_segment_data(segment.segment_index, payload) + .unwrap(); + } + + assert_eq!(multi_in.metadata, Some(metadata)); + assert_eq!(multi_in.reassemble().unwrap(), original); + } + + #[test] + fn test_request_next_produces_valid_request() { + let data = vec![0u8; 2000]; + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + assert!(outbound.num_parts() > 1); + + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Call request_next before receiving any parts + let action = inbound.request_next(); + + // Should produce a SendRequest action + assert!(matches!(action, TransferAction::SendRequest(_))); + + if let TransferAction::SendRequest(req_data) = &action { + // First byte: exhausted flag (should be NOT exhausted) + assert_eq!(req_data[0], HASHMAP_IS_NOT_EXHAUSTED); + + // Bytes 1..33: resource_hash + assert_eq!(&req_data[1..33], &outbound.resource_hash); + + // Remaining bytes: requested hashes (multiples of MAPHASH_LEN) + let hash_data = &req_data[33..]; + assert!(!hash_data.is_empty()); + assert_eq!(hash_data.len() % MAPHASH_LEN, 0); + + // Number of requested hashes should be <= window size + let num_requested = hash_data.len() / MAPHASH_LEN; + assert!(num_requested <= inbound.resource.window.window); + } + + // outstanding_parts should be set + assert!(inbound.outstanding_parts > 0); + // req_sent should be set + assert!(inbound.req_sent.is_some()); + } + + #[test] + fn test_request_next_skips_received_parts() { + let data = vec![0u8; 2000]; + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + let num_parts = outbound.num_parts(); + assert!(num_parts > 2); + + let mut inbound = InboundTransfer::from_advertisement( + num_parts, + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + outbound.map_hashes.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Receive the first part + inbound.resource.receive_part(outbound.parts[0].clone()); + + // Now request_next should skip part 0 + let action = inbound.request_next(); + if let TransferAction::SendRequest(req_data) = &action { + let hash_data = &req_data[33..]; + // The first requested hash should NOT be the first part's hash + if hash_data.len() >= MAPHASH_LEN { + let first_requested = &hash_data[..MAPHASH_LEN]; + // It should be part 1's hash since part 0 is received and consecutive_completed=1 + assert_eq!(first_requested, &outbound.map_hashes[1]); + } + } else { + panic!("Expected SendRequest action"); + } + } + + #[test] + fn test_request_next_not_sent_when_failed() { + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + inbound.resource.state = ResourceState::Failed; + let action = inbound.request_next(); + assert!(matches!(action, TransferAction::None)); + } + + #[test] + fn test_request_next_not_sent_when_waiting_for_hmu() { + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + inbound.waiting_for_hmu = true; + let action = inbound.request_next(); + assert!(matches!(action, TransferAction::None)); + } + + #[test] + fn test_handle_request_retransmits_parts() { + let data = vec![0u8; 2000]; + let mut sender = + OutboundTransfer::new(data.clone(), false, Duration::from_millis(100)).unwrap(); + + // Advertise + sender.tick(); + + // Build a request for the first few parts + let num_parts = sender.resource.num_parts(); + let window = sender.resource.window.window.min(num_parts); + + let mut request_data = Vec::new(); + request_data.push(HASHMAP_IS_NOT_EXHAUSTED); + request_data.extend_from_slice(&sender.resource.resource_hash); + // Request first `window` parts + for i in 0..window { + request_data.extend_from_slice(&sender.resource.map_hashes[i]); + } + + let actions = sender.handle_request(&request_data); + + // Should get back parts to send + let part_actions: Vec<_> = actions + .iter() + .filter(|a| matches!(a, TransferAction::SendPart(_, _))) + .collect(); + assert_eq!(part_actions.len(), window); + + // Verify the retransmitted parts match + for action in &part_actions { + if let TransferAction::SendPart(idx, part_data) = action { + assert_eq!(part_data, &sender.resource.parts[*idx]); + } + } + } + + #[test] + fn test_handle_request_empty_data() { + let mut sender = + OutboundTransfer::new(b"data".to_vec(), false, Duration::from_millis(100)).unwrap(); + + let actions = sender.handle_request(&[]); + assert!(actions.is_empty()); + } + + #[test] + fn test_handle_request_when_failed() { + let mut sender = + OutboundTransfer::new(b"data".to_vec(), false, Duration::from_millis(100)).unwrap(); + sender.resource.state = ResourceState::Failed; + + let mut request_data = Vec::new(); + request_data.push(HASHMAP_IS_NOT_EXHAUSTED); + request_data.extend_from_slice(&sender.resource.resource_hash); + + let actions = sender.handle_request(&request_data); + assert!(actions.is_empty()); + } + + #[test] + fn test_handle_request_packet_suppresses_duplicates() { + let data = vec![0u8; 2000]; + let mut sender = + OutboundTransfer::new(data.clone(), false, Duration::from_millis(100)).unwrap(); + + sender.tick(); + + let num_parts = sender.resource.num_parts(); + let window = sender.resource.window.window.min(num_parts); + let mut request_data = Vec::new(); + request_data.push(HASHMAP_IS_NOT_EXHAUSTED); + request_data.extend_from_slice(&sender.resource.resource_hash); + for i in 0..window { + request_data.extend_from_slice(&sender.resource.map_hashes[i]); + } + + let packet_hash = [0xAB; 32]; + let first = sender.handle_request_packet(packet_hash, &request_data); + assert!( + first + .iter() + .any(|action| matches!(action, TransferAction::SendPart(_, _))) + ); + + let duplicate = sender.handle_request_packet(packet_hash, &request_data); + assert!( + duplicate.is_empty(), + "duplicate RESOURCE_REQ packet hash must be ignored" + ); + + let retry = sender.handle_request_packet([0xCD; 32], &request_data); + assert!( + retry + .iter() + .any(|action| matches!(action, TransferAction::SendPart(_, _))) + ); + } + + #[test] + fn test_exhausted_request_non_boundary_cancels() { + let data = vec![0x42u8; 20_000]; + 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, + "test requires a multi-entry hashmap segment" + ); + + let mut request_data = Vec::new(); + request_data.push(HASHMAP_IS_EXHAUSTED); + request_data.extend_from_slice(&sender.resource.map_hashes[0]); + request_data.extend_from_slice(&sender.resource.resource_hash); + + let actions = sender.handle_request(&request_data); + assert_eq!(sender.resource.state, ResourceState::Failed); + assert!(matches!( + actions.as_slice(), + [TransferAction::SendCancel(CancelType::Icl, rh)] if *rh == sender.resource.resource_hash + )); + } + + #[test] + fn test_receive_part_decrements_outstanding() { + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Manually set outstanding_parts as if request_next was called + inbound.outstanding_parts = outbound.num_parts().min(WINDOW_INITIAL); + + // Receive one part + let initial_outstanding = inbound.outstanding_parts; + inbound.receive_part(outbound.parts[0].clone()); + assert_eq!(inbound.outstanding_parts, initial_outstanding - 1); + } + + #[test] + fn test_receive_part_triggers_request_next_on_window_complete() { + let data = vec![0u8; 5000]; // Multiple parts > window size + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + let num_parts = outbound.num_parts(); + assert!(num_parts > WINDOW_INITIAL); + + let mut inbound = InboundTransfer::from_advertisement( + num_parts, + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + outbound.map_hashes.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Set outstanding_parts to match window + let window = inbound.resource.window.window; + inbound.outstanding_parts = window; + + // Feed all parts in the window + let mut got_request = false; + for i in 0..window { + let action = inbound.receive_part(outbound.parts[i].clone()); + if matches!(action, TransferAction::SendRequest(_)) { + got_request = true; + } + } + + // Should have triggered request_next when outstanding_parts hit 0 + assert!(got_request, "Expected SendRequest when window is complete"); + } + + #[test] + fn test_check_timeout_no_timeout_initially() { + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Immediately after creation, no timeout should occur + let action = inbound.check_timeout(); + assert!(matches!(action, TransferAction::None)); + } + + #[test] + fn test_check_timeout_not_transferring() { + 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.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // If not in transferring state, should do nothing + inbound.resource.state = ResourceState::Assembling; + let action = inbound.check_timeout(); + assert!(matches!(action, TransferAction::None)); + } + + #[test] + fn test_check_timeout_triggers_retry() { + 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.clone(), + Duration::from_millis(1), // Very short RTT to trigger timeout quickly + ) + .unwrap(); + + inbound.outstanding_parts = 2; + // Set last_activity far enough in the past to trigger timeout + inbound.last_activity = Instant::now() - Duration::from_secs(60); + + let initial_retries = inbound.retries_left; + let action = inbound.check_timeout(); + + // Should trigger a retry (SendRequest) + assert!( + matches!(action, TransferAction::SendRequest(_)), + "Expected SendRequest on timeout, got {:?}", + action + ); + assert_eq!(inbound.retries_left, initial_retries - 1); + } + + #[test] + fn test_check_timeout_fails_when_retries_exhausted() { + 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.clone(), + Duration::from_millis(1), + ) + .unwrap(); + + inbound.outstanding_parts = 2; + inbound.retries_left = 0; + inbound.last_activity = Instant::now() - Duration::from_secs(60); + + let action = inbound.check_timeout(); + assert!(matches!(action, TransferAction::Failed(_))); + assert_eq!(inbound.resource.state, ResourceState::Failed); + } + + #[test] + fn test_hashmap_update_extends_map_hashes() { + let data = vec![0u8; 2000]; + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + + // Create inbound with only partial map hashes (simulating a large resource) + let partial_hashes = outbound.map_hashes[..2].to_vec(); + let initial_height = partial_hashes.len(); + + 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() + }, + partial_hashes, + Duration::from_millis(100), + ) + .unwrap(); + + assert_eq!(inbound.resource.map_hashes.len(), 2); + 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 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]); + } + + let action = inbound.hashmap_update(0, &hashmap_bytes); + + // Should have extended map_hashes + assert!(inbound.resource.map_hashes.len() >= end); + // Should have cleared waiting_for_hmu + assert!(!inbound.waiting_for_hmu); + // Should have triggered a request_next + assert!(matches!(action, TransferAction::SendRequest(_))); + } + + #[test] + fn test_full_transfer_with_request_next() { + // Full transfer using the request_next mechanism instead of + // the simple feed-all-parts approach. + let data = vec![0xAB; 3000]; // Multi-part + let mut sender = + OutboundTransfer::new(data.clone(), false, Duration::from_millis(50)).unwrap(); + + // Step 1: Sender advertises + let adv = sender.tick(); + assert!(matches!(adv, TransferAction::SendAdvertisement(_))); + + // Step 2: Receiver accepts and sends initial request + let mut receiver = InboundTransfer::from_advertisement( + sender.resource.num_parts(), + sender.resource.total_size, + data.len(), + sender.resource.random_hash, + sender.resource.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + sender.resource.map_hashes.clone(), + Duration::from_millis(50), + ) + .unwrap(); + + let initial_request = receiver.request_next(); + assert!(matches!(initial_request, TransferAction::SendRequest(_))); + + // Step 3: Transfer loop using request/response cycle + let mut iterations = 0; + let max_iterations = sender.resource.num_parts() * 4 + 20; + + // Process the initial request + let mut pending_request = Some(initial_request); + + while !receiver.resource.is_complete() && iterations < max_iterations { + if let Some(TransferAction::SendRequest(req_data)) = pending_request.take() { + // Sender handles the request and retransmits parts + let actions = sender.handle_request(&req_data); + for action in actions { + match action { + TransferAction::SendPart(_idx, part_data) => { + let recv_action = receiver.receive_part(part_data); + match recv_action { + TransferAction::SendRequest(_) => { + pending_request = Some(recv_action); + } + TransferAction::SendHmu(_) => { + // Transfer is complete from receiver's perspective + } + _ => {} + } + } + TransferAction::SendHmu(hmu) => { + sender.handle_hmu(&hmu); + } + _ => {} + } + } + } else { + // If no pending request, create one + pending_request = Some(receiver.request_next()); + } + iterations += 1; + } + + assert!( + receiver.resource.is_complete(), + "transfer incomplete after {} iterations ({} of {} parts received)", + iterations, + receiver.resource.received_count(), + receiver.resource.total_parts, + ); + + // Complete and verify integrity + let (assembled, proof) = receiver.complete(None).unwrap(); + assert_eq!(assembled, data); + assert!(sender.handle_proof(&proof)); + } + + #[test] + fn test_request_next_with_partial_loss() { + // Simulate a transfer where the first part is received but subsequent + // parts are lost, requiring re-request via request_next. + let data = vec![0xCD; 2000]; + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + let num_parts = outbound.num_parts(); + assert!(num_parts > 2); + + let mut inbound = InboundTransfer::from_advertisement( + num_parts, + outbound.total_size, + data.len(), + outbound.random_hash, + outbound.resource_hash, + ResourceFlags { + compressed: false, + ..Default::default() + }, + outbound.map_hashes.clone(), + Duration::from_millis(100), + ) + .unwrap(); + + // Receive only the first part + inbound.resource.receive_part(outbound.parts[0].clone()); + assert_eq!(inbound.resource.consecutive_completed, 1); + assert!(!inbound.resource.is_complete()); + + // request_next should request parts starting from consecutive_completed + let action = inbound.request_next(); + if let TransferAction::SendRequest(req_data) = &action { + let hash_data = &req_data[33..]; // Skip exhausted flag + resource_hash + let num_requested = hash_data.len() / MAPHASH_LEN; + + // Should request at least one part + assert!( + num_requested > 0, + "Should request at least one missing part" + ); + + // Number requested should not exceed window size + assert!(num_requested <= inbound.resource.window.window); + + // All requested hashes should match map hashes of missing parts + for i in 0..num_requested { + let start = i * MAPHASH_LEN; + let req_hash = &hash_data[start..start + MAPHASH_LEN]; + + let mut found = false; + for (idx, mh) in outbound.map_hashes.iter().enumerate() { + if mh.as_slice() == req_hash && inbound.resource.parts[idx].is_none() { + found = true; + break; + } + } + assert!(found, "Requested hash {} should match a missing part", i); + } + } else { + panic!("Expected SendRequest action"); + } + + // Now feed all remaining parts and verify completion + for i in 1..num_parts { + inbound.resource.receive_part(outbound.parts[i].clone()); + } + + assert!(inbound.resource.is_complete()); + let assembled = inbound.resource.assemble(None).unwrap(); + assert_eq!(assembled, data); + } + + #[test] + fn test_sender_receiver_min_consecutive_height_tracking() { + let data = vec![0u8; 5000]; + let mut sender = + OutboundTransfer::new(data.clone(), false, Duration::from_millis(100)).unwrap(); + + assert_eq!(sender.receiver_min_consecutive_height, 0); + + // Advertise + sender.tick(); + + // Create a request indicating hashmap exhaustion + 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 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); + + let _actions = sender.handle_request(&request_data); + + // receiver_min_consecutive_height should be updated + // (the exact value depends on WINDOW_MAX and the boundary index) + // Just verify it was potentially updated from 0 + // For small resources it may stay at 0 if boundary_idx < WINDOW_MAX + assert!(sender.receiver_min_consecutive_height <= sender.resource.num_parts()); + } + + fn build_inbound_for_eifr_tests(rtt: Duration) -> InboundTransfer { + let data = vec![0u8; 2000]; + let outbound = OutboundResource::new(data.clone(), false, None).unwrap(); + 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.clone(), + rtt, + ) + .unwrap() + } + + #[test] + fn test_update_eifr_prefers_measured_rate() { + let mut inbound = build_inbound_for_eifr_tests(Duration::from_millis(100)); + inbound.previous_eifr = Some(1_000.0); + inbound.req_data_rtt_rate = 500.0; // bytes/sec + + inbound.update_eifr(); + + let eifr = inbound.eifr.expect("update_eifr should populate eifr"); + assert!( + (eifr - 4_000.0).abs() < 1e-6, + "measured rate should win: expected 4000.0 bits/sec, got {}", + eifr + ); + // Non-zero sample must warm previous_eifr. + assert_eq!(inbound.previous_eifr, Some(4_000.0)); + } + + #[test] + fn test_update_eifr_falls_back_to_previous() { + let mut inbound = build_inbound_for_eifr_tests(Duration::from_millis(100)); + inbound.seed_previous_eifr(12_345.0); + assert_eq!(inbound.previous_eifr, Some(12_345.0)); + // No measured rate yet. + assert_eq!(inbound.req_data_rtt_rate, 0.0); + + inbound.update_eifr(); + + assert_eq!( + inbound.eifr, + Some(12_345.0), + "with req_data_rtt_rate == 0, previous_eifr should win" + ); + } + + #[test] + fn test_update_eifr_cold_start() { + let rtt = Duration::from_millis(200); + let mut inbound = build_inbound_for_eifr_tests(rtt); + assert_eq!(inbound.req_data_rtt_rate, 0.0); + assert!(inbound.previous_eifr.is_none()); + + inbound.update_eifr(); + + let expected = (EIFR_COLD_START_BYTES as f64 * 8.0) / rtt.as_secs_f64(); + let actual = inbound.eifr.expect("cold-start should still set eifr"); + assert!( + (actual - expected).abs() < 1e-6, + "cold start should use EIFR_COLD_START_BYTES * 8 / rtt: expected {}, got {}", + expected, + actual + ); + } + + #[test] + fn test_seed_previous_eifr_rejects_non_positive() { + let mut inbound = build_inbound_for_eifr_tests(Duration::from_millis(50)); + inbound.seed_previous_eifr(0.0); + assert!(inbound.previous_eifr.is_none()); + inbound.seed_previous_eifr(-1.0); + assert!(inbound.previous_eifr.is_none()); + inbound.seed_previous_eifr(1.0); + assert_eq!(inbound.previous_eifr, Some(1.0)); + } + + #[test] + fn test_request_next_snapshots_rxd_bytes() { + let mut inbound = build_inbound_for_eifr_tests(Duration::from_millis(100)); + inbound.rtt_rxd_bytes = 9_999; + assert_eq!(inbound.rtt_rxd_bytes_at_part_req, 0); + + let _ = inbound.request_next(); + + assert_eq!( + inbound.rtt_rxd_bytes_at_part_req, 9_999, + "request_next must snapshot rtt_rxd_bytes so the next window can compute a delta" + ); + } + + #[test] + fn test_check_timeout_includes_hmu_wait_when_waiting() { + // Two receivers, identical except `waiting_for_hmu` — the one that is + // waiting must tolerate a strictly longer silence before retrying. + let rtt = Duration::from_millis(1); + + let mut waiting = build_inbound_for_eifr_tests(rtt); + waiting.outstanding_parts = 2; + waiting.waiting_for_hmu = true; + waiting.previous_eifr = Some(1_000.0); // deterministic eifr + waiting.last_activity = Instant::now(); + + let mut not_waiting = build_inbound_for_eifr_tests(rtt); + not_waiting.outstanding_parts = 2; + not_waiting.waiting_for_hmu = false; + not_waiting.previous_eifr = Some(1_000.0); + not_waiting.last_activity = Instant::now(); + + // Give both a measured rate so they take the post-RTT branch. + waiting.req_data_rtt_rate = 125.0; + not_waiting.req_data_rtt_rate = 125.0; + + // Short idle — neither should retry yet. + let idle = Duration::from_millis(1); + waiting.last_activity = Instant::now() - idle; + not_waiting.last_activity = Instant::now() - idle; + + assert!(matches!(waiting.check_timeout(), TransferAction::None)); + assert!(matches!(not_waiting.check_timeout(), TransferAction::None)); + + // With waiting_for_hmu=true the HMU wait addend should be non-zero. + let sdu = waiting.resource.sdu as f64; + let eifr = waiting.eifr.unwrap(); + let hmu_addend = (sdu * 8.0 * HMU_WAIT_FACTOR) / eifr; + assert!( + hmu_addend > 0.0, + "with waiting_for_hmu=true, hmu addend should contribute a positive duration" + ); + } + + #[test] + fn test_check_timeout_pre_rtt_uses_cold_start_branch() { + // Receiver with no measured rate yet (req_data_rtt_rate==0) should + // take the cold-start branch. Validate by seeding an `eifr` that + // would be tiny under the post-RTT branch (huge timeout) but is + // derived from previous_eifr here, producing a knowable timeout. + let rtt = Duration::from_millis(100); + let mut inbound = build_inbound_for_eifr_tests(rtt); + inbound.outstanding_parts = 2; + inbound.previous_eifr = Some(800.0); // 800 bits/sec + inbound.retries_left = MAX_RETRIES; + + // Force last_activity far enough in the past that even the slow + // cold-start branch will fire. Use checked subtraction because Windows + // `Instant` panics if subtraction crosses its monotonic-clock base. + inbound.update_eifr(); + let timeout = inbound.part_timeout_factor + * ((3.0 * inbound.resource.sdu as f64) / inbound.eifr.unwrap()) + + RETRY_GRACE_TIME + + Duration::from_millis(1).as_secs_f64(); + let expired_by = Duration::from_secs_f64(timeout); + let now = Instant::now(); + inbound.last_activity = if let Some(last_activity) = now.checked_sub(expired_by) { + last_activity + } else { + std::thread::sleep(expired_by); + now + }; + + let initial_retries = inbound.retries_left; + let action = inbound.check_timeout(); + assert!( + matches!(action, TransferAction::SendRequest(_)), + "expected cold-start timeout to retry, got {:?}", + action + ); + assert_eq!(inbound.retries_left, initial_retries - 1); + } +} diff --git a/crates/rns-protocol/src/resource_adv.rs b/crates/rns-protocol/src/resource_adv.rs new file mode 100644 index 0000000..8bf5b8a --- /dev/null +++ b/crates/rns-protocol/src/resource_adv.rs @@ -0,0 +1,423 @@ +use crate::resource::{MAPHASH_LEN, ResourceFlags}; + +/// Advertisement overhead in bytes (non-hashmap data). +pub const OVERHEAD: usize = 134; + +/// Maximum map-hash entries that fit alongside the advertisement overhead in one MDU. +pub fn hashmap_max_len(mdu: usize) -> usize { + if mdu > OVERHEAD { + (mdu - OVERHEAD) / MAPHASH_LEN + } else { + 0 + } +} + +/// Space reserved to absorb a burst of out-of-order part requests without +/// churning the main hashmap: `2 * WINDOW_MAX_FAST + hashmap_max_len(mdu)`. +pub fn collision_guard_size(mdu: usize) -> usize { + 2 * crate::resource::WINDOW_MAX_FAST + hashmap_max_len(mdu) +} + +/// Msgpack-encoded announcement that precedes a resource transfer. +/// +/// Keys in the packed map: +/// - `t`: transfer_size, `d`: data_size, `n`: num_parts +/// - `h`: resource_hash, `r`: random_hash, `o`: original_hash +/// - `i`: segment_index, `l`: total_segments, `q`: request_id +/// - `f`: flags byte, `m`: hashmap +/// +/// When `flags.has_metadata` is set the reassembled data begins with a +/// length-prefixed metadata block that the receiver strips before delivering +/// the payload. +#[derive(Debug, Clone)] +pub struct ResourceAdvertisement { + pub transfer_size: usize, + pub data_size: usize, + pub num_parts: usize, + pub resource_hash: [u8; 32], + pub random_hash: Vec, + pub original_hash: [u8; 32], + pub segment_index: usize, + pub total_segments: usize, + pub request_id: Option>, + pub flags: ResourceFlags, + pub hashmap: Vec, + /// Length of the metadata prefix embedded in the resource data when + /// `flags.has_metadata` is set. Not transmitted on the wire. + pub metadata_size: usize, +} + +impl ResourceAdvertisement { + /// Build an advertisement with no metadata prefix. Equivalent to + /// [`Self::with_metadata_size`] with `metadata_size = 0`. + // Mirrors the Resource ADV wire fields; grouping these into a builder + // would hide the packet layout this constructor exists to preserve. + #[allow(clippy::too_many_arguments)] + pub fn new( + transfer_size: usize, + data_size: usize, + num_parts: usize, + resource_hash: [u8; 32], + random_hash: Vec, + flags: ResourceFlags, + map_hashes: &[[u8; MAPHASH_LEN]], + mdu: usize, + ) -> Self { + Self::with_metadata_size( + transfer_size, + data_size, + num_parts, + resource_hash, + random_hash, + flags, + map_hashes, + mdu, + 0, + ) + } + + /// Build an advertisement, truncating `map_hashes` to what actually fits in + /// the MDU. Callers are expected to send the remaining hashes in a + /// subsequent hashmap-update packet. + // Same Resource ADV field set as `new`, plus the local metadata prefix + // size needed to split payload from metadata after receive. + #[allow(clippy::too_many_arguments)] + pub fn with_metadata_size( + transfer_size: usize, + data_size: usize, + num_parts: usize, + resource_hash: [u8; 32], + random_hash: Vec, + flags: ResourceFlags, + map_hashes: &[[u8; MAPHASH_LEN]], + mdu: usize, + metadata_size: usize, + ) -> Self { + let max_hashes = hashmap_max_len(mdu); + let initial_hashes = map_hashes.len().min(max_hashes); + + let mut hashmap = Vec::with_capacity(initial_hashes * MAPHASH_LEN); + for hash in map_hashes.iter().take(initial_hashes) { + hashmap.extend_from_slice(hash); + } + + Self { + transfer_size, + data_size, + num_parts, + resource_hash, + random_hash, + original_hash: resource_hash, + segment_index: 1, + total_segments: 1, + request_id: None, + flags, + hashmap, + metadata_size, + } + } + + /// Decode an advertisement produced by [`Self::pack`] or by the Python + /// reference implementation. + pub fn unpack(data: &[u8]) -> Result { + use rmpv::Value; + + let value = + rmpv::decode::read_value(&mut &data[..]).map_err(|e| format!("msgpack decode: {e}"))?; + + let map = match &value { + Value::Map(m) => m, + _ => return Err("expected msgpack map".into()), + }; + + let get = |key: &str| -> Option<&Value> { + map.iter() + .find(|(k, _)| matches!(k, Value::String(s) if s.as_str() == Some(key))) + .map(|(_, v)| v) + }; + + let get_usize = |key: &str| -> Result { + get(key) + .and_then(|v| v.as_u64()) + .map(|v| v as usize) + .ok_or_else(|| format!("missing or invalid key: {key}")) + }; + + let get_bytes = |key: &str, len: usize| -> Result, String> { + let bytes = get(key) + .and_then(|v| v.as_slice()) + .ok_or_else(|| format!("missing or invalid key: {key}"))?; + if bytes.len() < len { + return Err(format!("{key}: expected {len} bytes, got {}", bytes.len())); + } + Ok(bytes.to_vec()) + }; + + let transfer_size = get_usize("t")?; + let data_size = get_usize("d")?; + let num_parts = get_usize("n")?; + + let h_bytes = get_bytes("h", 32)?; + let mut resource_hash = [0u8; 32]; + resource_hash.copy_from_slice(&h_bytes[..32]); + + // Python sends a 16-byte random tag, but any length >= 4 is acceptable. + let random_hash = get_bytes("r", 4)?; + + let o_bytes = get_bytes("o", 32)?; + let mut original_hash = [0u8; 32]; + original_hash.copy_from_slice(&o_bytes[..32]); + + let segment_index = get_usize("i")?; + let total_segments = get_usize("l")?; + + let request_id = get("q").and_then(|v| { + if v.is_nil() { + None + } else { + v.as_slice().map(|s| s.to_vec()) + } + }); + + let flags_byte = get("f").and_then(|v| v.as_u64()).unwrap_or(0) as u8; + let flags = ResourceFlags::from_byte(flags_byte); + + let hashmap = get("m") + .and_then(|v| v.as_slice()) + .map(|s| s.to_vec()) + .unwrap_or_default(); + + Ok(Self { + transfer_size, + data_size, + num_parts, + resource_hash, + random_hash, + original_hash, + segment_index, + total_segments, + request_id, + flags, + hashmap, + metadata_size: 0, + }) + } + + /// Encode as the msgpack map described on the struct docs. + pub fn pack(&self) -> Vec { + use rmpv::Value; + + let q_val = match &self.request_id { + Some(id) => Value::Binary(id.clone()), + None => Value::Nil, + }; + + let pairs: Vec<(Value, Value)> = vec![ + ( + Value::String("t".into()), + Value::Integer(self.transfer_size.into()), + ), + ( + Value::String("d".into()), + Value::Integer(self.data_size.into()), + ), + ( + Value::String("n".into()), + Value::Integer(self.num_parts.into()), + ), + ( + Value::String("h".into()), + Value::Binary(self.resource_hash.to_vec()), + ), + ( + Value::String("r".into()), + Value::Binary(self.random_hash.to_vec()), + ), + ( + Value::String("o".into()), + Value::Binary(self.original_hash.to_vec()), + ), + ( + Value::String("i".into()), + Value::Integer(self.segment_index.into()), + ), + ( + Value::String("l".into()), + Value::Integer(self.total_segments.into()), + ), + (Value::String("q".into()), q_val), + ( + Value::String("f".into()), + Value::Integer(self.flags.to_byte().into()), + ), + ( + Value::String("m".into()), + Value::Binary(self.hashmap.clone()), + ), + ]; + + let value = Value::Map(pairs); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &value).expect("msgpack encode should succeed"); + buf + } + + /// Split the packed `hashmap` field into fixed-length map-hash entries. + pub fn get_map_hashes(&self) -> Vec<[u8; MAPHASH_LEN]> { + self.hashmap + .chunks_exact(MAPHASH_LEN) + .map(|chunk| { + let mut hash = [0u8; MAPHASH_LEN]; + hash.copy_from_slice(chunk); + hash + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hashmap_max_len() { + // 415 is a typical link MDU on LoRa. + let max = hashmap_max_len(415); + assert_eq!(max, (415 - 134) / 4); + assert_eq!(max, 70); + } + + #[test] + fn test_default_link_mdu_matches_python_hashmap_capacity() { + assert_eq!(rns_wire::constants::ENCRYPTED_MDU, 431); + assert_eq!(hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU), 74); + } + + #[test] + fn test_advertisement_creation() { + let hashes: Vec<[u8; 4]> = (0..100).map(|i| [i as u8; 4]).collect(); + let adv = ResourceAdvertisement::new( + 1000, + 800, + 3, + [0xAA; 32], + vec![0xBB; 4], + ResourceFlags::default(), + &hashes, + 415, + ); + + let extracted = adv.get_map_hashes(); + // Construction must truncate to whatever fits in the MDU. + assert_eq!(extracted.len(), 70); + assert_eq!(extracted[0], [0; 4]); + } + + #[test] + fn test_collision_guard() { + let guard = collision_guard_size(415); + assert_eq!(guard, 2 * 75 + 70); + assert_eq!(guard, 220); + } + + #[test] + fn test_advertisement_with_metadata() { + let hashes: Vec<[u8; 4]> = (0..10).map(|i| [i as u8; 4]).collect(); + let flags = ResourceFlags { + has_metadata: true, + ..Default::default() + }; + let adv = ResourceAdvertisement::with_metadata_size( + 1000, + 800, + 3, + [0xAA; 32], + vec![0xBB; 4], + flags, + &hashes, + 415, + 42, + ); + + assert!(adv.flags.has_metadata); + assert_eq!(adv.metadata_size, 42); + } + + #[test] + fn test_advertisement_default_no_metadata() { + let hashes: Vec<[u8; 4]> = (0..5).map(|i| [i as u8; 4]).collect(); + let adv = ResourceAdvertisement::new( + 500, + 400, + 2, + [0xCC; 32], + vec![0xDD; 4], + ResourceFlags::default(), + &hashes, + 415, + ); + + assert!(!adv.flags.has_metadata); + assert_eq!(adv.metadata_size, 0); + } + + use proptest::prelude::*; + + proptest! { + /// ResourceAdvertisement msgpack round-trip. The existing tests + /// check construction / field-level behavior but not the pack → + /// unpack cycle. This samples the whole-struct space and locks + /// in: all top-level fields survive the msgpack round-trip, + /// including the optional `request_id` variants (Nil vs Binary). + #[test] + fn proptest_resource_adv_pack_unpack_roundtrip( + transfer_size in 0usize..=10_000_000, + data_size in 0usize..=10_000_000, + num_parts in 0usize..=10_000, + resource_hash: [u8; 32], + // random_hash is a fixed-size RANDOM_HASH_SIZE (4 bytes) field. + random_hash_bytes: [u8; crate::resource::RANDOM_HASH_SIZE], + segment_index in 1usize..=256, + total_segments in 1usize..=256, + request_id in proptest::option::of(proptest::collection::vec(any::(), 1..=32)), + flags_byte: u8, + hashmap in proptest::collection::vec(any::(), 0..=256), + ) { + let mut adv = ResourceAdvertisement { + transfer_size, + data_size, + num_parts, + resource_hash, + random_hash: random_hash_bytes.to_vec(), + original_hash: resource_hash, + segment_index, + total_segments, + request_id: request_id.clone(), + flags: ResourceFlags::from_byte(flags_byte), + hashmap: hashmap.clone(), + // metadata_size is NOT on the wire — set to 0 before + // packing so the round-trip comparison is meaningful. + metadata_size: 0, + }; + // Trim hashmap to multiples of MAPHASH_LEN so the reader's + // chunked parse doesn't drop a stray trailing byte. + let usable = (adv.hashmap.len() / MAPHASH_LEN) * MAPHASH_LEN; + adv.hashmap.truncate(usable); + + let packed = adv.pack(); + let unpacked = ResourceAdvertisement::unpack(&packed).unwrap(); + + prop_assert_eq!(unpacked.transfer_size, adv.transfer_size); + prop_assert_eq!(unpacked.data_size, adv.data_size); + prop_assert_eq!(unpacked.num_parts, adv.num_parts); + prop_assert_eq!(unpacked.resource_hash, adv.resource_hash); + prop_assert_eq!(unpacked.random_hash.as_slice(), &random_hash_bytes[..]); + prop_assert_eq!(unpacked.original_hash, adv.original_hash); + prop_assert_eq!(unpacked.segment_index, adv.segment_index); + prop_assert_eq!(unpacked.total_segments, adv.total_segments); + prop_assert_eq!(&unpacked.request_id, &adv.request_id); + prop_assert_eq!(unpacked.flags.to_byte(), adv.flags.to_byte()); + prop_assert_eq!(&unpacked.hashmap, &adv.hashmap); + } + } +} diff --git a/crates/rns-protocol/src/rnsh.rs b/crates/rns-protocol/src/rnsh.rs new file mode 100644 index 0000000..9d13728 --- /dev/null +++ b/crates/rns-protocol/src/rnsh.rs @@ -0,0 +1,740 @@ +//! rnsh channel message codecs. +//! +//! Python reference: `RNS/Utilities/rnsh/protocol.py`. + +use std::io::Cursor; + +use rmpv::Value; + +use crate::channel_message::{ChannelMessageError, MessageBase}; +use crate::compression; + +pub const MSG_MAGIC: u8 = 0xAC; +pub const PROTOCOL_VERSION: u64 = 1; + +pub const MSG_TYPE_NOOP: u16 = make_msg_type(0); +pub const MSG_TYPE_WINDOW_SIZE: u16 = make_msg_type(2); +pub const MSG_TYPE_EXECUTE_COMMAND: u16 = make_msg_type(3); +pub const MSG_TYPE_STREAM_DATA: u16 = make_msg_type(4); +pub const MSG_TYPE_VERSION_INFO: u16 = make_msg_type(5); +pub const MSG_TYPE_ERROR: u16 = make_msg_type(6); +pub const MSG_TYPE_COMMAND_EXITED: u16 = make_msg_type(7); + +pub const MESSAGE_TYPES: [u16; 7] = [ + MSG_TYPE_NOOP, + MSG_TYPE_VERSION_INFO, + MSG_TYPE_WINDOW_SIZE, + MSG_TYPE_EXECUTE_COMMAND, + MSG_TYPE_STREAM_DATA, + MSG_TYPE_COMMAND_EXITED, + MSG_TYPE_ERROR, +]; + +pub const STREAM_ID_STDIN: u16 = 0; +pub const STREAM_ID_STDOUT: u16 = 1; +pub const STREAM_ID_STDERR: u16 = 2; + +pub const STREAM_ID_MAX: u16 = 0x3FFF; +pub const STREAM_DATA_OVERHEAD: usize = 8; + +pub const fn make_msg_type(val: u8) -> u16 { + ((MSG_MAGIC as u16) << 8) | (val as u16) +} + +#[derive(Debug, thiserror::Error)] +pub enum RnshCodecError { + #[error("msgpack decode failed: {0}")] + Decode(String), + #[error("msgpack encode failed: {0}")] + Encode(String), + #[error("unexpected msgpack shape for {0}")] + InvalidShape(&'static str), + #[error("invalid utf-8 string")] + InvalidUtf8, + #[error("unknown rnsh message type: 0x{0:04X}")] + UnknownMessageType(u16), + #[error("stream data unpack failed")] + StreamData, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct NoopMessage; + +impl MessageBase for NoopMessage { + fn msg_type(&self) -> u16 { + MSG_TYPE_NOOP + } + + fn pack(&self) -> Vec { + Vec::new() + } + + fn unpack(&mut self, _raw: &[u8]) -> Result<(), ChannelMessageError> { + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct WindowSizeMessage { + pub rows: Option, + pub cols: Option, + pub hpix: Option, + pub vpix: Option, +} + +impl WindowSizeMessage { + pub fn new(rows: Option, cols: Option, hpix: Option, vpix: Option) -> Self { + Self { + rows, + cols, + hpix, + vpix, + } + } + + pub fn unpack_payload(raw: &[u8]) -> Result { + let values = decode_array(raw, 4, "WindowSizeMessage")?; + Ok(Self { + rows: value_to_u32_opt(&values[0], "rows")?, + cols: value_to_u32_opt(&values[1], "cols")?, + hpix: value_to_u32_opt(&values[2], "hpix")?, + vpix: value_to_u32_opt(&values[3], "vpix")?, + }) + } +} + +impl MessageBase for WindowSizeMessage { + fn msg_type(&self) -> u16 { + MSG_TYPE_WINDOW_SIZE + } + + fn pack(&self) -> Vec { + encode_value(&Value::Array(vec![ + u32_opt_to_value(self.rows), + u32_opt_to_value(self.cols), + u32_opt_to_value(self.hpix), + u32_opt_to_value(self.vpix), + ])) + .expect("rnsh window size msgpack encode") + } + + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + *self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExecuteCommandMessage { + pub cmdline: Option>, + pub pipe_stdin: bool, + pub pipe_stdout: bool, + pub pipe_stderr: bool, + pub tcflags: Option, + pub term: Option, + pub rows: Option, + pub cols: Option, + pub hpix: Option, + pub vpix: Option, +} + +impl ExecuteCommandMessage { + // Mirrors the rnsh ExecuteCommand channel payload; each parameter maps to + // a serialized field in the message. + #[allow(clippy::too_many_arguments)] + pub fn new( + cmdline: Option>, + pipe_stdin: bool, + pipe_stdout: bool, + pipe_stderr: bool, + tcflags: Option, + term: Option, + rows: Option, + cols: Option, + hpix: Option, + vpix: Option, + ) -> Self { + Self { + cmdline, + pipe_stdin, + pipe_stdout, + pipe_stderr, + tcflags, + term, + rows, + cols, + hpix, + vpix, + } + } + + pub fn unpack_payload(raw: &[u8]) -> Result { + let values = decode_array(raw, 10, "ExecuteCommandMessage")?; + Ok(Self { + cmdline: value_to_string_vec_opt(&values[0], "cmdline")?, + pipe_stdin: value_to_bool(&values[1], "pipe_stdin")?, + pipe_stdout: value_to_bool(&values[2], "pipe_stdout")?, + pipe_stderr: value_to_bool(&values[3], "pipe_stderr")?, + tcflags: none_if_nil(values[4].clone()), + term: value_to_string_opt(&values[5], "term")?, + rows: value_to_u32_opt(&values[6], "rows")?, + cols: value_to_u32_opt(&values[7], "cols")?, + hpix: value_to_u32_opt(&values[8], "hpix")?, + vpix: value_to_u32_opt(&values[9], "vpix")?, + }) + } +} + +impl MessageBase for ExecuteCommandMessage { + fn msg_type(&self) -> u16 { + MSG_TYPE_EXECUTE_COMMAND + } + + fn pack(&self) -> Vec { + encode_value(&Value::Array(vec![ + string_vec_opt_to_value(self.cmdline.as_ref()), + Value::Boolean(self.pipe_stdin), + Value::Boolean(self.pipe_stdout), + Value::Boolean(self.pipe_stderr), + self.tcflags.clone().unwrap_or(Value::Nil), + string_opt_to_value(self.term.as_deref()), + u32_opt_to_value(self.rows), + u32_opt_to_value(self.cols), + u32_opt_to_value(self.hpix), + u32_opt_to_value(self.vpix), + ])) + .expect("rnsh execute command msgpack encode") + } + + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + *self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RnshStreamDataMessage { + pub stream_id: u16, + pub eof: bool, + pub compressed: bool, + pub data: Vec, +} + +impl RnshStreamDataMessage { + pub fn new(stream_id: u16, data: Vec, eof: bool) -> Self { + Self { + stream_id: stream_id & STREAM_ID_MAX, + eof, + compressed: false, + data, + } + } + + fn header_value(&self) -> u16 { + let mut val = self.stream_id & STREAM_ID_MAX; + if self.eof { + val |= 0x8000; + } + if self.compressed { + val |= 0x4000; + } + val + } + + fn parse_header(val: u16) -> (u16, bool, bool) { + let eof = (val & 0x8000) != 0; + let compressed = (val & 0x4000) != 0; + let stream_id = val & STREAM_ID_MAX; + (stream_id, eof, compressed) + } + + pub fn unpack_payload(raw: &[u8]) -> Result { + if raw.len() < 2 { + return Err(RnshCodecError::StreamData); + } + + let header_val = u16::from_be_bytes([raw[0], raw[1]]); + let (stream_id, eof, compressed) = Self::parse_header(header_val); + let payload = &raw[2..]; + let data = if compressed && !payload.is_empty() { + compression::bz2_decompress(payload, crate::buffer::MAX_CHUNK_LEN) + .map_err(|_| RnshCodecError::StreamData)? + } else { + payload.to_vec() + }; + + Ok(Self { + stream_id, + eof, + compressed, + data, + }) + } +} + +impl Default for RnshStreamDataMessage { + fn default() -> Self { + Self::new(0, Vec::new(), false) + } +} + +impl MessageBase for RnshStreamDataMessage { + fn msg_type(&self) -> u16 { + MSG_TYPE_STREAM_DATA + } + + fn pack(&self) -> Vec { + let mut result = Vec::with_capacity(2 + self.data.len()); + result.extend_from_slice(&self.header_value().to_be_bytes()); + result.extend_from_slice(&self.data); + result + } + + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + *self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VersionInfoMessage { + pub sw_version: String, + pub protocol_version: u64, +} + +impl VersionInfoMessage { + pub fn new(sw_version: impl Into) -> Self { + Self { + sw_version: sw_version.into(), + protocol_version: PROTOCOL_VERSION, + } + } + + pub fn unpack_payload(raw: &[u8]) -> Result { + let values = decode_array(raw, 2, "VersionInfoMessage")?; + Ok(Self { + sw_version: value_to_string(&values[0], "sw_version")?, + protocol_version: value_to_u64(&values[1], "protocol_version")?, + }) + } +} + +impl Default for VersionInfoMessage { + fn default() -> Self { + Self::new(env!("CARGO_PKG_VERSION")) + } +} + +impl MessageBase for VersionInfoMessage { + fn msg_type(&self) -> u16 { + MSG_TYPE_VERSION_INFO + } + + fn pack(&self) -> Vec { + encode_value(&Value::Array(vec![ + string_to_value(&self.sw_version), + Value::from(self.protocol_version), + ])) + .expect("rnsh version info msgpack encode") + } + + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + *self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ErrorMessage { + pub msg: Option, + pub fatal: bool, + pub data: Option, +} + +impl ErrorMessage { + pub fn new(msg: Option, fatal: bool, data: Option) -> Self { + Self { msg, fatal, data } + } + + pub fn unpack_payload(raw: &[u8]) -> Result { + let values = decode_array(raw, 3, "ErrorMessage")?; + Ok(Self { + msg: value_to_string_opt(&values[0], "msg")?, + fatal: value_to_bool(&values[1], "fatal")?, + data: none_if_nil(values[2].clone()), + }) + } +} + +impl MessageBase for ErrorMessage { + fn msg_type(&self) -> u16 { + MSG_TYPE_ERROR + } + + fn pack(&self) -> Vec { + encode_value(&Value::Array(vec![ + string_opt_to_value(self.msg.as_deref()), + Value::Boolean(self.fatal), + self.data.clone().unwrap_or(Value::Nil), + ])) + .expect("rnsh error msgpack encode") + } + + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + *self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CommandExitedMessage { + pub return_code: i64, +} + +impl CommandExitedMessage { + pub fn new(return_code: i64) -> Self { + Self { return_code } + } + + pub fn unpack_payload(raw: &[u8]) -> Result { + let value = decode_value(raw)?; + let return_code = value_to_i64(&value, "return_code")?; + Ok(Self { return_code }) + } +} + +impl MessageBase for CommandExitedMessage { + fn msg_type(&self) -> u16 { + MSG_TYPE_COMMAND_EXITED + } + + fn pack(&self) -> Vec { + encode_value(&Value::from(self.return_code)).expect("rnsh command exited msgpack encode") + } + + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + *self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum RnshMessage { + Noop(NoopMessage), + WindowSize(WindowSizeMessage), + ExecuteCommand(ExecuteCommandMessage), + StreamData(RnshStreamDataMessage), + VersionInfo(VersionInfoMessage), + Error(ErrorMessage), + CommandExited(CommandExitedMessage), +} + +impl RnshMessage { + pub fn decode(msg_type: u16, payload: &[u8]) -> Result { + match msg_type { + MSG_TYPE_NOOP => Ok(Self::Noop(NoopMessage)), + MSG_TYPE_WINDOW_SIZE => Ok(Self::WindowSize(WindowSizeMessage::unpack_payload( + payload, + )?)), + MSG_TYPE_EXECUTE_COMMAND => Ok(Self::ExecuteCommand( + ExecuteCommandMessage::unpack_payload(payload)?, + )), + MSG_TYPE_STREAM_DATA => Ok(Self::StreamData(RnshStreamDataMessage::unpack_payload( + payload, + )?)), + MSG_TYPE_VERSION_INFO => Ok(Self::VersionInfo(VersionInfoMessage::unpack_payload( + payload, + )?)), + MSG_TYPE_ERROR => Ok(Self::Error(ErrorMessage::unpack_payload(payload)?)), + MSG_TYPE_COMMAND_EXITED => Ok(Self::CommandExited( + CommandExitedMessage::unpack_payload(payload)?, + )), + other => Err(RnshCodecError::UnknownMessageType(other)), + } + } + + pub fn msg_type(&self) -> u16 { + match self { + Self::Noop(msg) => msg.msg_type(), + Self::WindowSize(msg) => msg.msg_type(), + Self::ExecuteCommand(msg) => msg.msg_type(), + Self::StreamData(msg) => msg.msg_type(), + Self::VersionInfo(msg) => msg.msg_type(), + Self::Error(msg) => msg.msg_type(), + Self::CommandExited(msg) => msg.msg_type(), + } + } + + pub fn pack(&self) -> Vec { + match self { + Self::Noop(msg) => msg.pack(), + Self::WindowSize(msg) => msg.pack(), + Self::ExecuteCommand(msg) => msg.pack(), + Self::StreamData(msg) => msg.pack(), + Self::VersionInfo(msg) => msg.pack(), + Self::Error(msg) => msg.pack(), + Self::CommandExited(msg) => msg.pack(), + } + } +} + +fn encode_value(value: &Value) -> Result, RnshCodecError> { + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, value) + .map_err(|e| RnshCodecError::Encode(e.to_string()))?; + Ok(buf) +} + +fn decode_value(raw: &[u8]) -> Result { + let mut cursor = Cursor::new(raw); + let value = + rmpv::decode::read_value(&mut cursor).map_err(|e| RnshCodecError::Decode(e.to_string()))?; + if cursor.position() as usize != raw.len() { + return Err(RnshCodecError::InvalidShape("trailing msgpack bytes")); + } + Ok(value) +} + +fn decode_array( + raw: &[u8], + expected_len: usize, + name: &'static str, +) -> Result, RnshCodecError> { + let value = decode_value(raw)?; + match value { + Value::Array(items) if items.len() == expected_len => Ok(items), + _ => Err(RnshCodecError::InvalidShape(name)), + } +} + +fn none_if_nil(value: Value) -> Option { + if matches!(value, Value::Nil) { + None + } else { + Some(value) + } +} + +fn u32_opt_to_value(value: Option) -> Value { + value.map(Value::from).unwrap_or(Value::Nil) +} + +fn string_to_value(value: &str) -> Value { + Value::String(rmpv::Utf8String::from(value)) +} + +fn string_opt_to_value(value: Option<&str>) -> Value { + value.map(string_to_value).unwrap_or(Value::Nil) +} + +fn string_vec_opt_to_value(value: Option<&Vec>) -> Value { + value + .map(|items| Value::Array(items.iter().map(|s| string_to_value(s)).collect())) + .unwrap_or(Value::Nil) +} + +fn value_to_bool(value: &Value, field: &'static str) -> Result { + value.as_bool().ok_or(RnshCodecError::InvalidShape(field)) +} + +fn value_to_u32_opt(value: &Value, field: &'static str) -> Result, RnshCodecError> { + if matches!(value, Value::Nil) { + return Ok(None); + } + let number = value_to_u64(value, field)?; + if number > u32::MAX as u64 { + return Err(RnshCodecError::InvalidShape(field)); + } + Ok(Some(number as u32)) +} + +fn value_to_u64(value: &Value, field: &'static str) -> Result { + if let Some(number) = value.as_u64() { + return Ok(number); + } + if let Some(number) = value.as_i64() + && number >= 0 + { + return Ok(number as u64); + } + Err(RnshCodecError::InvalidShape(field)) +} + +fn value_to_i64(value: &Value, field: &'static str) -> Result { + if let Some(number) = value.as_i64() { + return Ok(number); + } + if let Some(number) = value.as_u64() + && number <= i64::MAX as u64 + { + return Ok(number as i64); + } + Err(RnshCodecError::InvalidShape(field)) +} + +fn value_to_string(value: &Value, field: &'static str) -> Result { + value_to_string_opt(value, field)?.ok_or(RnshCodecError::InvalidShape(field)) +} + +fn value_to_string_opt( + value: &Value, + field: &'static str, +) -> Result, RnshCodecError> { + match value { + Value::Nil => Ok(None), + Value::String(s) => Ok(Some( + s.as_str().ok_or(RnshCodecError::InvalidUtf8)?.to_string(), + )), + Value::Binary(b) => String::from_utf8(b.clone()) + .map(Some) + .map_err(|_| RnshCodecError::InvalidUtf8), + _ => Err(RnshCodecError::InvalidShape(field)), + } +} + +fn value_to_string_vec_opt( + value: &Value, + field: &'static str, +) -> Result>, RnshCodecError> { + match value { + Value::Nil => Ok(None), + Value::Array(items) => items + .iter() + .map(|item| value_to_string(item, field)) + .collect::, _>>() + .map(Some), + _ => Err(RnshCodecError::InvalidShape(field)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::channel::Envelope; + + #[test] + fn msg_type_constants_match_python_magic() { + assert_eq!(MSG_TYPE_NOOP, 0xAC00); + assert_eq!(MSG_TYPE_WINDOW_SIZE, 0xAC02); + assert_eq!(MSG_TYPE_EXECUTE_COMMAND, 0xAC03); + assert_eq!(MSG_TYPE_STREAM_DATA, 0xAC04); + assert_eq!(MSG_TYPE_VERSION_INFO, 0xAC05); + assert_eq!(MSG_TYPE_ERROR, 0xAC06); + assert_eq!(MSG_TYPE_COMMAND_EXITED, 0xAC07); + assert_eq!(PROTOCOL_VERSION, 1); + } + + #[test] + fn noop_envelope_vector_is_python_compatible() { + let msg = NoopMessage; + let env = Envelope::pack(&msg, 0x1234); + assert_eq!(env.raw, [0xAC, 0x00, 0x12, 0x34, 0x00, 0x00]); + } + + #[test] + fn window_size_msgpack_vector_roundtrips() { + let msg = WindowSizeMessage::new(Some(24), Some(80), None, None); + let expected = [0x94, 0x18, 0x50, 0xC0, 0xC0]; + assert_eq!(msg.pack(), expected); + assert_eq!(WindowSizeMessage::unpack_payload(&expected).unwrap(), msg); + } + + #[test] + fn window_size_all_fields_vector_roundtrips() { + let msg = WindowSizeMessage::new(Some(40), Some(120), Some(1920), Some(1080)); + let expected = [0x94, 0x28, 0x78, 0xCD, 0x07, 0x80, 0xCD, 0x04, 0x38]; + assert_eq!(msg.pack(), expected); + assert_eq!(WindowSizeMessage::unpack_payload(&expected).unwrap(), msg); + } + + #[test] + fn execute_command_msgpack_vector_roundtrips() { + let msg = ExecuteCommandMessage::new( + Some(vec!["sh".into(), "-lc".into(), "echo hi".into()]), + true, + true, + true, + None, + Some("xterm".into()), + Some(24), + Some(80), + None, + None, + ); + let expected = [ + 0x9A, 0x93, 0xA2, b's', b'h', 0xA3, b'-', b'l', b'c', 0xA7, b'e', b'c', b'h', b'o', + b' ', b'h', b'i', 0xC3, 0xC3, 0xC3, 0xC0, 0xA5, b'x', b't', b'e', b'r', b'm', 0x18, + 0x50, 0xC0, 0xC0, + ]; + assert_eq!(msg.pack(), expected); + assert_eq!( + ExecuteCommandMessage::unpack_payload(&expected).unwrap(), + msg + ); + } + + #[test] + fn stream_data_vector_roundtrips() { + let msg = RnshStreamDataMessage::new(STREAM_ID_STDOUT, b"hi".to_vec(), false); + let expected = [0x00, 0x01, b'h', b'i']; + assert_eq!(msg.pack(), expected); + assert_eq!( + RnshStreamDataMessage::unpack_payload(&expected).unwrap(), + msg + ); + + let eof = RnshStreamDataMessage::new(STREAM_ID_STDIN, Vec::new(), true); + assert_eq!(eof.pack(), [0x80, 0x00]); + } + + #[test] + fn compressed_stream_data_payload_is_decompressed_on_unpack() { + let data = b"rnsh stream compression".repeat(200); + let compressed = compression::bz2_compress(&data).unwrap(); + let mut raw = vec![0xC0, 0x01]; + raw.extend_from_slice(&compressed); + + let unpacked = RnshStreamDataMessage::unpack_payload(&raw).unwrap(); + assert_eq!(unpacked.stream_id, STREAM_ID_STDOUT); + assert!(unpacked.eof); + assert!(unpacked.compressed); + assert_eq!(unpacked.data, data); + } + + #[test] + fn version_info_msgpack_and_envelope_vectors_roundtrip() { + let msg = VersionInfoMessage::new("0.9.0"); + let payload = [0x92, 0xA5, b'0', b'.', b'9', b'.', b'0', 0x01]; + assert_eq!(msg.pack(), payload); + assert_eq!(VersionInfoMessage::unpack_payload(&payload).unwrap(), msg); + + let env = Envelope::pack(&msg, 7); + let expected = [ + 0xAC, 0x05, 0x00, 0x07, 0x00, 0x08, 0x92, 0xA5, b'0', b'.', b'9', b'.', b'0', 0x01, + ]; + assert_eq!(env.raw, expected); + } + + #[test] + fn error_and_exit_vectors_roundtrip() { + let error = ErrorMessage::new(Some("boom".into()), true, None); + let error_payload = [0x93, 0xA4, b'b', b'o', b'o', b'm', 0xC3, 0xC0]; + assert_eq!(error.pack(), error_payload); + assert_eq!(ErrorMessage::unpack_payload(&error_payload).unwrap(), error); + + let exited = CommandExitedMessage::new(0); + assert_eq!(exited.pack(), [0x00]); + assert_eq!( + CommandExitedMessage::unpack_payload(&[0x00]).unwrap(), + exited + ); + } + + #[test] + fn decode_dispatches_by_msg_type() { + let payload = VersionInfoMessage::new("0.9.0").pack(); + let decoded = RnshMessage::decode(MSG_TYPE_VERSION_INFO, &payload).unwrap(); + assert!(matches!(decoded, RnshMessage::VersionInfo(_))); + assert!(RnshMessage::decode(0xAC08, &[]).is_err()); + } +} diff --git a/crates/rns-protocol/src/stream_data.rs b/crates/rns-protocol/src/stream_data.rs new file mode 100644 index 0000000..266a7ee --- /dev/null +++ b/crates/rns-protocol/src/stream_data.rs @@ -0,0 +1,201 @@ +use crate::buffer::MAX_CHUNK_LEN; +use crate::channel_message::{ChannelMessageError, MessageBase, SMT_STREAM_DATA}; +use crate::compression; + +/// Maximum stream ID value (14 bits). +pub const STREAM_ID_MAX: u16 = 0x3FFF; + +/// StreamDataMessage overhead: 2-byte header + 6-byte channel envelope = 8 bytes. +pub const OVERHEAD: usize = 8; + +/// Stream frame for the Buffer protocol. +/// +/// Wire layout (2-byte big-endian header followed by payload): +/// - bit 15: EOF flag +/// - bit 14: compressed flag (payload is bz2) +/// - bits 13..0: stream ID (0..=16_383) +#[derive(Debug, Clone)] +pub struct StreamDataMessage { + pub stream_id: u16, + pub eof: bool, + pub compressed: bool, + pub data: Vec, +} + +impl StreamDataMessage { + pub fn new(stream_id: u16, data: Vec, eof: bool) -> Self { + Self { + stream_id: stream_id & STREAM_ID_MAX, + eof, + compressed: false, + data, + } + } + + fn header_value(&self) -> u16 { + let mut val = self.stream_id & STREAM_ID_MAX; + if self.eof { + val |= 0x8000; + } + if self.compressed { + val |= 0x4000; + } + val + } + + fn parse_header(val: u16) -> (u16, bool, bool) { + let eof = (val & 0x8000) != 0; + let compressed = (val & 0x4000) != 0; + let stream_id = val & STREAM_ID_MAX; + (stream_id, eof, compressed) + } +} + +impl MessageBase for StreamDataMessage { + fn msg_type(&self) -> u16 { + SMT_STREAM_DATA + } + + fn pack(&self) -> Vec { + let header = self.header_value(); + let header_bytes = header.to_be_bytes(); + let mut result = Vec::with_capacity(2 + self.data.len()); + result.extend_from_slice(&header_bytes); + result.extend_from_slice(&self.data); + result + } + + fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> { + if raw.len() < 2 { + return Err(ChannelMessageError::TooShort); + } + + let header_val = u16::from_be_bytes([raw[0], raw[1]]); + let (stream_id, eof, compressed) = Self::parse_header(header_val); + + self.stream_id = stream_id; + self.eof = eof; + self.compressed = compressed; + + let payload = &raw[2..]; + if compressed && !payload.is_empty() { + // Mirror Python `Buffer.py:96`: cap decompression at MAX_CHUNK_LEN + // (16 KiB) so a malicious peer can't expand a tiny bz2 payload into + // a large allocation. The streaming hard-cap in `bz2_decompress` + // returns an error rather than completing the allocation. + self.data = compression::bz2_decompress(payload, MAX_CHUNK_LEN) + .map_err(|_| ChannelMessageError::UnpackFailed)?; + } else { + self.data = payload.to_vec(); + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pack_unpack_roundtrip() { + let msg = StreamDataMessage::new(42, b"hello stream".to_vec(), false); + let packed = msg.pack(); + + let mut msg2 = StreamDataMessage::new(0, Vec::new(), false); + msg2.unpack(&packed).unwrap(); + + assert_eq!(msg2.stream_id, 42); + assert!(!msg2.eof); + assert!(!msg2.compressed); + assert_eq!(msg2.data, b"hello stream"); + } + + #[test] + fn test_eof_flag() { + let msg = StreamDataMessage::new(1, Vec::new(), true); + let packed = msg.pack(); + + let mut msg2 = StreamDataMessage::new(0, Vec::new(), false); + msg2.unpack(&packed).unwrap(); + + assert!(msg2.eof); + assert_eq!(msg2.stream_id, 1); + } + + #[test] + fn test_stream_id_mask() { + // IDs above 14 bits must wrap, not overflow into the flag bits. + let msg = StreamDataMessage::new(0xFFFF, b"test".to_vec(), false); + assert_eq!(msg.stream_id, STREAM_ID_MAX); + } + + #[test] + fn test_header_bits() { + let msg = StreamDataMessage { + stream_id: 100, + eof: true, + compressed: true, + data: Vec::new(), + }; + let packed = msg.pack(); + let header = u16::from_be_bytes([packed[0], packed[1]]); + assert_eq!(header & 0x3FFF, 100); + assert!(header & 0x8000 != 0); + assert!(header & 0x4000 != 0); + } + + #[test] + fn test_too_short() { + let mut msg = StreamDataMessage::new(0, Vec::new(), false); + assert!(msg.unpack(&[0x00]).is_err()); + } + + /// Regression for A2026-04.P-01: Buffer-protocol decompression must cap at + /// `MAX_CHUNK_LEN` (16 KiB), matching Python `Buffer.py:96`. A bz2 payload + /// that decompresses past that bound is a compression-bomb attack and must + /// be rejected rather than amplified into a large allocation. + #[test] + fn test_decompression_bounded_at_max_chunk_len() { + // Build a payload that bz2-compresses small but expands past the cap. + let big = vec![0u8; MAX_CHUNK_LEN + 1024]; + let compressed = compression::bz2_compress(&big).expect("compress"); + assert!( + compressed.len() < big.len(), + "test premise: compressed < raw" + ); + + // Hand-pack: header with compressed=true, stream_id=1. + let header_val: u16 = 0x4000 | 0x0001; + let mut packed = Vec::with_capacity(2 + compressed.len()); + packed.extend_from_slice(&header_val.to_be_bytes()); + packed.extend_from_slice(&compressed); + + let mut msg = StreamDataMessage::new(0, Vec::new(), false); + let result = msg.unpack(&packed); + assert!( + result.is_err(), + "compressed payload that decompresses past MAX_CHUNK_LEN must be rejected" + ); + } + + /// Companion: a compressed payload that fits inside `MAX_CHUNK_LEN` after + /// decompression must round-trip cleanly. Guards against an over-tight bound. + #[test] + fn test_decompression_under_bound_succeeds() { + let small = vec![0u8; MAX_CHUNK_LEN - 256]; + let compressed = compression::bz2_compress(&small).expect("compress"); + + let header_val: u16 = 0x4000 | 0x0007; + let mut packed = Vec::with_capacity(2 + compressed.len()); + packed.extend_from_slice(&header_val.to_be_bytes()); + packed.extend_from_slice(&compressed); + + let mut msg = StreamDataMessage::new(0, Vec::new(), false); + msg.unpack(&packed) + .expect("payload within bound must decode"); + assert_eq!(msg.data.len(), small.len()); + assert_eq!(msg.stream_id, 7); + assert!(msg.compressed); + } +} diff --git a/crates/rns-ratkey/Cargo.toml b/crates/rns-ratkey/Cargo.toml new file mode 100644 index 0000000..9df2b2b --- /dev/null +++ b/crates/rns-ratkey/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "rns-ratkey" +description = "Hardware-backed identity (YubiKey/Nitrokey PIV) for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +rns-crypto = { workspace = true, features = ["std"] } +rns-identity = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } +hex = { workspace = true } +zeroize = { workspace = true } +toml = "0.8" + +[dev-dependencies] +rns-crypto = { workspace = true, features = ["std"] } +rns-identity = { workspace = true } +rns-link = { path = "../rns-link" } + +[features] +default = [] +# Enable real hardware PIV session (requires pcsc system library) +hardware = ["dep:pcsc"] + +[dependencies.pcsc] +version = "2" +optional = true diff --git a/crates/rns-ratkey/HARDWARE_STATUS.md b/crates/rns-ratkey/HARDWARE_STATUS.md new file mode 100644 index 0000000..2dfc8d9 --- /dev/null +++ b/crates/rns-ratkey/HARDWARE_STATUS.md @@ -0,0 +1,23 @@ +# RatKey Hardware Status + +RatKey hardware identity support is intentionally not release-grade until it is +verified against real devices. The mock-backed tests cover public identity +shape, signing, ECDH, decrypt flow, and fail-closed key mismatch behavior, but +they do not prove PIV transport, touch/PIN policy, or X.509 chain verification. + +Required before hardware RatKey is documented as supported: + +- Replace the mock-only `HardwareIdentity` session storage with a real PIV + backend abstraction and YubiKey/Nitrokey implementations. +- Verify signing and ECDH against physical YubiKeys, including disconnect, + wrong PIN, touch timeout, and slot mismatch cases. +- Implement cryptographic attestation certificate chain verification against + the bundled Yubico roots and intermediates. +- Decide and document the ratchet policy for hardware identities. PIV cannot + hold Reticulum ratchet private keys, so enforced-ratchet decrypt currently + fails closed. +- Add hardware-gated tests that are skipped by default but run when a device is + explicitly selected by environment/config. + +Until those items pass on real devices, CLI/UI surfaces must label hardware +RatKey support as experimental. diff --git a/crates/rns-ratkey/certs/yubico-attestation-root-1.pem b/crates/rns-ratkey/certs/yubico-attestation-root-1.pem new file mode 100644 index 0000000..2a54d51 --- /dev/null +++ b/crates/rns-ratkey/certs/yubico-attestation-root-1.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDPjCCAiagAwIBAgIUXzeiEDJEOTt14F5n0o6Zf/bBwiUwDQYJKoZIhvcNAQEN +BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy +MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowJDEiMCAGA1UEAwwZWXViaWNvIEF0 +dGVzdGF0aW9uIFJvb3QgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AMZ6/TxM8rIT+EaoPvG81ontMOo/2mQ2RBwJHS0QZcxVaNXvl12LUhBZ5LmiBScI +Zd1Rnx1od585h+/dhK7hEm7JAALkKKts1fO53KGNLZujz5h3wGncr4hyKF0G74b/ +U3K9hE5mGND6zqYchCRAHfrYMYRDF4YL0X4D5nGdxvppAy6nkEmtWmMnwO3i0TAu +csrbE485HvGM4r0VpgVdJpvgQjiTJCTIq+D35hwtT8QDIv+nGvpcyi5wcIfCkzyC +imJukhYy6KoqNMKQEdpNiSOvWyDMTMt1bwCvEzpw91u+msUt4rj0efnO9s0ZOwdw +MRDnH4xgUl5ZLwrrPkfC1/0CAwEAAaNmMGQwHQYDVR0OBBYEFNLu71oijTptXCOX +PfKF1SbxJXuSMB8GA1UdIwQYMBaAFNLu71oijTptXCOXPfKF1SbxJXuSMBIGA1Ud +EwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBDQUAA4IB +AQC3IW/sgB9pZ8apJNjxuGoX+FkILks0wMNrdXL/coUvsrhzsvl6mePMrbGJByJ1 +XnquB5sgcRENFxdQFma3mio8Upf1owM1ZreXrJ0mADG2BplqbJnxiyYa+R11reIF +TWeIhMNcZKsDZrFAyPuFjCWSQvJmNWe9mFRYFgNhXJKkXIb5H1XgEDlwiedYRM7V +olBNlld6pRFKlX8ust6OTMOeADl2xNF0m1LThSdeuXvDyC1g9+ILfz3S6OIYgc3i +roRcFD354g7rKfu67qFAw9gC4yi0xBTPrY95rh4/HqaUYCA/L8ldRk6H7Xk35D+W +Vpmq2Sh/xT5HiFuhf4wJb0bK +-----END CERTIFICATE----- diff --git a/crates/rns-ratkey/certs/yubico-piv-root-ca-legacy.pem b/crates/rns-ratkey/certs/yubico-piv-root-ca-legacy.pem new file mode 100644 index 0000000..6874953 --- /dev/null +++ b/crates/rns-ratkey/certs/yubico-piv-root-ca-legacy.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1 +YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY +DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg +U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2 +cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E +ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq +joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH +BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf +wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet +X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0 +1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3 +DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s +XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2 +lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d +bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq +Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8 +SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7 +-----END CERTIFICATE----- diff --git a/crates/rns-ratkey/src/apdu.rs b/crates/rns-ratkey/src/apdu.rs new file mode 100644 index 0000000..c342ea6 --- /dev/null +++ b/crates/rns-ratkey/src/apdu.rs @@ -0,0 +1,685 @@ +//! PIV APDU build/parse. Specs: ISO 7816-4 (APDU), NIST SP 800-73-4 (PIV), +//! Yubico Ed25519 (0xE0) / X25519 (0xE1) extensions. +//! Ref: + +use crate::error::RatkeyError; + +/// NIST RID + PIV PIX. +pub const PIV_AID: &[u8] = &[0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x00]; + +pub const INS_SELECT: u8 = 0xA4; +pub const INS_VERIFY: u8 = 0x20; +pub const INS_CHANGE_REFERENCE: u8 = 0x24; +pub const INS_GENERAL_AUTHENTICATE: u8 = 0x87; +pub const INS_GENERATE_ASYMMETRIC: u8 = 0x47; +pub const INS_GET_DATA: u8 = 0xCB; +pub const INS_GET_METADATA: u8 = 0xF7; +pub const INS_ATTEST: u8 = 0xF9; +pub const INS_IMPORT_KEY: u8 = 0xFE; +pub const INS_GET_VERSION: u8 = 0xFD; +pub const INS_GET_SERIAL: u8 = 0xF8; + +// Algorithm IDs; ALG_ED25519/ALG_X25519 are YubiKey 5.7+ Yubico extensions. +pub const ALG_ED25519: u8 = 0xE0; +pub const ALG_X25519: u8 = 0xE1; +pub const ALG_ECCP256: u8 = 0x11; +pub const ALG_ECCP384: u8 = 0x14; + +pub const SLOT_AUTHENTICATION: u8 = 0x9A; +pub const SLOT_SIGNATURE: u8 = 0x9C; +pub const SLOT_KEY_MANAGEMENT: u8 = 0x9D; +pub const SLOT_CARD_AUTH: u8 = 0x9E; +pub const SLOT_ATTESTATION: u8 = 0xF9; + +pub const PIN_POLICY_NEVER: u8 = 0x01; +pub const PIN_POLICY_ONCE: u8 = 0x02; +pub const PIN_POLICY_ALWAYS: u8 = 0x03; + +pub const TOUCH_POLICY_NEVER: u8 = 0x01; +pub const TOUCH_POLICY_ALWAYS: u8 = 0x02; +pub const TOUCH_POLICY_CACHED: u8 = 0x03; + +const TAG_DYNAMIC_AUTH: u8 = 0x7C; +const TAG_AUTH_RESPONSE: u8 = 0x82; +const TAG_AUTH_CHALLENGE: u8 = 0x81; +const TAG_AUTH_EXPONENTIATION: u8 = 0x85; +const TAG_GEN_ALGORITHM: u8 = 0x80; +const TAG_PIN_POLICY: u8 = 0xAA; +const TAG_TOUCH_POLICY: u8 = 0xAB; +const TAG_OBJECT_ID: u8 = 0x5C; +const TAG_ECC_POINT: u8 = 0x86; + +/// Cert object ID for slot 9A (Authentication). +pub const OBJ_ID_9A: &[u8] = &[0x5F, 0xC1, 0x05]; +/// Cert object ID for slot 9D (Key Management). +pub const OBJ_ID_9D: &[u8] = &[0x5F, 0xC1, 0x0B]; + +pub fn slot_to_object_id(slot: u8) -> Option<&'static [u8]> { + match slot { + 0x9A => Some(OBJ_ID_9A), + 0x9D => Some(OBJ_ID_9D), + _ => None, + } +} + +// ISO 7816-4 APDU: CLA INS P1 P2 [Lc] [Data]. CLA=0x00 (no chaining, no secure messaging). +fn build_apdu(ins: u8, p1: u8, p2: u8, data: &[u8]) -> Vec { + let mut apdu = Vec::with_capacity(5 + data.len()); + apdu.push(0x00); + apdu.push(ins); + apdu.push(p1); + apdu.push(p2); + if !data.is_empty() { + if data.len() > 255 { + // Extended Lc: 0x00 + 2-byte BE length. + apdu.push(0x00); + apdu.push((data.len() >> 8) as u8); + apdu.push(data.len() as u8); + } else { + apdu.push(data.len() as u8); + } + apdu.extend_from_slice(data); + } + apdu +} + +fn tlv(tag: u8, value: &[u8]) -> Vec { + let mut out = Vec::with_capacity(4 + value.len()); + out.push(tag); + encode_der_length(value.len(), &mut out); + out.extend_from_slice(value); + out +} + +fn encode_der_length(len: usize, out: &mut Vec) { + if len < 128 { + out.push(len as u8); + } else if len < 256 { + out.push(0x81); + out.push(len as u8); + } else { + out.push(0x82); + out.push((len >> 8) as u8); + out.push(len as u8); + } +} + +pub fn select_piv() -> Vec { + build_apdu(INS_SELECT, 0x04, 0x00, PIV_AID) +} + +/// PIN is ASCII, 0xFF-padded to 8 bytes (NIST SP 800-73-4 §2.4.3). +pub fn verify_pin(pin: &str) -> Vec { + let mut pin_data = [0xFFu8; 8]; + let pin_bytes = pin.as_bytes(); + let copy_len = pin_bytes.len().min(8); + pin_data[..copy_len].copy_from_slice(&pin_bytes[..copy_len]); + build_apdu(INS_VERIFY, 0x00, 0x80, &pin_data) +} + +// CHANGE REFERENCE DATA. +pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec { + let mut data = [0xFFu8; 16]; + let old_bytes = old_pin.as_bytes(); + let new_bytes = new_pin.as_bytes(); + let old_len = old_bytes.len().min(8); + let new_len = new_bytes.len().min(8); + data[..old_len].copy_from_slice(&old_bytes[..old_len]); + data[8..8 + new_len].copy_from_slice(&new_bytes[..new_len]); + build_apdu(INS_CHANGE_REFERENCE, 0x00, 0x80, &data) +} + +// GENERATE ASYMMETRIC KEY PAIR (Ed25519/X25519). +pub fn generate_key( + slot: u8, + algorithm: u8, + pin_policy: Option, + touch_policy: Option, +) -> Vec { + let mut inner = tlv(TAG_GEN_ALGORITHM, &[algorithm]); + if let Some(pp) = pin_policy { + inner.extend_from_slice(&tlv(TAG_PIN_POLICY, &[pp])); + } + if let Some(tp) = touch_policy { + inner.extend_from_slice(&tlv(TAG_TOUCH_POLICY, &[tp])); + } + let data = tlv(0xAC, &inner); + build_apdu(INS_GENERATE_ASYMMETRIC, 0x00, slot, &data) +} + +/// GENERAL AUTHENTICATE Ed25519 sign. Send raw message — device does SHA-512 internally; no pre-hash. +pub fn sign_ed25519(slot: u8, message: &[u8]) -> Vec { + let challenge = tlv(TAG_AUTH_CHALLENGE, message); + // Empty response tag = request sig output. + let response_request = vec![TAG_AUTH_RESPONSE, 0x00]; + let mut inner = Vec::with_capacity(response_request.len() + challenge.len()); + inner.extend_from_slice(&response_request); + inner.extend_from_slice(&challenge); + let data = tlv(TAG_DYNAMIC_AUTH, &inner); + build_apdu(INS_GENERAL_AUTHENTICATE, ALG_ED25519, slot, &data) +} + +/// GENERAL AUTHENTICATE X25519 ECDH: peer 32-byte pubkey in, 32-byte shared secret out. +pub fn ecdh_x25519(slot: u8, peer_public_key: &[u8; 32]) -> Vec { + let exponentiation = tlv(TAG_AUTH_EXPONENTIATION, peer_public_key); + let response_request = vec![TAG_AUTH_RESPONSE, 0x00]; + let mut inner = Vec::with_capacity(response_request.len() + exponentiation.len()); + inner.extend_from_slice(&response_request); + inner.extend_from_slice(&exponentiation); + let data = tlv(TAG_DYNAMIC_AUTH, &inner); + build_apdu(INS_GENERAL_AUTHENTICATE, ALG_X25519, slot, &data) +} + +pub fn get_data(slot: u8) -> Option> { + let obj_id = slot_to_object_id(slot)?; + let data = tlv(TAG_OBJECT_ID, obj_id); + Some(build_apdu(INS_GET_DATA, 0x3F, 0xFF, &data)) +} + +pub fn get_metadata(slot: u8) -> Vec { + build_apdu(INS_GET_METADATA, 0x00, slot, &[]) +} + +/// Yubico proprietary; unsupported on Nitrokey 3. +pub fn get_version() -> Vec { + build_apdu(INS_GET_VERSION, 0x00, 0x00, &[]) +} + +/// Yubico proprietary; unsupported on Nitrokey 3. +pub fn get_serial() -> Vec { + build_apdu(INS_GET_SERIAL, 0x00, 0x00, &[]) +} + +pub fn attest_key(slot: u8) -> Vec { + build_apdu(INS_ATTEST, slot, 0x00, &[]) +} + +pub fn check_response(response: &[u8]) -> Result<&[u8], RatkeyError> { + if response.len() < 2 { + return Err(RatkeyError::Apdu { + sw1: 0x00, + sw2: 0x00, + }); + } + let sw1 = response[response.len() - 2]; + let sw2 = response[response.len() - 1]; + if sw1 == 0x90 && sw2 == 0x00 { + Ok(&response[..response.len() - 2]) + } else if sw1 == 0x63 && (sw2 & 0xF0) == 0xC0 { + // NIST SP 800-73-4 §2.4.3: low nibble of SW2 = retries remaining. + let remaining = sw2 & 0x0F; + if remaining == 0 { + Err(RatkeyError::PinLocked) + } else { + Err(RatkeyError::PinFailed { remaining }) + } + } else if sw1 == 0x69 && sw2 == 0x83 { + Err(RatkeyError::PinLocked) + } else { + Err(RatkeyError::Apdu { sw1, sw2 }) + } +} + +/// GENERATE ASYMMETRIC response: `7F49 86 20 <32 bytes>` → 32-byte public key. +pub fn parse_generate_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> { + let key_bytes = find_tlv_value(data, TAG_ECC_POINT).ok_or(RatkeyError::Apdu { + sw1: 0x6A, + sw2: 0x80, + })?; + if key_bytes.len() != 32 { + return Err(RatkeyError::InvalidHwid(format!( + "expected 32-byte public key, got {} bytes", + key_bytes.len() + ))); + } + let mut out = [0u8; 32]; + out.copy_from_slice(key_bytes); + Ok(out) +} + +/// GENERAL AUTHENTICATE response: `7C 82 40 <64 bytes>` → 64-byte Ed25519 sig. +pub fn parse_sign_response(data: &[u8]) -> Result<[u8; 64], RatkeyError> { + let sig_bytes = find_tlv_value(data, TAG_AUTH_RESPONSE).ok_or(RatkeyError::Apdu { + sw1: 0x6A, + sw2: 0x80, + })?; + if sig_bytes.len() != 64 { + return Err(RatkeyError::InvalidHwid(format!( + "expected 64-byte signature, got {} bytes", + sig_bytes.len() + ))); + } + let mut out = [0u8; 64]; + out.copy_from_slice(sig_bytes); + Ok(out) +} + +/// GET VERSION → (major, minor, patch). +pub fn parse_version_response(data: &[u8]) -> Result<(u8, u8, u8), RatkeyError> { + if data.len() != 3 { + return Err(RatkeyError::InvalidHwid(format!( + "expected 3-byte version, got {} bytes", + data.len() + ))); + } + Ok((data[0], data[1], data[2])) +} + +/// GET SERIAL → u32 (4-byte BE). +pub fn parse_serial_response(data: &[u8]) -> Result { + if data.len() != 4 { + return Err(RatkeyError::InvalidHwid(format!( + "expected 4-byte serial, got {} bytes", + data.len() + ))); + } + Ok(u32::from_be_bytes([data[0], data[1], data[2], data[3]])) +} + +/// X25519 ECDH response: `7C 82 20 <32 bytes>` → 32-byte shared secret. +pub fn parse_ecdh_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> { + let secret_bytes = find_tlv_value(data, TAG_AUTH_RESPONSE).ok_or(RatkeyError::Apdu { + sw1: 0x6A, + sw2: 0x80, + })?; + if secret_bytes.len() != 32 { + return Err(RatkeyError::InvalidHwid(format!( + "expected 32-byte shared secret, got {} bytes", + secret_bytes.len() + ))); + } + let mut out = [0u8; 32]; + out.copy_from_slice(secret_bytes); + Ok(out) +} + +// Recurse into 7C / AC / 53 / any 2-byte tag (7F49 etc) to find a single-byte tag. +fn find_tlv_value(data: &[u8], target_tag: u8) -> Option<&[u8]> { + let mut pos = 0; + while pos < data.len() { + let (tag_len, tag_first) = if pos < data.len() { + (1, data[pos]) + } else { + return None; + }; + + // 2-byte tags begin with 0x7F (e.g. 7F49 ECC pubkey). + let tag_bytes; + let tag_total_len; + if tag_first == 0x7F && pos + 1 < data.len() { + tag_bytes = 2; + tag_total_len = 2; + pos += 2; + } else { + tag_bytes = 1; + tag_total_len = 1; + let _ = tag_len; + pos += 1; + } + + if pos >= data.len() { + return None; + } + + let (value_len, len_bytes) = decode_der_length(&data[pos..])?; + pos += len_bytes; + + if pos + value_len > data.len() { + return None; + } + + let value = &data[pos..pos + value_len]; + + if tag_bytes == 1 && tag_first == target_tag { + return Some(value); + } + + if tag_first == TAG_DYNAMIC_AUTH + || tag_first == 0xAC + || tag_first == 0x53 + || (tag_total_len == 2) + { + if let Some(found) = find_tlv_value(value, target_tag) { + return Some(found); + } + } + + pos += value_len; + } + None +} + +fn decode_der_length(data: &[u8]) -> Option<(usize, usize)> { + if data.is_empty() { + return None; + } + let first = data[0]; + if first < 0x80 { + Some((first as usize, 1)) + } else if first == 0x81 { + if data.len() < 2 { + return None; + } + Some((data[1] as usize, 2)) + } else if first == 0x82 { + if data.len() < 3 { + return None; + } + Some((((data[1] as usize) << 8) | data[2] as usize, 3)) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_select_piv() { + let apdu = select_piv(); + assert_eq!( + apdu, + vec![ + 0x00, 0xA4, 0x04, 0x00, 0x09, 0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x00 + ] + ); + } + + #[test] + fn test_verify_pin_default() { + let apdu = verify_pin("123456"); + assert_eq!( + apdu, + vec![ + 0x00, 0x20, 0x00, 0x80, 0x08, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0xFF, 0xFF + ] + ); + } + + #[test] + fn test_verify_pin_full_length() { + let apdu = verify_pin("12345678"); + assert_eq!( + apdu, + vec![ + 0x00, 0x20, 0x00, 0x80, 0x08, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 + ] + ); + } + + #[test] + fn test_generate_ed25519_slot_9a() { + let apdu = generate_key(SLOT_AUTHENTICATION, ALG_ED25519, None, None); + assert_eq!( + apdu, + vec![0x00, 0x47, 0x00, 0x9A, 0x05, 0xAC, 0x03, 0x80, 0x01, 0xE0] + ); + } + + #[test] + fn test_generate_x25519_with_policies() { + let apdu = generate_key( + SLOT_KEY_MANAGEMENT, + ALG_X25519, + Some(PIN_POLICY_ONCE), + Some(TOUCH_POLICY_CACHED), + ); + // AC 09: 80 01 E1, AA 01 02, AB 01 03 + assert_eq!( + apdu, + vec![ + 0x00, 0x47, 0x00, 0x9D, 0x0B, 0xAC, 0x09, 0x80, 0x01, 0xE1, 0xAA, 0x01, 0x02, 0xAB, + 0x01, 0x03 + ] + ); + } + + #[test] + fn test_sign_ed25519_short_message() { + let message = [0xAA; 32]; + let apdu = sign_ed25519(SLOT_AUTHENTICATION, &message); + // Header: 00 87 E0 9A + assert_eq!(apdu[0], 0x00); // CLA + assert_eq!(apdu[1], 0x87); // INS = GENERAL AUTHENTICATE + assert_eq!(apdu[2], 0xE0); // P1 = Ed25519 + assert_eq!(apdu[3], 0x9A); // P2 = slot + // Data starts at [5]: 7C container + assert_eq!(apdu[5], 0x7C); // Dynamic Auth Template tag + // Inside 7C: 82 00, 81 20 <32 bytes> + // 82 00 = response request (2 bytes) + // 81 20 <32 bytes> = challenge (34 bytes) + // 7C length = 36 = 0x24 + assert_eq!(apdu[6], 0x24); // 7C length + assert_eq!(apdu[7], 0x82); // Response tag + assert_eq!(apdu[8], 0x00); // Empty (request) + assert_eq!(apdu[9], 0x81); // Challenge tag + assert_eq!(apdu[10], 0x20); // Challenge length (32) + assert_eq!(&apdu[11..43], &message); // Message data + assert_eq!(apdu.len(), 43); + } + + #[test] + fn test_sign_ed25519_empty_message() { + let apdu = sign_ed25519(SLOT_AUTHENTICATION, &[]); + assert_eq!(apdu[2], 0xE0); // P1 = Ed25519 + assert_eq!(apdu[9], 0x81); // Challenge tag + assert_eq!(apdu[10], 0x00); // Challenge length = 0 + } + + #[test] + fn test_ecdh_x25519() { + let peer_pub = [0xBB; 32]; + let apdu = ecdh_x25519(SLOT_KEY_MANAGEMENT, &peer_pub); + assert_eq!(apdu[0], 0x00); // CLA + assert_eq!(apdu[1], 0x87); // INS = GENERAL AUTHENTICATE + assert_eq!(apdu[2], 0xE1); // P1 = X25519 + assert_eq!(apdu[3], 0x9D); // P2 = Key Management slot + assert_eq!(apdu[5], 0x7C); // Dynamic Auth Template + assert_eq!(apdu[7], 0x82); // Response tag + assert_eq!(apdu[8], 0x00); // Empty (request) + assert_eq!(apdu[9], 0x85); // Exponentiation tag (NOT 0x81) + assert_eq!(apdu[10], 0x20); // Length = 32 + assert_eq!(&apdu[11..43], &peer_pub); + } + + #[test] + fn test_get_data_slot_9a() { + let apdu = get_data(SLOT_AUTHENTICATION).unwrap(); + assert_eq!( + apdu, + vec![0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, 0x03, 0x5F, 0xC1, 0x05] + ); + } + + #[test] + fn test_get_data_slot_9d() { + let apdu = get_data(SLOT_KEY_MANAGEMENT).unwrap(); + assert_eq!( + apdu, + vec![0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, 0x03, 0x5F, 0xC1, 0x0B] + ); + } + + #[test] + fn test_attest_slot_9a() { + let apdu = attest_key(SLOT_AUTHENTICATION); + assert_eq!(apdu, vec![0x00, 0xF9, 0x9A, 0x00]); + } + + #[test] + fn test_get_metadata() { + let apdu = get_metadata(SLOT_AUTHENTICATION); + assert_eq!(apdu, vec![0x00, 0xF7, 0x00, 0x9A]); + } + + #[test] + fn test_get_version_apdu() { + assert_eq!(get_version(), vec![0x00, 0xFD, 0x00, 0x00]); + } + + #[test] + fn test_get_serial_apdu() { + assert_eq!(get_serial(), vec![0x00, 0xF8, 0x00, 0x00]); + } + + #[test] + fn test_parse_version_response() { + assert_eq!( + parse_version_response(&[0x05, 0x07, 0x01]).unwrap(), + (5, 7, 1) + ); + } + + #[test] + fn test_parse_version_response_wrong_length() { + assert!(parse_version_response(&[0x05, 0x07]).is_err()); + assert!(parse_version_response(&[0x05, 0x07, 0x01, 0x00]).is_err()); + } + + #[test] + fn test_parse_serial_response() { + // 0x00BC614E = 12_345_678 + assert_eq!( + parse_serial_response(&[0x00, 0xBC, 0x61, 0x4E]).unwrap(), + 12_345_678 + ); + } + + #[test] + fn test_parse_serial_response_wrong_length() { + assert!(parse_serial_response(&[0x00, 0x01, 0x02]).is_err()); + } + + #[test] + fn test_change_pin() { + let apdu = change_pin("123456", "654321"); + assert_eq!(apdu[0], 0x00); // CLA + assert_eq!(apdu[1], 0x24); // INS = CHANGE REFERENCE + assert_eq!(apdu[2], 0x00); // P1 + assert_eq!(apdu[3], 0x80); // P2 = PIN + assert_eq!(apdu[4], 0x10); // Lc = 16 + // Old PIN: 31 32 33 34 35 36 FF FF + assert_eq!( + &apdu[5..13], + &[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0xFF, 0xFF] + ); + // New PIN: 36 35 34 33 32 31 FF FF + assert_eq!( + &apdu[13..21], + &[0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0xFF, 0xFF] + ); + } + + #[test] + fn test_check_response_success() { + let response = vec![0xAA, 0xBB, 0x90, 0x00]; + let data = check_response(&response).unwrap(); + assert_eq!(data, &[0xAA, 0xBB]); + } + + #[test] + fn test_check_response_pin_failed() { + let response = vec![0x63, 0xC2]; // 2 retries remaining + match check_response(&response) { + Err(RatkeyError::PinFailed { remaining }) => assert_eq!(remaining, 2), + other => panic!("expected PinFailed, got {other:?}"), + } + } + + #[test] + fn test_check_response_pin_locked() { + let response = vec![0x69, 0x83]; + assert!(matches!( + check_response(&response), + Err(RatkeyError::PinLocked) + )); + } + + #[test] + fn test_check_response_pin_locked_via_c0() { + let response = vec![0x63, 0xC0]; // 0 retries = locked + assert!(matches!( + check_response(&response), + Err(RatkeyError::PinLocked) + )); + } + + #[test] + fn test_parse_generate_response_ed25519() { + // 7F49 22 86 20 <32 bytes key> + let mut response = vec![0x7F, 0x49, 0x22, 0x86, 0x20]; + response.extend_from_slice(&[0xAA; 32]); + let key = parse_generate_response(&response).unwrap(); + assert_eq!(key, [0xAA; 32]); + } + + #[test] + fn test_parse_sign_response() { + // 7C 42 82 40 <64 bytes sig> + let mut response = vec![0x7C, 0x42, 0x82, 0x40]; + response.extend_from_slice(&[0xBB; 64]); + let sig = parse_sign_response(&response).unwrap(); + assert_eq!(sig, [0xBB; 64]); + } + + #[test] + fn test_parse_ecdh_response() { + // 7C 22 82 20 <32 bytes secret> + let mut response = vec![0x7C, 0x22, 0x82, 0x20]; + response.extend_from_slice(&[0xCC; 32]); + let secret = parse_ecdh_response(&response).unwrap(); + assert_eq!(secret, [0xCC; 32]); + } + + #[test] + fn test_parse_generate_response_wrong_size() { + let mut response = vec![0x7F, 0x49, 0x12, 0x86, 0x10]; + response.extend_from_slice(&[0xAA; 16]); + assert!(parse_generate_response(&response).is_err()); + } + + #[test] + fn test_der_length_short() { + let mut buf = Vec::new(); + encode_der_length(32, &mut buf); + assert_eq!(buf, vec![0x20]); + } + + #[test] + fn test_der_length_medium() { + let mut buf = Vec::new(); + encode_der_length(200, &mut buf); + assert_eq!(buf, vec![0x81, 0xC8]); + } + + #[test] + fn test_der_length_long() { + let mut buf = Vec::new(); + encode_der_length(500, &mut buf); + assert_eq!(buf, vec![0x82, 0x01, 0xF4]); + } + + #[test] + fn test_decode_der_length() { + assert_eq!(decode_der_length(&[0x20]), Some((32, 1))); + assert_eq!(decode_der_length(&[0x81, 0xC8]), Some((200, 2))); + assert_eq!(decode_der_length(&[0x82, 0x01, 0xF4]), Some((500, 3))); + } + + #[test] + fn test_sign_large_message_der_length() { + // >127 bytes: DER extended length (0x81 prefix). + let message = vec![0xAA; 200]; + let apdu = sign_ed25519(SLOT_AUTHENTICATION, &message); + let response_request_pos = apdu.iter().position(|&b| b == TAG_AUTH_RESPONSE).unwrap(); + let challenge_tag_pos = response_request_pos + 2; + assert_eq!(apdu[challenge_tag_pos], TAG_AUTH_CHALLENGE); + assert_eq!(apdu[challenge_tag_pos + 1], 0x81); + assert_eq!(apdu[challenge_tag_pos + 2], 200); + assert_eq!( + &apdu[challenge_tag_pos + 3..challenge_tag_pos + 3 + 200], + &message[..] + ); + } +} diff --git a/crates/rns-ratkey/src/attestation.rs b/crates/rns-ratkey/src/attestation.rs new file mode 100644 index 0000000..cc10089 --- /dev/null +++ b/crates/rns-ratkey/src/attestation.rs @@ -0,0 +1,445 @@ +//! YubiKey PIV attestation verification. Bundled root CAs — never fetched. +//! +//! Legacy chain (firmware < 5.7.4): +//! Yubico PIV Root CA Serial 263751 → device intermediate (slot F9) → per-key attestation cert. +//! +//! New chain (firmware >= 5.7.4): +//! Yubico Attestation Root 1 → Intermediate A/B 1 → PIV Attestation A/B 1 +//! → device intermediate (slot F9) → per-key attestation cert. +//! +//! Nitrokey 3 does not support PIV attestation (firmware 1.8) — verification skipped. +//! +//! Chain verification status: structural + OID extraction only. The +//! `verified` flag remains false until X.509 path validation is exercised +//! against real devices. See crates/rns-ratkey/HARDWARE_STATUS.md. + +use crate::error::RatkeyError; + +/// Yubico PIV Root CA (legacy, firmware < 5.7.4). Subject: "Yubico PIV Root CA Serial 263751". +pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str = + include_str!("../certs/yubico-piv-root-ca-legacy.pem"); + +/// Yubico Attestation Root 1 (firmware >= 5.7.4). Subject: "Yubico Attestation Root 1". +pub const YUBICO_ATTESTATION_ROOT_1_PEM: &str = + include_str!("../certs/yubico-attestation-root-1.pem"); + +/// SHA-256 fingerprint of the legacy Yubico PIV Root CA (belt-and-suspenders vs PEM swap). +pub const YUBICO_LEGACY_ROOT_SHA256: &str = + "63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced73833120785b546"; + +/// SHA-256 fingerprint of the new Yubico Attestation Root 1 (belt-and-suspenders vs PEM swap). +pub const YUBICO_NEW_ROOT_SHA256: &str = + "62760c6a6ef91679f454c8902b80fd009825b3f25da90f1fbace2ec6586cd5a8"; + +// Yubico PIV attestation OIDs. Yubico PEN: 1.3.6.1.4.1.41482; PIV attestation subtree: .3. + +/// Firmware version (3 bytes: major.minor.patch). +pub const OID_FIRMWARE_VERSION: &[u8] = + &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x03]; + +/// Serial number (INTEGER). +pub const OID_SERIAL_NUMBER: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x07]; + +/// Usage policy (2 bytes: pin_policy, touch_policy). +pub const OID_USAGE_POLICY: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x08]; + +/// Form factor (1 byte). +pub const OID_FORM_FACTOR: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x09]; + +#[derive(Debug, Clone)] +pub struct AttestationInfo { + pub firmware_version: Option<(u8, u8, u8)>, + pub serial_number: Option, + pub pin_policy: Option, + pub touch_policy: Option, + pub form_factor: Option, + pub attestation_cert_der: Vec, + /// Device intermediate (slot F9) DER. + pub device_cert_der: Vec, +} + +#[derive(Debug, Clone)] +pub struct AttestationVerification { + /// True only when the attestation certificate chain has been + /// cryptographically verified to a bundled trusted root. + pub verified: bool, + /// True when Yubico attestation metadata could be extracted from the cert. + pub metadata_extracted: bool, + /// Explicit chain-verification label for UI/CLI surfaces. + pub chain_verified: bool, + pub info: AttestationInfo, + /// "legacy" or "new". + pub root_ca: String, + pub description: String, +} + +/// Verify chain: attestation cert (from ATTEST) + device intermediate (slot F9). +/// Currently structural + OID extraction only. +pub fn verify_attestation( + attestation_cert_der: &[u8], + device_cert_der: &[u8], +) -> Result { + let info = extract_attestation_info(attestation_cert_der, device_cert_der)?; + + let metadata_extracted = info.firmware_version.is_some(); + let chain_verified = false; + let root_ca = if let Some((major, minor, patch)) = info.firmware_version { + if major > 5 || (major == 5 && minor >= 7 && patch >= 4) { + "new".to_string() + } else { + "legacy".to_string() + } + } else { + "unknown".to_string() + }; + + let description = if metadata_extracted { + let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0)); + format!( + "YubiKey firmware {maj}.{min}.{pat}{}; attestation chain not cryptographically verified", + info.serial_number + .map(|s| format!(", serial {s}")) + .unwrap_or_default() + ) + } else { + "could not extract YubiKey attestation metadata".to_string() + }; + + Ok(AttestationVerification { + verified: chain_verified, + metadata_extracted, + chain_verified, + info, + root_ca, + description, + }) +} + +/// YubiKey 5 (firmware >= 4.3.0) only. Nitrokey 3 has no PIV attestation. +pub fn supports_attestation(device_type: &str) -> bool { + device_type == "yubikey5" +} + +fn extract_attestation_info( + attestation_cert_der: &[u8], + device_cert_der: &[u8], +) -> Result { + let firmware = find_oid_value(attestation_cert_der, OID_FIRMWARE_VERSION).and_then(|v| { + if v.len() >= 3 { + Some((v[0], v[1], v[2])) + } else { + None + } + }); + + let serial = find_oid_value(attestation_cert_der, OID_SERIAL_NUMBER) + .and_then(|v| parse_asn1_integer(&v)); + + let (pin_policy, touch_policy) = find_oid_value(attestation_cert_der, OID_USAGE_POLICY) + .map(|v| { + let pp = v.first().copied(); + let tp = v.get(1).copied(); + (pp, tp) + }) + .unwrap_or((None, None)); + + let form_factor = + find_oid_value(attestation_cert_der, OID_FORM_FACTOR).and_then(|v| v.first().copied()); + + Ok(AttestationInfo { + firmware_version: firmware, + serial_number: serial, + pin_policy, + touch_policy, + form_factor, + attestation_cert_der: attestation_cert_der.to_vec(), + device_cert_der: device_cert_der.to_vec(), + }) +} + +// Byte-scan DER for OID pattern, return TLV value after it. Avoids full ASN.1 parser dependency. +fn find_oid_value(der: &[u8], oid_bytes: &[u8]) -> Option> { + let oid_with_tag = { + let mut v = Vec::with_capacity(2 + oid_bytes.len()); + v.push(0x06); // OID tag + v.push(oid_bytes.len() as u8); + v.extend_from_slice(oid_bytes); + v + }; + + let pos = der + .windows(oid_with_tag.len()) + .position(|w| w == oid_with_tag.as_slice())?; + + let after_oid = pos + oid_with_tag.len(); + if after_oid >= der.len() { + return None; + } + + let tag = der[after_oid]; + if after_oid + 1 >= der.len() { + return None; + } + + let (value_len, len_bytes) = decode_der_length(&der[after_oid + 1..])?; + let value_start = after_oid + 1 + len_bytes; + let value_end = value_start + value_len; + + if value_end > der.len() { + return None; + } + + let value = &der[value_start..value_end]; + + // Unwrap one level if OCTET STRING wraps another OCTET STRING or INTEGER. + if tag == 0x04 && value.len() >= 2 { + let inner_tag = value[0]; + if inner_tag == 0x04 || inner_tag == 0x02 { + if let Some((inner_len, inner_len_bytes)) = decode_der_length(&value[1..]) { + let inner_start = 1 + inner_len_bytes; + if inner_start + inner_len <= value.len() { + return Some(value[inner_start..inner_start + inner_len].to_vec()); + } + } + } + return Some(value.to_vec()); + } + + Some(value.to_vec()) +} + +fn parse_asn1_integer(bytes: &[u8]) -> Option { + if bytes.is_empty() || bytes.len() > 4 { + return None; + } + let mut result: u32 = 0; + for &b in bytes { + result = result.checked_shl(8)?.checked_add(b as u32)?; + } + Some(result) +} + +fn decode_der_length(data: &[u8]) -> Option<(usize, usize)> { + if data.is_empty() { + return None; + } + let first = data[0]; + if first < 0x80 { + Some((first as usize, 1)) + } else if first == 0x81 { + data.get(1).map(|&b| (b as usize, 2)) + } else if first == 0x82 { + if data.len() < 3 { + return None; + } + Some((((data[1] as usize) << 8) | data[2] as usize, 3)) + } else { + None + } +} + +pub fn pem_to_der(pem: &str) -> Option> { + let lines: Vec<&str> = pem.lines().filter(|l| !l.starts_with("-----")).collect(); + let b64: String = lines.join(""); + base64_decode(&b64) +} + +// Standard alphabet, padding optional. +fn base64_decode(input: &str) -> Option> { + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + fn val(c: u8) -> Option { + TABLE.iter().position(|&b| b == c).map(|p| p as u8) + } + + let bytes: Vec = input + .bytes() + .filter(|&b| b != b'=' && b != b'\n' && b != b'\r' && b != b' ') + .collect(); + let mut out = Vec::with_capacity(bytes.len() * 3 / 4); + let mut i = 0; + while i + 3 < bytes.len() { + let a = val(bytes[i])?; + let b = val(bytes[i + 1])?; + let c = val(bytes[i + 2])?; + let d = val(bytes[i + 3])?; + out.push((a << 2) | (b >> 4)); + out.push((b << 4) | (c >> 2)); + out.push((c << 6) | d); + i += 4; + } + let remaining = bytes.len() - i; + if remaining >= 2 { + let a = val(bytes[i])?; + let b = val(bytes[i + 1])?; + out.push((a << 2) | (b >> 4)); + if remaining >= 3 { + let c = val(bytes[i + 2])?; + out.push((b << 4) | (c >> 2)); + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_legacy_root_ca_loads() { + let der = pem_to_der(YUBICO_PIV_ROOT_CA_LEGACY_PEM); + assert!(der.is_some(), "legacy root CA PEM should decode"); + let der = der.unwrap(); + assert!(der.len() > 500, "DER should be substantial"); + // DER starts with SEQUENCE tag (0x30) + assert_eq!(der[0], 0x30, "DER must start with SEQUENCE tag"); + } + + #[test] + fn test_new_root_ca_loads() { + let der = pem_to_der(YUBICO_ATTESTATION_ROOT_1_PEM); + assert!(der.is_some(), "new root CA PEM should decode"); + let der = der.unwrap(); + assert!(der.len() > 500); + assert_eq!(der[0], 0x30); + } + + #[test] + fn test_pem_to_der_roundtrip() { + let pem = "-----BEGIN CERTIFICATE-----\nTUlJ\n-----END CERTIFICATE-----\n"; + let der = pem_to_der(pem); + assert!(der.is_some()); + } + + #[test] + fn test_supports_attestation() { + assert!(supports_attestation("yubikey5")); + assert!(!supports_attestation("nitrokey3")); + assert!(!supports_attestation("unknown")); + } + + #[test] + fn test_parse_asn1_integer() { + assert_eq!(parse_asn1_integer(&[0x01]), Some(1)); + assert_eq!(parse_asn1_integer(&[0x00, 0xFF]), Some(255)); + assert_eq!(parse_asn1_integer(&[0x01, 0x00, 0x00]), Some(65536)); + assert_eq!(parse_asn1_integer(&[]), None); + assert_eq!(parse_asn1_integer(&[0x01, 0x02, 0x03, 0x04, 0x05]), None); // > 4 bytes + } + + #[test] + fn test_find_oid_in_synthetic_der() { + // Build a minimal DER structure containing a Yubico firmware OID + // SEQUENCE { OID(firmware) OCTET_STRING(3 bytes: 05 07 01) } + let mut der = Vec::new(); + // Outer SEQUENCE + let mut inner = Vec::new(); + // OID tag + length + firmware OID bytes + inner.push(0x06); // OID tag + inner.push(OID_FIRMWARE_VERSION.len() as u8); + inner.extend_from_slice(OID_FIRMWARE_VERSION); + // OCTET STRING with firmware version 5.7.1 + inner.push(0x04); // OCTET STRING tag + inner.push(0x03); // length = 3 + inner.push(0x05); // major = 5 + inner.push(0x07); // minor = 7 + inner.push(0x01); // patch = 1 + + der.push(0x30); // SEQUENCE tag + der.push(inner.len() as u8); + der.extend_from_slice(&inner); + + let value = find_oid_value(&der, OID_FIRMWARE_VERSION); + assert!(value.is_some(), "should find firmware OID"); + let v = value.unwrap(); + assert_eq!(v, vec![0x05, 0x07, 0x01], "firmware should be 5.7.1"); + } + + #[test] + fn test_find_oid_serial_number() { + // Build DER with serial number OID + let mut der = Vec::new(); + let mut inner = Vec::new(); + inner.push(0x06); + inner.push(OID_SERIAL_NUMBER.len() as u8); + inner.extend_from_slice(OID_SERIAL_NUMBER); + // INTEGER with serial 12345678 = 0x00BC614E + inner.push(0x02); // INTEGER tag + inner.push(0x04); // length = 4 + inner.extend_from_slice(&[0x00, 0xBC, 0x61, 0x4E]); + + der.push(0x30); + der.push(inner.len() as u8); + der.extend_from_slice(&inner); + + let value = find_oid_value(&der, OID_SERIAL_NUMBER); + assert!(value.is_some()); + let serial = parse_asn1_integer(&value.unwrap()); + assert_eq!(serial, Some(12345678)); + } + + #[test] + fn test_verify_attestation_synthetic() { + // Build a minimal attestation cert with firmware OID + let mut attest_der = Vec::new(); + let mut inner = Vec::new(); + inner.push(0x06); + inner.push(OID_FIRMWARE_VERSION.len() as u8); + inner.extend_from_slice(OID_FIRMWARE_VERSION); + inner.push(0x04); + inner.push(0x03); + inner.extend_from_slice(&[0x05, 0x07, 0x01]); // 5.7.1 + + attest_der.push(0x30); + attest_der.push(inner.len() as u8); + attest_der.extend_from_slice(&inner); + + // Minimal device cert (just a SEQUENCE) + let device_der = vec![0x30, 0x00]; + + let result = verify_attestation(&attest_der, &device_der).unwrap(); + assert!(result.metadata_extracted); + assert!(!result.verified); + assert!(!result.chain_verified); + assert_eq!(result.root_ca, "legacy"); // 5.7.1 < 5.7.4 + assert!(result.description.contains("5.7.1")); + assert!( + result + .description + .contains("not cryptographically verified") + ); + } + + #[test] + fn test_verify_attestation_new_firmware_metadata_only() { + let mut attest_der = Vec::new(); + let mut inner = Vec::new(); + inner.push(0x06); + inner.push(OID_FIRMWARE_VERSION.len() as u8); + inner.extend_from_slice(OID_FIRMWARE_VERSION); + inner.push(0x04); + inner.push(0x03); + inner.extend_from_slice(&[0x05, 0x07, 0x04]); // 5.7.4 + + attest_der.push(0x30); + attest_der.push(inner.len() as u8); + attest_der.extend_from_slice(&inner); + + let device_der = vec![0x30, 0x00]; + + let result = verify_attestation(&attest_der, &device_der).unwrap(); + assert!(result.metadata_extracted); + assert!(!result.verified); + assert!(!result.chain_verified); + assert_eq!(result.root_ca, "new"); // 5.7.4 → new root CA + } + + #[test] + fn test_verify_attestation_empty_cert() { + let result = verify_attestation(&[], &[]).unwrap(); + assert!(!result.verified); + assert!(!result.metadata_extracted); + assert!(!result.chain_verified); + assert_eq!(result.root_ca, "unknown"); + } +} diff --git a/crates/rns-ratkey/src/detect.rs b/crates/rns-ratkey/src/detect.rs new file mode 100644 index 0000000..55fd5bc --- /dev/null +++ b/crates/rns-ratkey/src/detect.rs @@ -0,0 +1,176 @@ +//! PC/SC reader enumeration; filters to YubiKey 5 / Nitrokey 3 by reader name. + +use pcsc::{Card, Context, Protocols, Scope, ShareMode}; +use tracing::{debug, info, warn}; + +use crate::error::RatkeyError; + +#[derive(Debug, Clone)] +pub struct DeviceInfo { + /// "yubikey5" or "nitrokey3". + pub device_type: String, + pub reader_name: String, + pub serial: Option, + pub firmware: Option, + /// Slot 9A occupied. + pub has_signing_key: bool, + /// Slot 9D occupied. + pub has_encryption_key: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeviceType { + YubiKey5, + Nitrokey3, + Unknown, +} + +impl DeviceType { + pub fn as_str(&self) -> &'static str { + match self { + DeviceType::YubiKey5 => "yubikey5", + DeviceType::Nitrokey3 => "nitrokey3", + DeviceType::Unknown => "unknown", + } + } +} + +/// YubiKey readers contain "Yubico" / "YubiKey"; Nitrokey 3 contains "Nitrokey". +pub fn detect_device_type(reader_name: &str) -> DeviceType { + let lower = reader_name.to_lowercase(); + if lower.contains("yubico") || lower.contains("yubikey") { + DeviceType::YubiKey5 + } else if lower.contains("nitrokey") { + DeviceType::Nitrokey3 + } else { + DeviceType::Unknown + } +} + +pub fn list_readers() -> Result, RatkeyError> { + let ctx = Context::establish(Scope::User)?; + + let mut reader_buf = vec![0u8; 4096]; + let readers = match ctx.list_readers(&mut reader_buf) { + Ok(readers) => readers, + Err(pcsc::Error::NoReadersAvailable) => { + return Ok(Vec::new()); + } + Err(e) => return Err(e.into()), + }; + + let names: Vec = readers.map(|r| r.to_string_lossy().to_string()).collect(); + + Ok(names) +} + +pub fn detect_devices() -> Result, RatkeyError> { + let readers = list_readers()?; + let mut devices = Vec::new(); + + for reader_name in &readers { + let device_type = detect_device_type(reader_name); + if device_type == DeviceType::Unknown { + debug!("skipping non-RATKEY reader: {}", reader_name); + continue; + } + + info!( + "found potential device: {} ({})", + reader_name, + device_type.as_str() + ); + + match try_connect_piv(reader_name) { + Ok(info) => { + devices.push(DeviceInfo { + device_type: device_type.as_str().to_string(), + reader_name: reader_name.clone(), + serial: info.serial, + firmware: info.firmware, + has_signing_key: info.has_signing_key, + has_encryption_key: info.has_encryption_key, + }); + } + Err(e) => { + warn!("failed to connect to {}: {}", reader_name, e); + } + } + } + + Ok(devices) +} + +fn try_connect_piv(reader_name: &str) -> Result { + use crate::apdu; + + let ctx = Context::establish(Scope::User)?; + + let reader = std::ffi::CString::new(reader_name) + .map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?; + + let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?; + + let select_cmd = apdu::select_piv(); + let mut response_buf = vec![0u8; 256]; + let response = card.transmit(&select_cmd, &mut response_buf)?; + apdu::check_response(response)?; + + debug!("PIV applet selected on {}", reader_name); + + let device_type = detect_device_type(reader_name); + + // GET METADATA success = slot occupied. Errors treated as empty so partially + // provisioned tokens still detect. + let meta_9a_cmd = apdu::get_metadata(apdu::SLOT_AUTHENTICATION); + let mut meta_buf = vec![0u8; 256]; + let has_signing = match card.transmit(&meta_9a_cmd, &mut meta_buf) { + Ok(resp) => apdu::check_response(resp).is_ok(), + Err(_) => false, + }; + + let meta_9d_cmd = apdu::get_metadata(apdu::SLOT_KEY_MANAGEMENT); + let mut meta_buf2 = vec![0u8; 256]; + let has_encryption = match card.transmit(&meta_9d_cmd, &mut meta_buf2) { + Ok(resp) => apdu::check_response(resp).is_ok(), + Err(_) => false, + }; + + let (serial, firmware) = read_identity(&card, device_type); + + Ok(DeviceInfo { + device_type: device_type.as_str().to_string(), + reader_name: reader_name.to_string(), + serial, + firmware, + has_signing_key: has_signing, + has_encryption_key: has_encryption, + }) +} + +/// Best-effort serial/firmware read. Yubico proprietary INS — Nitrokey 3 returns (None, None). +/// APDU errors are tolerated; never fails a connection. +pub(crate) fn read_identity(card: &Card, device_type: DeviceType) -> (Option, Option) { + use crate::apdu; + + if device_type != DeviceType::YubiKey5 { + return (None, None); + } + + let mut buf = vec![0u8; 256]; + + let serial = card + .transmit(&apdu::get_serial(), &mut buf) + .ok() + .and_then(|resp| apdu::check_response(resp).ok().map(<[u8]>::to_vec)) + .and_then(|data| apdu::parse_serial_response(&data).ok()); + + let firmware = card + .transmit(&apdu::get_version(), &mut buf) + .ok() + .and_then(|resp| apdu::check_response(resp).ok().map(<[u8]>::to_vec)) + .and_then(|data| apdu::parse_version_response(&data).ok()) + .map(|(maj, min, patch)| format!("{maj}.{min}.{patch}")); + + (serial, firmware) +} diff --git a/crates/rns-ratkey/src/error.rs b/crates/rns-ratkey/src/error.rs new file mode 100644 index 0000000..7eaea3b --- /dev/null +++ b/crates/rns-ratkey/src/error.rs @@ -0,0 +1,58 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum RatkeyError { + #[error("no hardware token found")] + NoDevice, + + #[error("hardware token disconnected")] + Disconnected, + + #[error("PIN verification failed ({remaining} attempts remaining)")] + PinFailed { remaining: u8 }, + + /// PIN locked (retry counter exhausted); PUK required to unlock. + #[error("PIN locked — device requires PUK to unlock")] + PinLocked, + + #[error("PIN required — call verify_pin() first")] + PinRequired, + + #[error("touch required on hardware token")] + TouchRequired, + + #[error("PIV slot 0x{slot:02X} has no key")] + EmptySlot { slot: u8 }, + + #[error("PIV slot 0x{slot:02X} already contains a key")] + SlotOccupied { slot: u8 }, + + #[error("unsupported device: {0}")] + UnsupportedDevice(String), + + #[error("firmware version {found} does not meet minimum {required}")] + FirmwareVersion { required: String, found: String }, + + #[error("key mismatch: hardware public key does not match .hwid file")] + KeyMismatch, + + #[cfg(feature = "hardware")] + #[error("PC/SC error: {0}")] + Pcsc(#[from] pcsc::Error), + + /// ISO 7816-4 status word (SW1/SW2) returned by the card. + #[error("APDU error: SW={sw1:02X}{sw2:02X}")] + Apdu { sw1: u8, sw2: u8 }, + + #[error("invalid .hwid file: {0}")] + InvalidHwid(String), + + #[error("signing failed: {0}")] + SigningFailed(String), + + #[error("ECDH failed: {0}")] + EcdhFailed(String), + + #[error("io error: {0}")] + Io(#[from] std::io::Error), +} diff --git a/crates/rns-ratkey/src/hardware.rs b/crates/rns-ratkey/src/hardware.rs new file mode 100644 index 0000000..0c6fdfd --- /dev/null +++ b/crates/rns-ratkey/src/hardware.rs @@ -0,0 +1,369 @@ +//! `HardwareIdentity`: public-key-only `Identity` + PIV session for private ops. +//! Wire-compatible with software identities. + +use std::path::Path; + +use rns_crypto::hkdf::derive_key_64; +use rns_crypto::token; +use rns_identity::identity::Identity; + +use crate::error::RatkeyError; +use crate::hwid::HwidConfig; +use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D}; + +pub struct HardwareIdentity { + pub identity: Identity, + pub config: HwidConfig, + ed25519_pub: [u8; 32], + x25519_pub: [u8; 32], + // Mock session storage keeps the current API testable until the real PIV + // backend is wired. See crates/rns-ratkey/HARDWARE_STATUS.md. + mock_session: Option, +} + +impl HardwareIdentity { + pub fn from_hwid_mock( + config: HwidConfig, + session: MockPivSession, + ) -> Result { + let ed25519_pub = config.ed25519_pub_bytes()?; + let x25519_pub = config.x25519_pub_bytes()?; + + // Fail closed: published identity hash must map to keys actually on the device. + let session_ed = session.read_ed25519_public(SLOT_9A)?; + let session_x = session.read_x25519_public(SLOT_9D)?; + if session_ed != ed25519_pub || session_x != x25519_pub { + return Err(RatkeyError::KeyMismatch); + } + + let mut pub_key_bytes = [0u8; 64]; + pub_key_bytes[..32].copy_from_slice(&x25519_pub); + pub_key_bytes[32..].copy_from_slice(&ed25519_pub); + let identity = Identity::from_public_key(&pub_key_bytes) + .map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?; + + Ok(Self { + identity, + config, + ed25519_pub, + x25519_pub, + mock_session: Some(session), + }) + } + + pub fn from_file_mock(path: &Path, session: MockPivSession) -> Result { + let config = HwidConfig::from_file(path)?; + Self::from_hwid_mock(config, session) + } + + /// Test-only: build without `.hwid`; skips key-mismatch guard. + pub fn from_keys_mock( + ed25519_pub: [u8; 32], + x25519_pub: [u8; 32], + session: MockPivSession, + ) -> Result { + let config = HwidConfig { + identity: crate::hwid::HwidIdentity { + hash: String::new(), + nickname: "test".to_string(), + created_at: 0, + }, + device: crate::hwid::HwidDevice { + device_type: session.device_type.clone(), + serial: session.serial, + firmware: session.firmware.clone(), + }, + keys: crate::hwid::HwidKeys { + ed25519_pub: hex::encode(ed25519_pub), + x25519_pub: hex::encode(x25519_pub), + }, + slots: crate::hwid::HwidSlots { + signing: "9A".to_string(), + encryption: "9D".to_string(), + }, + policy: crate::hwid::HwidPolicy { + pin_cache_timeout: 300, + touch_signing: "never".to_string(), + touch_encryption: "never".to_string(), + }, + attestation: Default::default(), + app: Default::default(), + backup: Default::default(), + }; + + let mut pub_key_bytes = [0u8; 64]; + pub_key_bytes[..32].copy_from_slice(&x25519_pub); + pub_key_bytes[32..].copy_from_slice(&ed25519_pub); + let identity = Identity::from_public_key(&pub_key_bytes) + .map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?; + + let mut config = config; + // Hash is derived from the Identity so the .hwid stays consistent. + config.identity.hash = hex::encode(identity.hash); + + Ok(Self { + identity, + config, + ed25519_pub, + x25519_pub, + mock_session: Some(session), + }) + } + + pub fn hash(&self) -> &[u8; 16] { + &self.identity.hash + } + + pub fn hash_hex(&self) -> String { + hex::encode(self.identity.hash) + } + + /// 64-byte public key (X25519_pub || Ed25519_pub). + pub fn get_public_key(&self) -> [u8; 64] { + self.identity.get_public_key() + } + + pub fn ed25519_public(&self) -> &[u8; 32] { + &self.ed25519_pub + } + + pub fn x25519_public(&self) -> &[u8; 32] { + &self.x25519_pub + } + + pub fn as_identity(&self) -> &Identity { + &self.identity + } + + pub fn sign(&mut self, message: &[u8]) -> Result<[u8; 64], RatkeyError> { + let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?; + session.sign_ed25519(SLOT_9A, message) + } + + pub fn ecdh(&mut self, peer_pub_bytes: &[u8; 32]) -> Result<[u8; 32], RatkeyError> { + let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?; + session.ecdh_x25519(SLOT_9D, peer_pub_bytes) + } + + /// Ciphertext = ephemeral_pub(32) || AES-256-CBC token. Mirrors `Identity::decrypt` + /// but does the ECDH on-device. + pub fn decrypt( + &mut self, + ciphertext: &[u8], + ratchets: Option<&[&[u8; 32]]>, + enforce_ratchets: bool, + ) -> Result, RatkeyError> { + if ciphertext.len() <= 32 { + return Err(RatkeyError::EcdhFailed("ciphertext too short".to_string())); + } + + let ephemeral_pub_bytes: [u8; 32] = ciphertext[..32] + .try_into() + .map_err(|_| RatkeyError::EcdhFailed("invalid ephemeral key".to_string()))?; + let encrypted_token = &ciphertext[32..]; + + // PIV cannot store Reticulum ratchet private keys. This backend skips + // ratchet keys and falls back to identity ECDH; enforced ratchets fail + // closed. + if let Some(ratchet_keys) = ratchets { + for _ratchet_pub in ratchet_keys {} + if enforce_ratchets { + return Err(RatkeyError::EcdhFailed( + "no valid ratchet key found and ratchets enforced".to_string(), + )); + } + } + + let shared_secret = self.ecdh(&ephemeral_pub_bytes)?; + + // HKDF-SHA256, salt = identity hash. Matches Identity::decrypt. + let derived = derive_key_64(&shared_secret, &self.identity.hash) + .map_err(|_| RatkeyError::EcdhFailed("HKDF derivation failed".to_string()))?; + + token::decrypt(encrypted_token, &derived) + .map_err(|_| RatkeyError::EcdhFailed("decryption failed".to_string())) + } + + /// Verification is a public-key op; no hardware call. + pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool { + self.identity.verify(message, signature) + } + + pub fn is_connected(&self) -> bool { + self.mock_session.as_ref().is_some_and(|s| s.is_connected()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey}; + use rns_identity::identity::Identity; + + #[test] + fn test_from_keys_mock() { + let session = MockPivSession::with_keys(); + let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); + let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + + let hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + assert_eq!(hw.ed25519_public(), &ed_pub); + assert_eq!(hw.x25519_public(), &x_pub); + assert!(!hw.hash_hex().is_empty()); + } + + #[test] + fn test_sign_and_verify() { + let session = MockPivSession::with_keys(); + let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); + let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + + let message = b"ratkey hardware identity test"; + let sig = hw.sign(message).unwrap(); + assert!(hw.verify(message, &sig)); + } + + #[test] + fn test_sign_matches_software_identity() { + // Load-bearing: Ed25519 is deterministic, hardware and software paths + // MUST be byte-identical for shared key material. + let ed_seed = [0x42u8; 32]; + let x_secret = [0x43u8; 32]; + let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret); + let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); + let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + + let mut prv_bytes = [0u8; 64]; + prv_bytes[..32].copy_from_slice(&x_secret); + prv_bytes[32..].copy_from_slice(&ed_seed); + let sw_identity = Identity::from_private_key(&prv_bytes).unwrap(); + + let message = b"cross-validation test"; + + let hw_sig = hw.sign(message).unwrap(); + let sw_sig = sw_identity.sign(message).unwrap(); + + assert_eq!( + hw_sig, sw_sig, + "hardware and software signatures must match" + ); + assert_eq!(hw.identity.hash, sw_identity.hash); + assert_eq!(hw.get_public_key(), sw_identity.get_public_key()); + } + + #[test] + fn test_ecdh_with_software_peer() { + let session = MockPivSession::with_keys(); + let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); + let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + + let peer_prv = X25519PrivateKey::generate(); + let peer_pub = peer_prv.public_key(); + let peer_pub_bytes = peer_pub.to_bytes(); + + let hw_shared = hw.ecdh(&peer_pub_bytes).unwrap(); + + let hw_pub = X25519PublicKey::from_bytes(&x_pub); + let sw_shared = peer_prv.exchange(&hw_pub); + + assert_eq!(hw_shared, sw_shared, "ECDH must be symmetric"); + } + + #[test] + fn test_encrypt_decrypt_round_trip() { + let ed_seed = [0x42u8; 32]; + let x_secret = [0x43u8; 32]; + let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret); + let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); + let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + + let mut prv_bytes = [0u8; 64]; + prv_bytes[..32].copy_from_slice(&x_secret); + prv_bytes[32..].copy_from_slice(&ed_seed); + let sw_identity = Identity::from_private_key(&prv_bytes).unwrap(); + + let plaintext = b"secret message for hardware identity"; + let ciphertext = sw_identity.encrypt(plaintext, None).unwrap(); + + let decrypted = hw.decrypt(&ciphertext, None, false).unwrap(); + assert_eq!(decrypted, plaintext); + } + + #[test] + fn test_encrypt_from_other_identity() { + let session = MockPivSession::with_keys(); + let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); + let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + + let _sender = Identity::new(); + + let ciphertext = hw.identity.encrypt(b"hello from sender", None).unwrap(); + + let decrypted = hw.decrypt(&ciphertext, None, false).unwrap(); + assert_eq!(decrypted, b"hello from sender"); + } + + #[test] + fn test_disconnect_fails_operations() { + let session = MockPivSession::with_keys(); + let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); + let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + + assert!(hw.is_connected()); + hw.mock_session.as_mut().unwrap().disconnect(); + assert!(!hw.is_connected()); + + assert!(matches!(hw.sign(b"test"), Err(RatkeyError::Disconnected))); + } + + #[test] + fn test_key_mismatch_rejected() { + // from_keys_mock does not cross-check; the .hwid path does (test_hwid_key_mismatch). + let session = MockPivSession::with_keys(); + let wrong_ed = [0xFFu8; 32]; + let wrong_x = [0xFFu8; 32]; + let _result = HardwareIdentity::from_keys_mock(wrong_ed, wrong_x, session); + } + + #[test] + fn test_hwid_key_mismatch() { + let session = MockPivSession::with_keys(); + let config = HwidConfig { + identity: crate::hwid::HwidIdentity { + hash: "test".to_string(), + nickname: "test".to_string(), + created_at: 0, + }, + device: crate::hwid::HwidDevice { + device_type: "yubikey5".to_string(), + serial: 99999999, + firmware: "5.7.1".to_string(), + }, + keys: crate::hwid::HwidKeys { + ed25519_pub: "ff".repeat(32), + x25519_pub: "ff".repeat(32), + }, + slots: crate::hwid::HwidSlots { + signing: "9A".to_string(), + encryption: "9D".to_string(), + }, + policy: crate::hwid::HwidPolicy { + pin_cache_timeout: 300, + touch_signing: "never".to_string(), + touch_encryption: "never".to_string(), + }, + attestation: Default::default(), + app: Default::default(), + backup: Default::default(), + }; + + let result = HardwareIdentity::from_hwid_mock(config, session); + assert!(matches!(result, Err(RatkeyError::KeyMismatch))); + } +} diff --git a/crates/rns-ratkey/src/hwid.rs b/crates/rns-ratkey/src/hwid.rs new file mode 100644 index 0000000..1f8b366 --- /dev/null +++ b/crates/rns-ratkey/src/hwid.rs @@ -0,0 +1,332 @@ +//! `.hwid` TOML: public metadata for a hardware identity. No private key material ever. +//! Location: `/identities/{hash_hex}/identity.hwid`. + +use std::path::Path; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +use crate::error::RatkeyError; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HwidConfig { + pub identity: HwidIdentity, + pub device: HwidDevice, + pub keys: HwidKeys, + pub slots: HwidSlots, + pub policy: HwidPolicy, + #[serde(default)] + pub attestation: HwidAttestation, + #[serde(default)] + pub app: HwidApp, + #[serde(default)] + pub backup: HwidBackup, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HwidIdentity { + /// 16-byte hash (32 hex chars). + pub hash: String, + #[serde(default)] + pub nickname: String, + pub created_at: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HwidDevice { + /// "yubikey5" or "nitrokey3". + #[serde(rename = "type")] + pub device_type: String, + pub serial: u32, + pub firmware: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HwidKeys { + /// 32-byte hex. + pub ed25519_pub: String, + /// 32-byte hex. + pub x25519_pub: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HwidSlots { + /// PIV slot hex (e.g. "9A"). + pub signing: String, + /// PIV slot hex (e.g. "9D"). + pub encryption: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HwidPolicy { + /// Seconds; 0 = never cache. + #[serde(default = "default_pin_cache_timeout")] + pub pin_cache_timeout: u64, + /// "always" | "cached" | "never". + #[serde(default = "default_touch_signing")] + pub touch_signing: String, + /// "always" | "cached" | "never". + #[serde(default = "default_touch_encryption")] + pub touch_encryption: String, +} + +fn default_pin_cache_timeout() -> u64 { + 300 +} +fn default_touch_signing() -> String { + "always".to_string() +} +fn default_touch_encryption() -> String { + "cached".to_string() +} + +/// Attestation certificates (base64-encoded DER). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct HwidAttestation { + #[serde(default)] + pub ed25519_cert: String, + #[serde(default)] + pub x25519_cert: String, + /// Cryptographic attestation-chain verification status. Metadata + /// extraction alone must not set this true. + #[serde(default)] + pub verified: bool, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct HwidApp { + /// Pre-computed app destination hash (hex). + #[serde(default)] + pub app_hash: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct HwidBackup { + /// 0=none, 1=device-clone, 2=encrypted-offline. + #[serde(default)] + pub tier: u8, + /// Tier 1 only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub backup_serial: Option, + /// Tier 2 only: SHA-256 of encrypted backup. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encrypted_backup_hash: Option, +} + +impl HwidConfig { + pub fn from_file(path: &Path) -> Result { + let content = std::fs::read_to_string(path) + .map_err(|e| RatkeyError::InvalidHwid(format!("cannot read file: {e}")))?; + content.parse() + } + + pub fn to_file(&self, path: &Path) -> Result<(), RatkeyError> { + let content = self.to_string()?; + // Atomic: write tmp, then rename. + let tmp_path = path.with_extension("hwid.tmp"); + std::fs::write(&tmp_path, content)?; + std::fs::rename(&tmp_path, path)?; + Ok(()) + } + + pub fn to_string(&self) -> Result { + let header = "# RATKEY Hardware Identity \u{2014} DO NOT EDIT MANUALLY\n\ + # Private keys exist ONLY on the hardware device.\n\n"; + let body = + toml::to_string_pretty(self).map_err(|e| RatkeyError::InvalidHwid(e.to_string()))?; + Ok(format!("{header}{body}")) + } + + pub fn ed25519_pub_bytes(&self) -> Result<[u8; 32], RatkeyError> { + decode_hex_32(&self.keys.ed25519_pub, "ed25519_pub") + } + + pub fn x25519_pub_bytes(&self) -> Result<[u8; 32], RatkeyError> { + decode_hex_32(&self.keys.x25519_pub, "x25519_pub") + } + + pub fn signing_slot(&self) -> Result { + parse_slot(&self.slots.signing) + } + + pub fn encryption_slot(&self) -> Result { + parse_slot(&self.slots.encryption) + } +} + +impl FromStr for HwidConfig { + type Err = RatkeyError; + + fn from_str(s: &str) -> Result { + toml::from_str(s).map_err(|e| RatkeyError::InvalidHwid(e.to_string())) + } +} + +fn decode_hex_32(hex_str: &str, field: &str) -> Result<[u8; 32], RatkeyError> { + let bytes = + hex::decode(hex_str).map_err(|e| RatkeyError::InvalidHwid(format!("{field}: {e}")))?; + if bytes.len() != 32 { + return Err(RatkeyError::InvalidHwid(format!( + "{field}: expected 32 bytes, got {}", + bytes.len() + ))); + } + let mut arr = [0u8; 32]; + arr.copy_from_slice(&bytes); + Ok(arr) +} + +fn parse_slot(s: &str) -> Result { + u8::from_str_radix(s.trim_start_matches("0x").trim_start_matches("0X"), 16) + .map_err(|e| RatkeyError::InvalidHwid(format!("invalid slot '{s}': {e}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_config() -> HwidConfig { + HwidConfig { + identity: HwidIdentity { + hash: "a1b2c3d4e5f6a7b8a1b2c3d4e5f6a7b8".to_string(), + nickname: "Test YubiKey".to_string(), + created_at: 1711580400, + }, + device: HwidDevice { + device_type: "yubikey5".to_string(), + serial: 12345678, + firmware: "5.7.1".to_string(), + }, + keys: HwidKeys { + ed25519_pub: "aa".repeat(32), + x25519_pub: "bb".repeat(32), + }, + slots: HwidSlots { + signing: "9A".to_string(), + encryption: "9D".to_string(), + }, + policy: HwidPolicy { + pin_cache_timeout: 300, + touch_signing: "always".to_string(), + touch_encryption: "cached".to_string(), + }, + attestation: HwidAttestation::default(), + app: HwidApp::default(), + backup: HwidBackup::default(), + } + } + + #[test] + fn test_round_trip() { + let config = sample_config(); + let toml_str = config.to_string().unwrap(); + let parsed = toml_str.parse::().unwrap(); + + assert_eq!(parsed.identity.hash, config.identity.hash); + assert_eq!(parsed.identity.nickname, config.identity.nickname); + assert_eq!(parsed.device.device_type, config.device.device_type); + assert_eq!(parsed.device.serial, config.device.serial); + assert_eq!(parsed.keys.ed25519_pub, config.keys.ed25519_pub); + assert_eq!(parsed.keys.x25519_pub, config.keys.x25519_pub); + assert_eq!(parsed.slots.signing, config.slots.signing); + assert_eq!(parsed.slots.encryption, config.slots.encryption); + assert_eq!( + parsed.policy.pin_cache_timeout, + config.policy.pin_cache_timeout + ); + assert_eq!(parsed.policy.touch_signing, config.policy.touch_signing); + assert_eq!(parsed.backup.tier, 0); + } + + #[test] + fn test_decode_public_keys() { + let config = sample_config(); + let ed_bytes = config.ed25519_pub_bytes().unwrap(); + assert_eq!(ed_bytes, [0xAA; 32]); + let x_bytes = config.x25519_pub_bytes().unwrap(); + assert_eq!(x_bytes, [0xBB; 32]); + } + + #[test] + fn test_parse_slots() { + let config = sample_config(); + assert_eq!(config.signing_slot().unwrap(), 0x9A); + assert_eq!(config.encryption_slot().unwrap(), 0x9D); + } + + #[test] + fn test_invalid_hex() { + let mut config = sample_config(); + config.keys.ed25519_pub = "not_hex".to_string(); + assert!(config.ed25519_pub_bytes().is_err()); + } + + #[test] + fn test_wrong_key_length() { + let mut config = sample_config(); + config.keys.ed25519_pub = "aa".repeat(16); // 16 bytes instead of 32 + assert!(config.ed25519_pub_bytes().is_err()); + } + + #[test] + fn test_invalid_slot() { + let mut config = sample_config(); + config.slots.signing = "ZZ".to_string(); + assert!(config.signing_slot().is_err()); + } + + #[test] + fn test_toml_contains_header() { + let config = sample_config(); + let toml_str = config.to_string().unwrap(); + assert!(toml_str.contains("RATKEY Hardware Identity")); + assert!(toml_str.contains("DO NOT EDIT MANUALLY")); + } + + #[test] + fn test_file_round_trip() { + let config = sample_config(); + let dir = std::env::temp_dir().join("ratkey_test_hwid"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("test.hwid"); + + config.to_file(&path).unwrap(); + let loaded = HwidConfig::from_file(&path).unwrap(); + + assert_eq!(loaded.identity.hash, config.identity.hash); + assert_eq!(loaded.device.serial, config.device.serial); + assert_eq!(loaded.keys.ed25519_pub, config.keys.ed25519_pub); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_defaults_applied() { + let minimal = r#" +[identity] +hash = "aabb" +created_at = 1000 + +[device] +type = "yubikey5" +serial = 1 +firmware = "5.7.0" + +[keys] +ed25519_pub = "aa" +x25519_pub = "bb" + +[slots] +signing = "9A" +encryption = "9D" + +[policy] +"#; + let config = minimal.parse::().unwrap(); + assert_eq!(config.policy.pin_cache_timeout, 300); + assert_eq!(config.policy.touch_signing, "always"); + assert_eq!(config.policy.touch_encryption, "cached"); + assert_eq!(config.backup.tier, 0); + assert!(config.attestation.ed25519_cert.is_empty()); + } +} diff --git a/crates/rns-ratkey/src/lib.rs b/crates/rns-ratkey/src/lib.rs new file mode 100644 index 0000000..2701258 --- /dev/null +++ b/crates/rns-ratkey/src/lib.rs @@ -0,0 +1,24 @@ +//! Hardware-backed identity (YubiKey 5, Nitrokey 3) via PIV. Ed25519 sign + X25519 +//! ECDH keys live on-device; only public keys and results leave the token. +//! Wire-compatible with software identities. `hardware` feature enables real PIV via `pcsc`. + +pub mod apdu; +pub mod attestation; +pub mod error; +pub mod hardware; +pub mod hwid; +pub mod mock; +pub mod pin; +pub mod provision; + +#[cfg(feature = "hardware")] +pub mod detect; +#[cfg(feature = "hardware")] +pub mod session; + +pub use error::RatkeyError; +pub use hardware::HardwareIdentity; +pub use hwid::HwidConfig; +pub use mock::MockPivSession; +pub use pin::PinCache; +pub use provision::{ProvisionConfig, ProvisionResult}; diff --git a/crates/rns-ratkey/src/mock.rs b/crates/rns-ratkey/src/mock.rs new file mode 100644 index 0000000..18740ac --- /dev/null +++ b/crates/rns-ratkey/src/mock.rs @@ -0,0 +1,628 @@ +//! In-memory PIV mock with real Ed25519/X25519 crypto; signatures/ECDH are bit-identical +//! to software results for test vector reuse. Simulates PIN retry/lockout, touch policy, +//! disconnect, slot state. Primary dev/validation env until hardware lands. + +use std::collections::HashMap; + +use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; +use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey}; +use zeroize::Zeroize; + +use crate::error::RatkeyError; + +/// Slot 9A: PIV Authentication — Ed25519 signing. +pub const SLOT_9A: u8 = 0x9A; +/// Slot 9D: PIV Key Management — X25519 ECDH. +pub const SLOT_9D: u8 = 0x9D; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TouchPolicy { + Never, + Always, + /// YubiKey ~15s cache. + Cached, +} + +struct SlotState { + ed25519_prv: Option, + ed25519_pub: Option, + x25519_prv: Option, + x25519_pub: Option, + touch_policy: TouchPolicy, +} + +impl SlotState { + fn empty() -> Self { + Self { + ed25519_prv: None, + ed25519_pub: None, + x25519_prv: None, + x25519_pub: None, + touch_policy: TouchPolicy::Never, + } + } +} + +#[derive(Debug, Clone)] +pub enum MockOperation { + PinVerify { success: bool }, + GenerateEd25519 { slot: u8 }, + GenerateX25519 { slot: u8 }, + SignEd25519 { slot: u8, data_len: usize }, + EcdhX25519 { slot: u8 }, + ReadPublicKey { slot: u8 }, +} + +pub struct MockPivSession { + slots: HashMap, + pin: String, + pin_verified: bool, + pin_retries: u8, + max_retries: u8, + connected: bool, + /// True: `TouchPolicy::Always` slots reject ops. `simulate_touch()` clears. + touch_required: bool, + pub device_type: String, + pub serial: u32, + pub firmware: String, + pub operations: Vec, +} + +impl MockPivSession { + pub fn new() -> Self { + let mut slots = HashMap::new(); + slots.insert(SLOT_9A, SlotState::empty()); + slots.insert(SLOT_9D, SlotState::empty()); + + Self { + slots, + pin: "123456".to_string(), + pin_verified: false, + pin_retries: 3, + max_retries: 3, + connected: true, + touch_required: true, + device_type: "yubikey5".to_string(), + serial: 99999999, + firmware: "5.7.1".to_string(), + operations: Vec::new(), + } + } + + /// Pre-populated slots 9A/9D; skips provision step for sign/ECDH tests. + pub fn with_keys() -> Self { + let mut session = Self::new(); + session.pin_verified = true; + session.touch_required = false; + + let ed_prv = Ed25519PrivateKey::generate(); + let ed_pub = ed_prv.public_key(); + let slot_9a = session.slots.get_mut(&SLOT_9A).unwrap(); + slot_9a.ed25519_prv = Some(ed_prv); + slot_9a.ed25519_pub = Some(ed_pub); + + let x_prv = X25519PrivateKey::generate(); + let x_pub = x_prv.public_key(); + let slot_9d = session.slots.get_mut(&SLOT_9D).unwrap(); + slot_9d.x25519_prv = Some(x_prv); + slot_9d.x25519_pub = Some(x_pub); + + session + } + + /// Deterministic key material for test vectors. + pub fn with_key_bytes(ed25519_seed: &[u8; 32], x25519_secret: &[u8; 32]) -> Self { + let mut session = Self::new(); + session.pin_verified = true; + session.touch_required = false; + + let ed_prv = Ed25519PrivateKey::from_bytes(ed25519_seed); + let ed_pub = ed_prv.public_key(); + let slot_9a = session.slots.get_mut(&SLOT_9A).unwrap(); + slot_9a.ed25519_prv = Some(ed_prv); + slot_9a.ed25519_pub = Some(ed_pub); + + let x_prv = X25519PrivateKey::from_bytes(x25519_secret); + let x_pub = x_prv.public_key(); + let slot_9d = session.slots.get_mut(&SLOT_9D).unwrap(); + slot_9d.x25519_prv = Some(x_prv); + slot_9d.x25519_pub = Some(x_pub); + + session + } + + pub fn set_pin(&mut self, pin: &str) { + self.pin = pin.to_string(); + self.pin_verified = false; + } + + pub fn disconnect(&mut self) { + self.connected = false; + } + + pub fn reconnect(&mut self) { + self.connected = true; + self.pin_verified = false; + } + + pub fn simulate_touch(&mut self) { + self.touch_required = false; + } + + pub fn require_touch(&mut self) { + self.touch_required = true; + } + + fn check_connected(&self) -> Result<(), RatkeyError> { + if !self.connected { + Err(RatkeyError::Disconnected) + } else { + Ok(()) + } + } + + fn check_pin(&self) -> Result<(), RatkeyError> { + if !self.pin_verified { + Err(RatkeyError::PinRequired) + } else { + Ok(()) + } + } + + fn check_touch(&self, slot: u8) -> Result<(), RatkeyError> { + if let Some(slot_state) = self.slots.get(&slot) { + if slot_state.touch_policy == TouchPolicy::Always && self.touch_required { + return Err(RatkeyError::TouchRequired); + } + } + Ok(()) + } + + pub fn is_connected(&self) -> bool { + self.connected + } + + pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> { + self.check_connected()?; + + if self.pin_retries == 0 { + self.operations + .push(MockOperation::PinVerify { success: false }); + return Err(RatkeyError::PinLocked); + } + + if pin == self.pin { + self.pin_verified = true; + self.pin_retries = self.max_retries; + self.operations + .push(MockOperation::PinVerify { success: true }); + Ok(()) + } else { + self.pin_retries -= 1; + self.operations + .push(MockOperation::PinVerify { success: false }); + if self.pin_retries == 0 { + Err(RatkeyError::PinLocked) + } else { + Err(RatkeyError::PinFailed { + remaining: self.pin_retries, + }) + } + } + } + + pub fn generate_ed25519( + &mut self, + slot: u8, + touch_policy: TouchPolicy, + ) -> Result<[u8; 32], RatkeyError> { + self.check_connected()?; + self.check_pin()?; + + let slot_state = self + .slots + .get_mut(&slot) + .ok_or(RatkeyError::InvalidHwid(format!( + "unknown slot 0x{slot:02X}" + )))?; + + if slot_state.ed25519_prv.is_some() { + return Err(RatkeyError::SlotOccupied { slot }); + } + + let prv = Ed25519PrivateKey::generate(); + let pub_key = prv.public_key(); + let pub_bytes = pub_key.to_bytes(); + + slot_state.ed25519_prv = Some(prv); + slot_state.ed25519_pub = Some(pub_key); + slot_state.touch_policy = touch_policy; + + self.operations + .push(MockOperation::GenerateEd25519 { slot }); + Ok(pub_bytes) + } + + pub fn generate_x25519( + &mut self, + slot: u8, + touch_policy: TouchPolicy, + ) -> Result<[u8; 32], RatkeyError> { + self.check_connected()?; + self.check_pin()?; + + let slot_state = self + .slots + .get_mut(&slot) + .ok_or(RatkeyError::InvalidHwid(format!( + "unknown slot 0x{slot:02X}" + )))?; + + if slot_state.x25519_prv.is_some() { + return Err(RatkeyError::SlotOccupied { slot }); + } + + let prv = X25519PrivateKey::generate(); + let pub_key = prv.public_key(); + let pub_bytes = pub_key.to_bytes(); + + slot_state.x25519_prv = Some(prv); + slot_state.x25519_pub = Some(pub_key); + slot_state.touch_policy = touch_policy; + + self.operations.push(MockOperation::GenerateX25519 { slot }); + Ok(pub_bytes) + } + + pub fn sign_ed25519(&mut self, slot: u8, data: &[u8]) -> Result<[u8; 64], RatkeyError> { + self.check_connected()?; + self.check_pin()?; + self.check_touch(slot)?; + + let slot_state = self + .slots + .get(&slot) + .ok_or(RatkeyError::InvalidHwid(format!( + "unknown slot 0x{slot:02X}" + )))?; + + let prv = slot_state + .ed25519_prv + .as_ref() + .ok_or(RatkeyError::EmptySlot { slot })?; + + let sig = prv.sign(data); + + self.operations.push(MockOperation::SignEd25519 { + slot, + data_len: data.len(), + }); + Ok(sig) + } + + pub fn ecdh_x25519( + &mut self, + slot: u8, + peer_pub_bytes: &[u8; 32], + ) -> Result<[u8; 32], RatkeyError> { + self.check_connected()?; + self.check_pin()?; + self.check_touch(slot)?; + + let slot_state = self + .slots + .get(&slot) + .ok_or(RatkeyError::InvalidHwid(format!( + "unknown slot 0x{slot:02X}" + )))?; + + let prv = slot_state + .x25519_prv + .as_ref() + .ok_or(RatkeyError::EmptySlot { slot })?; + + let peer_pub = X25519PublicKey::from_bytes(peer_pub_bytes); + let shared = prv.exchange(&peer_pub); + + self.operations.push(MockOperation::EcdhX25519 { slot }); + Ok(shared) + } + + pub fn read_ed25519_public(&self, slot: u8) -> Result<[u8; 32], RatkeyError> { + self.check_connected()?; + + let slot_state = self + .slots + .get(&slot) + .ok_or(RatkeyError::InvalidHwid(format!( + "unknown slot 0x{slot:02X}" + )))?; + + let pub_key = slot_state + .ed25519_pub + .as_ref() + .ok_or(RatkeyError::EmptySlot { slot })?; + + Ok(pub_key.to_bytes()) + } + + pub fn read_x25519_public(&self, slot: u8) -> Result<[u8; 32], RatkeyError> { + self.check_connected()?; + + let slot_state = self + .slots + .get(&slot) + .ok_or(RatkeyError::InvalidHwid(format!( + "unknown slot 0x{slot:02X}" + )))?; + + let pub_key = slot_state + .x25519_pub + .as_ref() + .ok_or(RatkeyError::EmptySlot { slot })?; + + Ok(pub_key.to_bytes()) + } +} + +impl Default for MockPivSession { + fn default() -> Self { + Self::new() + } +} + +impl Drop for MockPivSession { + fn drop(&mut self) { + self.pin.zeroize(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pin_verify_success() { + let mut session = MockPivSession::new(); + assert!(session.verify_pin("123456").is_ok()); + assert!(session.pin_verified); + } + + #[test] + fn test_pin_verify_wrong() { + let mut session = MockPivSession::new(); + let err = session.verify_pin("wrong").unwrap_err(); + match err { + RatkeyError::PinFailed { remaining } => assert_eq!(remaining, 2), + other => panic!("expected PinFailed, got {other:?}"), + } + assert!(!session.pin_verified); + } + + #[test] + fn test_pin_lockout() { + let mut session = MockPivSession::new(); + let _ = session.verify_pin("wrong"); + let _ = session.verify_pin("wrong"); + let err = session.verify_pin("wrong").unwrap_err(); + assert!(matches!(err, RatkeyError::PinLocked)); + + // Locked state survives correct PIN until PUK unlock. + let err = session.verify_pin("123456").unwrap_err(); + assert!(matches!(err, RatkeyError::PinLocked)); + } + + #[test] + fn test_pin_retry_reset() { + let mut session = MockPivSession::new(); + let _ = session.verify_pin("wrong"); + // Success resets retries. + session.verify_pin("123456").unwrap(); + let _ = session.verify_pin("wrong"); + let _ = session.verify_pin("wrong"); + let err = session.verify_pin("wrong").unwrap_err(); + assert!(matches!(err, RatkeyError::PinLocked)); + } + + #[test] + fn test_disconnect() { + let mut session = MockPivSession::with_keys(); + session.disconnect(); + assert!(!session.is_connected()); + assert!(matches!( + session.sign_ed25519(SLOT_9A, b"test"), + Err(RatkeyError::Disconnected) + )); + } + + #[test] + fn test_reconnect_requires_pin() { + let mut session = MockPivSession::with_keys(); + session.disconnect(); + session.reconnect(); + assert!(session.is_connected()); + assert!(matches!( + session.sign_ed25519(SLOT_9A, b"test"), + Err(RatkeyError::PinRequired) + )); + } + + #[test] + fn test_generate_ed25519() { + let mut session = MockPivSession::new(); + session.verify_pin("123456").unwrap(); + let pub_bytes = session + .generate_ed25519(SLOT_9A, TouchPolicy::Never) + .unwrap(); + assert_eq!(pub_bytes.len(), 32); + + assert!(matches!( + session.generate_ed25519(SLOT_9A, TouchPolicy::Never), + Err(RatkeyError::SlotOccupied { slot: 0x9A }) + )); + } + + #[test] + fn test_generate_x25519() { + let mut session = MockPivSession::new(); + session.verify_pin("123456").unwrap(); + let pub_bytes = session + .generate_x25519(SLOT_9D, TouchPolicy::Cached) + .unwrap(); + assert_eq!(pub_bytes.len(), 32); + } + + #[test] + fn test_sign_verify() { + let mut session = MockPivSession::with_keys(); + let message = b"hello ratkey"; + let sig = session.sign_ed25519(SLOT_9A, message).unwrap(); + assert_eq!(sig.len(), 64); + + let pub_bytes = session.read_ed25519_public(SLOT_9A).unwrap(); + let pub_key = Ed25519PublicKey::from_bytes(&pub_bytes).unwrap(); + assert!(pub_key.verify(message, &sig).is_ok()); + } + + #[test] + fn test_sign_matches_software() { + // Load-bearing: mock signatures MUST match software signatures bit-for-bit + // so test vectors generated on hardware can be replayed here. + let seed = [0x42u8; 32]; + let secret = [0x43u8; 32]; + let mut session = MockPivSession::with_key_bytes(&seed, &secret); + + let software_key = Ed25519PrivateKey::from_bytes(&seed); + let message = b"deterministic signature test"; + + let hw_sig = session.sign_ed25519(SLOT_9A, message).unwrap(); + let sw_sig = software_key.sign(message); + + assert_eq!( + hw_sig, sw_sig, + "mock signature must match software signature" + ); + } + + #[test] + fn test_ecdh_symmetric() { + let mut session = MockPivSession::with_keys(); + let session_x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + + let peer_prv = X25519PrivateKey::generate(); + let peer_pub = peer_prv.public_key(); + let peer_pub_bytes = peer_pub.to_bytes(); + + let secret_hw = session.ecdh_x25519(SLOT_9D, &peer_pub_bytes).unwrap(); + + let session_pub = X25519PublicKey::from_bytes(&session_x_pub); + let secret_sw = peer_prv.exchange(&session_pub); + + assert_eq!( + secret_hw, secret_sw, + "ECDH shared secrets must be identical from both sides" + ); + } + + #[test] + fn test_ecdh_deterministic() { + let seed = [0x42u8; 32]; + let secret = [0x43u8; 32]; + let mut session = MockPivSession::with_key_bytes(&seed, &secret); + + let peer_pub = [0x55u8; 32]; + + let software_key = X25519PrivateKey::from_bytes(&secret); + let peer = X25519PublicKey::from_bytes(&peer_pub); + let sw_shared = software_key.exchange(&peer); + + let hw_shared = session.ecdh_x25519(SLOT_9D, &peer_pub).unwrap(); + + assert_eq!( + hw_shared, sw_shared, + "mock ECDH must match software ECDH for same keys" + ); + } + + #[test] + fn test_sign_empty_slot() { + let mut session = MockPivSession::new(); + session.verify_pin("123456").unwrap(); + assert!(matches!( + session.sign_ed25519(SLOT_9A, b"test"), + Err(RatkeyError::EmptySlot { slot: 0x9A }) + )); + } + + #[test] + fn test_touch_policy_always() { + let mut session = MockPivSession::new(); + session.verify_pin("123456").unwrap(); + session + .generate_ed25519(SLOT_9A, TouchPolicy::Always) + .unwrap(); + + session.require_touch(); + assert!(matches!( + session.sign_ed25519(SLOT_9A, b"test"), + Err(RatkeyError::TouchRequired) + )); + + session.simulate_touch(); + assert!(session.sign_ed25519(SLOT_9A, b"test").is_ok()); + } + + #[test] + fn test_touch_policy_never() { + let mut session = MockPivSession::new(); + session.verify_pin("123456").unwrap(); + session + .generate_ed25519(SLOT_9A, TouchPolicy::Never) + .unwrap(); + + // TouchPolicy::Never ignores touch_required. + session.require_touch(); + assert!(session.sign_ed25519(SLOT_9A, b"test").is_ok()); + } + + #[test] + fn test_operations_log() { + let mut session = MockPivSession::new(); + session.verify_pin("123456").unwrap(); + session + .generate_ed25519(SLOT_9A, TouchPolicy::Never) + .unwrap(); + session.sign_ed25519(SLOT_9A, b"test").unwrap(); + + assert_eq!(session.operations.len(), 3); + assert!(matches!( + session.operations[0], + MockOperation::PinVerify { success: true } + )); + assert!(matches!( + session.operations[1], + MockOperation::GenerateEd25519 { slot: 0x9A } + )); + assert!(matches!( + session.operations[2], + MockOperation::SignEd25519 { slot: 0x9A, .. } + )); + } + + #[test] + fn test_without_pin_verify() { + let mut session = MockPivSession::new(); + assert!(matches!( + session.generate_ed25519(SLOT_9A, TouchPolicy::Never), + Err(RatkeyError::PinRequired) + )); + } + + #[test] + fn test_custom_pin() { + let mut session = MockPivSession::new(); + session.set_pin("mypin123"); + assert!(session.verify_pin("123456").is_err()); + assert!(session.verify_pin("mypin123").is_ok()); + } +} diff --git a/crates/rns-ratkey/src/pin.rs b/crates/rns-ratkey/src/pin.rs new file mode 100644 index 0000000..203a187 --- /dev/null +++ b/crates/rns-ratkey/src/pin.rs @@ -0,0 +1,131 @@ +//! PIN cache: `Zeroizing` wiped on drop or expiry. + +use std::time::{Duration, Instant}; +use zeroize::Zeroizing; + +pub struct PinCache { + pin: Option>, + verified_at: Option, + timeout: Duration, +} + +impl PinCache { + /// `Duration::ZERO` disables caching (PIN required every op). + pub fn new(timeout: Duration) -> Self { + Self { + pin: None, + verified_at: None, + timeout, + } + } + + /// 5-minute default. + pub fn default_timeout() -> Self { + Self::new(Duration::from_secs(300)) + } + + pub fn cache(&mut self, pin: &str) { + self.pin = Some(Zeroizing::new(pin.to_string())); + self.verified_at = Some(Instant::now()); + } + + pub fn get(&self) -> Option<&str> { + let pin = self.pin.as_ref()?; + let verified_at = self.verified_at?; + + if self.timeout == Duration::ZERO { + return None; + } + + if verified_at.elapsed() < self.timeout { + Some(pin.as_str()) + } else { + None + } + } + + pub fn is_cached(&self) -> bool { + self.get().is_some() + } + + pub fn remaining(&self) -> Option { + let verified_at = self.verified_at?; + if self.pin.is_none() || self.timeout == Duration::ZERO { + return None; + } + self.timeout.checked_sub(verified_at.elapsed()) + } + + pub fn clear(&mut self) { + self.pin = None; + self.verified_at = None; + } +} + +impl Drop for PinCache { + fn drop(&mut self) { + self.clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::thread::sleep; + + #[test] + fn test_cache_and_retrieve() { + let mut cache = PinCache::new(Duration::from_secs(60)); + assert!(!cache.is_cached()); + assert!(cache.get().is_none()); + + cache.cache("123456"); + assert!(cache.is_cached()); + assert_eq!(cache.get(), Some("123456")); + } + + #[test] + fn test_cache_expiry() { + let mut cache = PinCache::new(Duration::from_millis(50)); + cache.cache("123456"); + assert!(cache.is_cached()); + + sleep(Duration::from_millis(60)); + assert!(!cache.is_cached()); + assert!(cache.get().is_none()); + } + + #[test] + fn test_zero_timeout_never_caches() { + let mut cache = PinCache::new(Duration::ZERO); + cache.cache("123456"); + assert!(!cache.is_cached()); + assert!(cache.get().is_none()); + } + + #[test] + fn test_clear() { + let mut cache = PinCache::new(Duration::from_secs(60)); + cache.cache("123456"); + assert!(cache.is_cached()); + + cache.clear(); + assert!(!cache.is_cached()); + } + + #[test] + fn test_remaining() { + let mut cache = PinCache::new(Duration::from_secs(60)); + assert!(cache.remaining().is_none()); + + cache.cache("123456"); + let remaining = cache.remaining().unwrap(); + assert!(remaining.as_secs() >= 59); + } + + #[test] + fn test_default_timeout() { + let cache = PinCache::default_timeout(); + assert_eq!(cache.timeout, Duration::from_secs(300)); + } +} diff --git a/crates/rns-ratkey/src/provision.rs b/crates/rns-ratkey/src/provision.rs new file mode 100644 index 0000000..ddd7861 --- /dev/null +++ b/crates/rns-ratkey/src/provision.rs @@ -0,0 +1,255 @@ +//! Generate keys on-device, derive identity hash, write `.hwid`. + +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rns_crypto::sha::truncated_hash; + +use crate::error::RatkeyError; +use crate::hwid::*; +use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D, TouchPolicy}; + +#[derive(Debug, Clone)] +pub struct ProvisionResult { + pub config: HwidConfig, + pub ed25519_pub: [u8; 32], + pub x25519_pub: [u8; 32], + /// 16-byte Reticulum identity hash. + pub identity_hash: [u8; 16], + pub identity_hash_hex: String, + pub hwid_path: Option, +} + +#[derive(Debug, Clone)] +pub struct ProvisionConfig { + /// PIV PIN (6-8 chars). + pub pin: String, + pub touch_signing: TouchPolicy, + pub touch_encryption: TouchPolicy, + pub nickname: String, + /// None = don't write to disk. + pub identities_dir: Option, +} + +impl Default for ProvisionConfig { + fn default() -> Self { + Self { + pin: String::new(), + touch_signing: TouchPolicy::Always, + touch_encryption: TouchPolicy::Cached, + nickname: String::new(), + identities_dir: None, + } + } +} + +pub fn provision_mock( + session: &mut MockPivSession, + config: &ProvisionConfig, +) -> Result { + session.verify_pin(&config.pin)?; + + let ed25519_pub = session.generate_ed25519(SLOT_9A, config.touch_signing)?; + let x25519_pub = session.generate_x25519(SLOT_9D, config.touch_encryption)?; + + // Reticulum identity hash: SHA-256(X25519_pub || Ed25519_pub) truncated to 16 bytes. + let mut pub_key_bytes = [0u8; 64]; + pub_key_bytes[..32].copy_from_slice(&x25519_pub); + pub_key_bytes[32..].copy_from_slice(&ed25519_pub); + let identity_hash = truncated_hash(&pub_key_bytes); + let identity_hash_hex = hex::encode(identity_hash); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + + let touch_signing_str = match config.touch_signing { + TouchPolicy::Always => "always", + TouchPolicy::Cached => "cached", + TouchPolicy::Never => "never", + }; + let touch_encryption_str = match config.touch_encryption { + TouchPolicy::Always => "always", + TouchPolicy::Cached => "cached", + TouchPolicy::Never => "never", + }; + + let hwid = HwidConfig { + identity: HwidIdentity { + hash: identity_hash_hex.clone(), + nickname: config.nickname.clone(), + created_at: now, + }, + device: HwidDevice { + device_type: session.device_type.clone(), + serial: session.serial, + firmware: session.firmware.clone(), + }, + keys: HwidKeys { + ed25519_pub: hex::encode(ed25519_pub), + x25519_pub: hex::encode(x25519_pub), + }, + slots: HwidSlots { + signing: "9A".to_string(), + encryption: "9D".to_string(), + }, + policy: HwidPolicy { + pin_cache_timeout: 300, + touch_signing: touch_signing_str.to_string(), + touch_encryption: touch_encryption_str.to_string(), + }, + attestation: HwidAttestation::default(), + app: HwidApp::default(), + backup: HwidBackup::default(), + }; + + let hwid_path = if let Some(ref dir) = config.identities_dir { + let identity_dir = dir.join(&identity_hash_hex); + std::fs::create_dir_all(&identity_dir)?; + let path = identity_dir.join("identity.hwid"); + hwid.to_file(&path)?; + Some(path) + } else { + None + }; + + Ok(ProvisionResult { + config: hwid, + ed25519_pub, + x25519_pub, + identity_hash, + identity_hash_hex, + hwid_path, + }) +} + +/// First 16 bytes of `SHA-256(X25519_pub || Ed25519_pub)`. Matches `rns_identity::Identity::hash()`. +pub fn compute_identity_hash(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> [u8; 16] { + let mut pub_key_bytes = [0u8; 64]; + pub_key_bytes[..32].copy_from_slice(x25519_pub); + pub_key_bytes[32..].copy_from_slice(ed25519_pub); + truncated_hash(&pub_key_bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_provision_mock_basic() { + let mut session = MockPivSession::new(); + let config = ProvisionConfig { + pin: "123456".to_string(), + touch_signing: TouchPolicy::Never, + touch_encryption: TouchPolicy::Never, + nickname: "test key".to_string(), + identities_dir: None, + }; + + let result = provision_mock(&mut session, &config).unwrap(); + + assert_eq!(result.ed25519_pub.len(), 32); + assert_eq!(result.x25519_pub.len(), 32); + assert_eq!(result.identity_hash.len(), 16); + assert_eq!(result.identity_hash_hex.len(), 32); + + let recomputed = compute_identity_hash(&result.ed25519_pub, &result.x25519_pub); + assert_eq!(result.identity_hash, recomputed); + + assert_eq!(result.config.identity.hash, result.identity_hash_hex); + assert_eq!(result.config.identity.nickname, "test key"); + assert_eq!(result.config.device.device_type, "yubikey5"); + assert_eq!(result.config.slots.signing, "9A"); + assert_eq!(result.config.slots.encryption, "9D"); + + assert!(result.hwid_path.is_none()); + } + + #[test] + fn test_provision_writes_hwid_file() { + let mut session = MockPivSession::new(); + let dir = std::env::temp_dir().join("ratkey_test_provision"); + let _ = std::fs::remove_dir_all(&dir); + + let config = ProvisionConfig { + pin: "123456".to_string(), + touch_signing: TouchPolicy::Always, + touch_encryption: TouchPolicy::Cached, + nickname: "my yubikey".to_string(), + identities_dir: Some(dir.clone()), + }; + + let result = provision_mock(&mut session, &config).unwrap(); + + let path = result.hwid_path.as_ref().unwrap(); + assert!(path.exists()); + assert!(path.to_string_lossy().contains("identity.hwid")); + + let loaded = HwidConfig::from_file(path).unwrap(); + assert_eq!(loaded.identity.hash, result.identity_hash_hex); + assert_eq!(loaded.identity.nickname, "my yubikey"); + assert_eq!(loaded.policy.touch_signing, "always"); + assert_eq!(loaded.policy.touch_encryption, "cached"); + + let loaded_ed = loaded.ed25519_pub_bytes().unwrap(); + let loaded_x = loaded.x25519_pub_bytes().unwrap(); + assert_eq!(loaded_ed, result.ed25519_pub); + assert_eq!(loaded_x, result.x25519_pub); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_provision_and_use_identity() { + let mut session = MockPivSession::new(); + session.set_pin("mypin1"); + let dir = std::env::temp_dir().join("ratkey_test_provision_use"); + let _ = std::fs::remove_dir_all(&dir); + + let config = ProvisionConfig { + pin: "mypin1".to_string(), + touch_signing: TouchPolicy::Never, + touch_encryption: TouchPolicy::Never, + nickname: "round-trip test".to_string(), + identities_dir: Some(dir.clone()), + }; + + let result = provision_mock(&mut session, &config).unwrap(); + + let path = result.hwid_path.as_ref().unwrap(); + let mut hw = crate::HardwareIdentity::from_file_mock(path, session).unwrap(); + + let message = b"provisioned and loaded"; + let sig = hw.sign(message).unwrap(); + assert!(hw.verify(message, &sig)); + + assert_eq!(hw.hash(), &result.identity_hash); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_provision_wrong_pin() { + let mut session = MockPivSession::new(); + let config = ProvisionConfig { + pin: "wrong_pin".to_string(), + ..Default::default() + }; + + let err = provision_mock(&mut session, &config).unwrap_err(); + assert!(matches!(err, RatkeyError::PinFailed { .. })); + } + + #[test] + fn test_provision_deterministic_hash() { + let ed = [0xAA; 32]; + let x = [0xBB; 32]; + let hash1 = compute_identity_hash(&ed, &x); + let hash2 = compute_identity_hash(&ed, &x); + assert_eq!(hash1, hash2); + + let hash3 = compute_identity_hash(&[0xCC; 32], &x); + assert_ne!(hash1, hash3); + } +} diff --git a/crates/rns-ratkey/src/session.rs b/crates/rns-ratkey/src/session.rs new file mode 100644 index 0000000..e9f6d6e --- /dev/null +++ b/crates/rns-ratkey/src/session.rs @@ -0,0 +1,174 @@ +//! Real PIV session over PC/SC (YubiKey 5, Nitrokey 3). +//! Requires `hardware` feature + PC/SC daemon (macOS CryptoTokenKit / Linux pcscd / Windows WinSCard). + +use pcsc::{Card, Context, Protocols, Scope, ShareMode}; +use tracing::{debug, warn}; +use zeroize::Zeroize; + +use crate::apdu; +use crate::detect::DeviceType; +use crate::error::RatkeyError; +use crate::pin::PinCache; + +const MAX_RESPONSE: usize = 4096; + +pub struct PivSession { + card: Card, + device_type: DeviceType, + reader_name: String, + serial: Option, + firmware: Option, + pin_cache: PinCache, +} + +impl PivSession { + pub fn connect() -> Result { + 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 { + let ctx = Context::establish(Scope::User)?; + let reader = std::ffi::CString::new(reader_name) + .map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?; + + let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?; + + let resp = transmit(&card, &apdu::select_piv())?; + apdu::check_response(&resp)?; + + let device_type = crate::detect::detect_device_type(reader_name); + debug!( + "PIV session established with {} ({})", + reader_name, + device_type.as_str() + ); + + let (serial, firmware) = crate::detect::read_identity(&card, device_type); + + Ok(Self { + card, + device_type, + reader_name: reader_name.to_string(), + serial, + firmware, + pin_cache: PinCache::default_timeout(), + }) + } + + pub fn device_type(&self) -> DeviceType { + self.device_type + } + + pub fn reader_name(&self) -> &str { + &self.reader_name + } + + pub fn serial(&self) -> Option { + self.serial + } + + pub fn firmware(&self) -> Option<&str> { + self.firmware.as_deref() + } + + /// Probes the attestation slot (F9) — always present on provisioned tokens. + pub fn is_connected(&self) -> bool { + let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION); + let mut buf = vec![0u8; 256]; + self.card.transmit(&cmd, &mut buf).is_ok() + } + + pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> { + let cmd = apdu::verify_pin(pin); + let resp = transmit(&self.card, &cmd)?; + apdu::check_response(&resp)?; + self.pin_cache.cache(pin); + debug!("PIN verified"); + Ok(()) + } + + pub fn change_pin(&mut self, old_pin: &str, new_pin: &str) -> Result<(), RatkeyError> { + let cmd = apdu::change_pin(old_pin, new_pin); + let resp = transmit(&self.card, &cmd)?; + apdu::check_response(&resp)?; + self.pin_cache.cache(new_pin); + debug!("PIN changed"); + Ok(()) + } + + pub fn generate_ed25519( + &self, + slot: u8, + pin_policy: Option, + touch_policy: Option, + ) -> Result<[u8; 32], RatkeyError> { + let cmd = apdu::generate_key(slot, apdu::ALG_ED25519, pin_policy, touch_policy); + let resp = transmit(&self.card, &cmd)?; + let data = apdu::check_response(&resp)?; + apdu::parse_generate_response(data) + } + + pub fn generate_x25519( + &self, + slot: u8, + pin_policy: Option, + touch_policy: Option, + ) -> Result<[u8; 32], RatkeyError> { + let cmd = apdu::generate_key(slot, apdu::ALG_X25519, pin_policy, touch_policy); + let resp = transmit(&self.card, &cmd)?; + let data = apdu::check_response(&resp)?; + apdu::parse_generate_response(data) + } + + pub fn sign_ed25519(&self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> { + let cmd = apdu::sign_ed25519(slot, message); + let resp = transmit(&self.card, &cmd)?; + let data = apdu::check_response(&resp)?; + apdu::parse_sign_response(data) + } + + pub fn ecdh_x25519(&self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> { + let cmd = apdu::ecdh_x25519(slot, peer_pub); + let resp = transmit(&self.card, &cmd)?; + let data = apdu::check_response(&resp)?; + let mut secret = apdu::parse_ecdh_response(data)?; + // Wipes local stack copy only. Caller must zeroize the returned bytes. + let result = secret; + secret.zeroize(); + Ok(result) + } + + /// Returns DER-encoded X.509 attestation certificate. + pub fn attest_key(&self, slot: u8) -> Result, RatkeyError> { + let cmd = apdu::attest_key(slot); + let resp = transmit(&self.card, &cmd)?; + let data = apdu::check_response(&resp)?; + Ok(data.to_vec()) + } + + pub fn read_certificate(&self, slot: u8) -> Result, RatkeyError> { + let cmd = apdu::get_data(slot).ok_or(RatkeyError::EmptySlot { slot })?; + let resp = transmit(&self.card, &cmd)?; + let data = apdu::check_response(&resp)?; + Ok(data.to_vec()) + } + + /// Returns raw metadata TLV bytes. + pub fn read_metadata(&self, slot: u8) -> Result, RatkeyError> { + let cmd = apdu::get_metadata(slot); + let resp = transmit(&self.card, &cmd)?; + let data = apdu::check_response(&resp)?; + Ok(data.to_vec()) + } +} + +fn transmit(card: &Card, command: &[u8]) -> Result, 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()) +} diff --git a/crates/rns-runtime/Cargo.toml b/crates/rns-runtime/Cargo.toml new file mode 100644 index 0000000..23492b5 --- /dev/null +++ b/crates/rns-runtime/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "rns-runtime" +description = "Core runtime, config parsing, and lifecycle for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[features] +default = [] +serial = ["rns-interface/serial"] +ble = ["rns-interface/ble"] + +[dependencies] +rns-crypto = { workspace = true, features = ["std"] } +rns-wire = { workspace = true, features = ["std"] } +rns-identity = { workspace = true } +rns-transport = { workspace = true } +rns-link = { workspace = true } +rns-protocol = { workspace = true } +rns-interface = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +bytes = { workspace = true } +tracing = { workspace = true } +hmac = { workspace = true } +sha2 = { workspace = true } +rmp-serde = { workspace = true } +rmpv = { workspace = true, features = ["with-serde"] } +serde = { workspace = true } +subtle = { workspace = true } +hex = { workspace = true } +nix = { workspace = true } diff --git a/crates/rns-runtime/src/config.rs b/crates/rns-runtime/src/config.rs new file mode 100644 index 0000000..154461b --- /dev/null +++ b/crates/rns-runtime/src/config.rs @@ -0,0 +1,942 @@ +//! INI parser compatible with the ConfigObj subset used by Python Reticulum: +//! nested sections, quoted keys/sections/values, ConfigObj list values, +//! multiline values, `#` comments outside quotes, and boolean variants +//! `True`/`Yes`/`On`/`1`. + +use std::collections::HashMap; +use std::path::Path; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum ConfigError { + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), + #[error("parse error at line {line}: {message}")] + Parse { line: usize, message: String }, + #[error("missing required key: [{section}] {key}")] + MissingKey { section: String, key: String }, + #[error("invalid value for [{section}] {key}: {message}")] + InvalidValue { + section: String, + key: String, + message: String, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ConfigValue { + Scalar(String), + List(Vec), +} + +impl ConfigValue { + fn as_str(&self) -> Option<&str> { + match self { + ConfigValue::Scalar(value) => Some(value.as_str()), + ConfigValue::List(_) => None, + } + } + + fn as_list(&self) -> Vec { + match self { + ConfigValue::Scalar(value) => vec![value.clone()], + ConfigValue::List(values) => values.clone(), + } + } +} + +#[derive(Debug, Clone, Default)] +pub struct ConfigSection { + pub values: HashMap, + value_order: Vec, + pub subsections: HashMap, + subsection_order: Vec, +} + +impl ConfigSection { + pub fn new() -> Self { + Self::default() + } + + pub fn get(&self, key: &str) -> Option<&str> { + self.values.get(key).and_then(ConfigValue::as_str) + } + + pub fn get_bool(&self, key: &str) -> Option { + let v = self.get(key)?; + parse_bool(v) + } + + pub fn get_bool_or(&self, key: &str, default: bool) -> bool { + self.get_bool(key).unwrap_or(default) + } + + pub fn get_int(&self, key: &str) -> Option { + let v = self.get(key)?; + v.parse().ok() + } + + pub fn get_uint(&self, key: &str) -> Option { + let v = self.get(key)?; + v.parse().ok() + } + + pub fn get_float(&self, key: &str) -> Option { + let v = self.get(key)?; + v.parse().ok() + } + + pub fn get_list(&self, key: &str) -> Option> { + let v = self.values.get(key)?; + Some(v.as_list()) + } + + pub fn get_hex(&self, key: &str) -> Option> { + let v = self.get(key)?; + hex_decode(v.trim()) + } + + pub fn has(&self, key: &str) -> bool { + self.values.contains_key(key) + } + + pub fn set(&mut self, key: &str, value: &str) { + self.set_value(key.to_string(), ConfigValue::Scalar(value.to_string())); + } + + pub fn set_list(&mut self, key: &str, value: Vec) { + self.set_value(key.to_string(), ConfigValue::List(value)); + } + + fn set_value(&mut self, key: String, value: ConfigValue) { + if !self.values.contains_key(&key) { + self.value_order.push(key.clone()); + } + self.values.insert(key, value); + } + + fn insert_value( + &mut self, + key: String, + value: ConfigValue, + line: usize, + ) -> Result<(), ConfigError> { + if self.values.contains_key(&key) { + return Err(ConfigError::Parse { + line, + message: "duplicate keyword name".to_string(), + }); + } + self.value_order.push(key.clone()); + self.values.insert(key, value); + Ok(()) + } + + fn insert_subsection( + &mut self, + name: String, + line: usize, + ) -> Result<&mut ConfigSection, ConfigError> { + if self.subsections.contains_key(&name) { + return Err(ConfigError::Parse { + line, + message: "duplicate section name".to_string(), + }); + } + self.subsection_order.push(name.clone()); + self.subsections.insert(name.clone(), ConfigSection::new()); + Ok(self.subsections.get_mut(&name).unwrap()) + } +} + +/// Keys before any `[section]` header land under the empty-string section. +#[derive(Debug, Clone, Default)] +pub struct Config { + pub sections: HashMap, + section_order: Vec, +} + +impl Config { + pub fn new() -> Self { + Self::default() + } + + /// Mirrors Python ConfigObj file loading, including normal OS symlink + /// following. Security policy for config paths must be enforced by callers. + pub fn from_file(path: &Path) -> Result { + let content = std::fs::read_to_string(path)?; + let mut config = Self::parse(&content)?; + config.prepare_loaded_reticulum_config(path)?; + Ok(config) + } + + pub fn parse(input: &str) -> Result { + let mut config = Config::new(); + let mut current_section: Option = None; + let mut current_path: Vec = Vec::new(); + let lines: Vec<&str> = input.lines().collect(); + let mut index = 0; + + while index < lines.len() { + let line_num = index + 1; + let raw_line = lines[index]; + let line = strip_comment(raw_line).trim().to_string(); + + if line.is_empty() { + index += 1; + continue; + } + + if line.starts_with('[') && line.ends_with(']') { + let open_depth = line.chars().take_while(|&ch| ch == '[').count(); + let close_depth = line.chars().rev().take_while(|&ch| ch == ']').count(); + if open_depth != close_depth { + return Err(ConfigError::Parse { + line: line_num, + message: "mismatched section brackets".to_string(), + }); + } + + let name = unquote_token(line[open_depth..line.len() - close_depth].trim()) + .map_err(|message| ConfigError::Parse { + line: line_num, + message, + })?; + if name.is_empty() { + return Err(ConfigError::Parse { + line: line_num, + message: if open_depth == 1 { + "empty section name".to_string() + } else { + "empty subsection name".to_string() + }, + }); + } + + if open_depth == 1 { + if config.sections.contains_key(&name) { + return Err(ConfigError::Parse { + line: line_num, + message: "duplicate section name".to_string(), + }); + } + current_section = Some(name.clone()); + current_path.clear(); + config.section_order.push(name.clone()); + config.sections.insert(name, ConfigSection::new()); + } else { + if current_section.is_none() { + return Err(ConfigError::Parse { + line: line_num, + message: "subsection without parent section".to_string(), + }); + } + + let parent_depth = open_depth - 2; + if current_path.len() < parent_depth { + return Err(ConfigError::Parse { + line: line_num, + message: "section too nested".to_string(), + }); + } + let section_name = current_section.as_ref().unwrap(); + let section = config.sections.get_mut(section_name).unwrap(); + let parent = section_for_path_mut(section, ¤t_path[..parent_depth]); + parent.insert_subsection(name.clone(), line_num)?; + + current_path.truncate(parent_depth); + current_path.push(name); + } + index += 1; + continue; + } + + if let Some(eq_pos) = line.find('=') { + let key = + unquote_token(line[..eq_pos].trim()).map_err(|message| ConfigError::Parse { + line: line_num, + message, + })?; + let (value, consumed_index) = + parse_config_value(line[eq_pos + 1..].trim(), &lines, index)?; + + if key.is_empty() { + return Err(ConfigError::Parse { + line: line_num, + message: "empty key".to_string(), + }); + } + + match ¤t_section { + Some(sec) => { + let section = config.sections.get_mut(sec).unwrap(); + section_for_path_mut(section, ¤t_path) + .insert_value(key, value, line_num)?; + } + None => { + config + .root_section_mut() + .insert_value(key, value, line_num)?; + } + } + index = consumed_index + 1; + continue; + } + + return Err(ConfigError::Parse { + line: line_num, + message: format!("unrecognized line: {line}"), + }); + } + + Ok(config) + } + + pub fn section(&self, name: &str) -> Option<&ConfigSection> { + self.sections.get(name) + } + + pub fn section_mut(&mut self, name: &str) -> Option<&mut ConfigSection> { + self.sections.get_mut(name) + } + + pub fn subsection(&self, section: &str, subsection: &str) -> Option<&ConfigSection> { + self.sections + .get(section) + .and_then(|s| s.subsections.get(subsection)) + } + + pub fn subsections(&self, section: &str) -> Vec<(&str, &ConfigSection)> { + match self.sections.get(section) { + Some(s) => s + .subsection_order + .iter() + .filter_map(|k| s.subsections.get_key_value(k)) + .map(|(k, v)| (k.as_str(), v)) + .collect(), + None => Vec::new(), + } + } + + pub fn default_config() -> &'static str { + DEFAULT_CONFIG + } + + pub fn write_default(path: &Path) -> Result<(), ConfigError> { + std::fs::write(path, DEFAULT_CONFIG)?; + Ok(()) + } + + fn prepare_loaded_reticulum_config(&mut self, _config_path: &Path) -> Result<(), ConfigError> { + let Some(section) = self.section_mut("reticulum") else { + return Ok(()); + }; + + validate_identity_hash_list(section, "remote_management_allowed")?; + validate_identity_hash_list(section, "blackhole_sources")?; + validate_identity_hash_list(section, "interface_discovery_sources")?; + + Ok(()) + } + + fn root_section_mut(&mut self) -> &mut ConfigSection { + if !self.sections.contains_key("") { + self.section_order.push(String::new()); + self.sections.insert(String::new(), ConfigSection::new()); + } + self.sections.get_mut("").unwrap() + } +} + +fn section_for_path_mut<'a>( + mut section: &'a mut ConfigSection, + path: &[String], +) -> &'a mut ConfigSection { + for part in path { + section = section + .subsections + .get_mut(part) + .expect("current subsection path was not initialised"); + } + section +} + +fn unquote_token(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + return Err("empty quoted value".to_string()); + } + let Some(first) = value.chars().next() else { + return Err("empty quoted value".to_string()); + }; + if first == '"' || first == '\'' { + if !value.ends_with(first) || value.len() < 2 { + return Err("parse error in value".to_string()); + } + Ok(value[1..value.len() - 1].to_string()) + } else { + Ok(value.to_string()) + } +} + +fn parse_config_value( + raw: &str, + lines: &[&str], + index: usize, +) -> Result<(ConfigValue, usize), ConfigError> { + if raw.starts_with("\"\"\"") || raw.starts_with("'''") { + return parse_multiline_value(raw, lines, index); + } + + parse_single_line_value(raw) + .map(|value| (value, index)) + .map_err(|message| ConfigError::Parse { + line: index + 1, + message, + }) +} + +fn parse_multiline_value( + raw: &str, + lines: &[&str], + index: usize, +) -> Result<(ConfigValue, usize), ConfigError> { + let quote = &raw[..3]; + let rest = &raw[3..]; + if let Some(end) = rest.find(quote) { + return Ok((ConfigValue::Scalar(rest[..end].to_string()), index)); + } + + let mut value = rest.to_string(); + let mut current = index; + while current + 1 < lines.len() { + current += 1; + value.push('\n'); + let line = lines[current]; + if let Some(end) = line.find(quote) { + value.push_str(&line[..end]); + return Ok((ConfigValue::Scalar(value), current)); + } + value.push_str(line); + } + + Err(ConfigError::Parse { + line: index + 1, + message: "unterminated multiline value".to_string(), + }) +} + +fn parse_single_line_value(raw: &str) -> Result { + let value = raw.trim(); + if value.is_empty() { + return Ok(ConfigValue::Scalar(String::new())); + } + if value == "," { + return Ok(ConfigValue::List(Vec::new())); + } + + let (mut parts, saw_comma) = split_value_parts(value)?; + if saw_comma { + if parts.last().is_some_and(|part| part.trim().is_empty()) { + parts.pop(); + } + let mut values = Vec::with_capacity(parts.len()); + for part in parts { + let part = part.trim(); + if part.is_empty() { + return Err("parse error in value".to_string()); + } + values.push(unquote_token(part)?); + } + return Ok(ConfigValue::List(values)); + } + + Ok(ConfigValue::Scalar(unquote_token(value)?)) +} + +fn split_value_parts(value: &str) -> Result<(Vec, bool), String> { + let mut parts = Vec::new(); + let mut current = String::new(); + let mut quote: Option = None; + let mut quoted_item_closed = false; + let mut item_started = false; + let mut saw_comma = false; + + for ch in value.chars() { + if let Some(q) = quote { + current.push(ch); + if ch == q { + quote = None; + quoted_item_closed = true; + } + continue; + } + + if quoted_item_closed { + if ch == ',' { + parts.push(current.trim().to_string()); + current.clear(); + quoted_item_closed = false; + item_started = false; + saw_comma = true; + } else if ch.is_whitespace() { + current.push(ch); + } else { + return Err("parse error in value".to_string()); + } + continue; + } + + if ch == ',' { + parts.push(current.trim().to_string()); + current.clear(); + item_started = false; + saw_comma = true; + } else if (ch == '"' || ch == '\'') && !item_started { + quote = Some(ch); + item_started = true; + current.push(ch); + } else { + if !ch.is_whitespace() { + item_started = true; + } + current.push(ch); + } + } + + if quote.is_some() { + return Err("parse error in value".to_string()); + } + + if saw_comma { + parts.push(current.trim().to_string()); + } + + Ok((parts, saw_comma)) +} + +/// Truncate at the first `#` outside a quoted string. +fn strip_comment(line: &str) -> &str { + let mut in_quote = false; + let mut quote_char = ' '; + for (i, ch) in line.char_indices() { + if in_quote { + if ch == quote_char { + in_quote = false; + } + } else if ch == '"' || ch == '\'' { + in_quote = true; + quote_char = ch; + } else if ch == '#' { + return &line[..i]; + } + } + line +} + +fn parse_bool(s: &str) -> Option { + match s.to_lowercase().as_str() { + "true" | "yes" | "on" | "1" => Some(true), + "false" | "no" | "off" | "0" => Some(false), + _ => None, + } +} + +fn validate_identity_hash_list(section: &ConfigSection, key: &str) -> Result<(), ConfigError> { + let Some(values) = section.get_list(key) else { + return Ok(()); + }; + + for value in values { + let hexhash = value.trim(); + if hexhash.len() != 32 { + return Err(ConfigError::InvalidValue { + section: "reticulum".to_string(), + key: key.to_string(), + message: format!( + "identity hash {hexhash} must be 32 hexadecimal characters (16 bytes)" + ), + }); + } + if hex_decode(hexhash).is_none() { + return Err(ConfigError::InvalidValue { + section: "reticulum".to_string(), + key: key.to_string(), + message: format!("invalid identity hash: {hexhash}"), + }); + } + } + + Ok(()) +} + +fn hex_decode(s: &str) -> Option> { + if !s.len().is_multiple_of(2) { + return None; + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) + .collect() +} + +const DEFAULT_CONFIG: &str = r#"# This is the default Reticulum config file. + +[reticulum] +enable_transport = False +share_instance = Yes +instance_name = default + +[logging] +loglevel = 4 + +[interfaces] + +[[Default Interface]] +type = AutoInterface +enabled = Yes +"#; + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + #[test] + fn test_parse_empty() { + let config = Config::parse("").unwrap(); + assert!(config.sections.is_empty()); + } + + #[test] + fn test_parse_section() { + let config = Config::parse("[reticulum]\nshare_instance = Yes\n").unwrap(); + let sec = config.section("reticulum").unwrap(); + assert_eq!(sec.get_bool("share_instance"), Some(true)); + } + + #[test] + fn test_parse_subsection() { + let input = r#" +[interfaces] + +[[My UDP Interface]] +type = UDPInterface +enabled = yes +listen_port = 4242 +"#; + let config = Config::parse(input).unwrap(); + let subs = config.subsections("interfaces"); + assert_eq!(subs.len(), 1); + let (name, sub) = &subs[0]; + assert_eq!(*name, "My UDP Interface"); + assert_eq!(sub.get("type"), Some("UDPInterface")); + assert_eq!(sub.get_bool("enabled"), Some(true)); + assert_eq!(sub.get_uint("listen_port"), Some(4242)); + } + + #[test] + fn test_parse_nested_subsection() { + let input = r#" +[interfaces] + +[[OpenCom XL]] +type = RNodeMultiInterface +port = /dev/ttyACM0 + +[[[High Datarate]]] +enabled = yes +vport = 1 +frequency = 2400000000 + +[[[Low Datarate]]] +enabled = no +vport = 0 +frequency = 865600000 +"#; + let config = Config::parse(input).unwrap(); + let iface = config.section("interfaces").unwrap(); + let rnode = iface.subsections.get("OpenCom XL").unwrap(); + assert_eq!(rnode.get("type"), Some("RNodeMultiInterface")); + assert_eq!(rnode.get("port"), Some("/dev/ttyACM0")); + + let high = rnode.subsections.get("High Datarate").unwrap(); + assert_eq!(high.get_bool("enabled"), Some(true)); + assert_eq!(high.get_uint("vport"), Some(1)); + assert_eq!(high.get_uint("frequency"), Some(2_400_000_000)); + + let low = rnode.subsections.get("Low Datarate").unwrap(); + assert_eq!(low.get_bool("enabled"), Some(false)); + assert_eq!(low.get_uint("vport"), Some(0)); + assert_eq!(low.get_uint("frequency"), Some(865_600_000)); + } + + #[test] + fn test_parse_comments() { + let input = "# Full line comment\n[sec]\nkey = value # inline comment\n"; + let config = Config::parse(input).unwrap(); + let sec = config.section("sec").unwrap(); + assert_eq!(sec.get("key"), Some("value")); + } + + #[test] + fn test_parse_bool_variants() { + assert_eq!(parse_bool("True"), Some(true)); + assert_eq!(parse_bool("true"), Some(true)); + assert_eq!(parse_bool("YES"), Some(true)); + assert_eq!(parse_bool("yes"), Some(true)); + assert_eq!(parse_bool("On"), Some(true)); + assert_eq!(parse_bool("1"), Some(true)); + assert_eq!(parse_bool("False"), Some(false)); + assert_eq!(parse_bool("false"), Some(false)); + assert_eq!(parse_bool("NO"), Some(false)); + assert_eq!(parse_bool("no"), Some(false)); + assert_eq!(parse_bool("Off"), Some(false)); + assert_eq!(parse_bool("0"), Some(false)); + assert_eq!(parse_bool("maybe"), None); + } + + #[test] + fn test_get_list() { + let input = "[sec]\nitems = one, two, three\n"; + let config = Config::parse(input).unwrap(); + let sec = config.section("sec").unwrap(); + let list = sec.get_list("items").unwrap(); + assert_eq!(list, vec!["one", "two", "three"]); + } + + #[test] + fn test_get_hex() { + let input = "[sec]\nkey = aabbccdd\n"; + let config = Config::parse(input).unwrap(); + let sec = config.section("sec").unwrap(); + let bytes = sec.get_hex("key").unwrap(); + assert_eq!(bytes, vec![0xaa, 0xbb, 0xcc, 0xdd]); + } + + #[test] + fn test_get_float() { + let input = "[sec]\nval = 1.25\n"; + let config = Config::parse(input).unwrap(); + let sec = config.section("sec").unwrap(); + assert!((sec.get_float("val").unwrap() - 1.25).abs() < f64::EPSILON); + } + + #[test] + fn test_keys_preserve_case_like_configobj() { + let input = "[sec]\nMyKey = hello\n"; + let config = Config::parse(input).unwrap(); + let sec = config.section("sec").unwrap(); + assert_eq!(sec.get("MyKey"), Some("hello")); + assert_eq!(sec.get("mykey"), None); + } + + #[test] + fn test_configobj_quoted_values_and_lists() { + let input = r#" +[sec] +empty = +empty_list = , +quoted_empty = "" +quoted_hash = "value # kept" # dropped +quoted_comma = "one,two" +items = "one", "two,three", four, +"quoted key" = "quoted value" +"#; + let config = Config::parse(input).unwrap(); + let sec = config.section("sec").unwrap(); + assert_eq!(sec.get("empty"), Some("")); + assert_eq!(sec.get_list("empty"), Some(vec![String::new()])); + assert_eq!(sec.get_list("empty_list"), Some(Vec::new())); + assert_eq!(sec.get("quoted_empty"), Some("")); + assert_eq!(sec.get("quoted_hash"), Some("value # kept")); + assert_eq!(sec.get("quoted_comma"), Some("one,two")); + assert_eq!( + sec.get_list("items").unwrap(), + vec!["one", "two,three", "four"] + ); + assert_eq!(sec.get("quoted key"), Some("quoted value")); + } + + #[test] + fn test_configobj_quoted_sections_and_multiline_values() { + let input = "[interfaces]\n[[\"My Interface\"]]\ntype = AutoInterface\nnotes = \"\"\"first\nsecond\"\"\"\n"; + let config = Config::parse(input).unwrap(); + let iface = config.subsection("interfaces", "My Interface").unwrap(); + assert_eq!(iface.get("type"), Some("AutoInterface")); + assert_eq!(iface.get("notes"), Some("first\nsecond")); + } + + #[test] + fn test_duplicate_keys_and_sections_fail_like_configobj() { + assert!(Config::parse("[sec]\nkey = one\nkey = two\n").is_err()); + assert!(Config::parse("[sec]\nkey = one\n[sec]\nkey = two\n").is_err()); + assert!(Config::parse("[interfaces]\n[[iface]]\ntype = A\n[[iface]]\ntype = B\n").is_err()); + } + + #[test] + fn test_malformed_configobj_values_fail() { + assert!(Config::parse("[sec]\nkey = \"unterminated\n").is_err()); + assert!(Config::parse("[sec]\nkey = one,,two\n").is_err()); + assert!(Config::parse("[sec]\nkey = one, , two\n").is_err()); + assert!(Config::parse("[sec]\nkey = \"\"\"unterminated\n").is_err()); + } + + #[test] + fn test_multiple_sections() { + let input = "[reticulum]\nkey1 = v1\n[logging]\nkey2 = v2\n"; + let config = Config::parse(input).unwrap(); + assert_eq!(config.section("reticulum").unwrap().get("key1"), Some("v1")); + assert_eq!(config.section("logging").unwrap().get("key2"), Some("v2")); + } + + #[test] + fn test_multiple_subsections() { + let input = r#" +[interfaces] +[[iface1]] +type = TCPClientInterface +[[iface2]] +type = UDPInterface +"#; + let config = Config::parse(input).unwrap(); + let subs = config.subsections("interfaces"); + assert_eq!(subs.len(), 2); + assert_eq!(subs[0].0, "iface1"); + assert_eq!(subs[1].0, "iface2"); + } + + #[test] + fn test_named_subsection_lookup() { + let input = r#" +[interfaces] +[[iface1]] +type = TCPClientInterface +[[iface2]] +type = UDPInterface +"#; + let config = Config::parse(input).unwrap(); + assert_eq!( + config + .subsection("interfaces", "iface2") + .and_then(|s| s.get("type")), + Some("UDPInterface") + ); + assert!(config.subsection("interfaces", "missing").is_none()); + } + + #[test] + fn test_subsection_without_section_fails() { + let result = Config::parse("[[orphan]]\nkey = val\n"); + assert!(result.is_err()); + } + + #[test] + fn test_nested_subsection_without_parent_fails() { + let result = Config::parse("[interfaces]\n[[[orphan]]]\nkey = val\n"); + assert!(result.is_err()); + } + + #[test] + fn test_empty_section_name_fails() { + let result = Config::parse("[]\nkey = val\n"); + assert!(result.is_err()); + } + + #[test] + fn test_default_config_parses() { + let config = Config::parse(Config::default_config()).unwrap(); + let ret = config.section("reticulum").unwrap(); + assert_eq!(ret.get_bool("share_instance"), Some(true)); + assert_eq!(ret.get_bool("enable_transport"), Some(false)); + assert_eq!(ret.get("instance_name"), Some("default")); + assert_eq!(ret.get_uint("shared_instance_port"), None); + } + + #[test] + fn test_loaded_config_rejects_malformed_identity_hash_lists() { + let dir = unique_test_dir("hash-list-validation"); + let path = dir.join("config"); + std::fs::write(&path, "[reticulum]\nremote_management_allowed = deadbeef\n").unwrap(); + + assert!(matches!( + Config::from_file(&path), + Err(ConfigError::InvalidValue { key, .. }) if key == "remote_management_allowed" + )); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn test_loaded_config_preserves_network_identity_value_without_side_effect() { + let dir = unique_test_dir("network-identity"); + let identity = dir.join("network.identity"); + let path = dir.join("config"); + std::fs::write( + &path, + format!( + "[reticulum]\nnetwork_identity = {}\n", + identity.file_name().unwrap().to_string_lossy() + ), + ) + .unwrap(); + + let config = Config::from_file(&path).unwrap(); + assert!(!identity.is_file()); + let expected = identity.file_name().unwrap().to_string_lossy(); + assert_eq!( + config + .section("reticulum") + .and_then(|section| section.get("network_identity")), + Some(expected.as_ref()) + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn test_from_file_follows_symlink_like_configobj() { + let dir = unique_test_dir("symlink-config"); + let target = dir.join("target_config"); + let link = dir.join("config"); + std::fs::write(&target, "[reticulum]\nshare_instance = No\n").unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + + let config = Config::from_file(&link).unwrap(); + assert_eq!( + config + .section("reticulum") + .and_then(|section| section.get_bool("share_instance")), + Some(false) + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn test_get_bool_or_default() { + let sec = ConfigSection::new(); + assert!(sec.get_bool_or("missing", true)); + assert!(!sec.get_bool_or("missing", false)); + } + + #[test] + fn test_strip_comment_in_quotes() { + let result = strip_comment(r#"key = "value # with hash""#); + assert_eq!(result, r#"key = "value # with hash""#); + } + + fn unique_test_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "reticulum_config_test_{name}_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } +} diff --git a/crates/rns-runtime/src/constants.rs b/crates/rns-runtime/src/constants.rs new file mode 100644 index 0000000..9b428f4 --- /dev/null +++ b/crates/rns-runtime/src/constants.rs @@ -0,0 +1,40 @@ +pub const LOCAL_INTERFACE_PORT: u16 = 37428; +pub const LOCAL_CONTROL_PORT: u16 = 37429; + +pub const JOB_INTERVAL: u64 = 300; +pub const CLEAN_INTERVAL: u64 = 900; +pub const PERSIST_INTERVAL: u64 = 43200; + +/// Minimum spacing between externally-requested persists. +pub const GRACIOUS_PERSIST_INTERVAL: u64 = 300; + +pub const RESOURCE_CACHE: u64 = 86400; +pub const MAX_QUEUED_ANNOUNCES: usize = 16384; +pub const QUEUED_ANNOUNCE_LIFE: u64 = 86400; + +/// Percentage matching Python `Reticulum.ANNOUNCE_CAP = 2`; transport actor +/// divides by 100 before applying to bitrate math. +pub const ANNOUNCE_CAP: f64 = 2.0; + +pub const MINIMUM_BITRATE: u64 = 5; +pub const IFAC_MIN_SIZE: usize = 1; +pub const LOG_MAXSIZE: u64 = 5_242_880; +pub const DEFAULT_INSTANCE_NAME: &str = "default"; + +pub const RPC_AUTH_TAG: &[u8] = b"reticulum_rs_rpc_auth_v1"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_constants() { + assert_eq!(LOCAL_INTERFACE_PORT, 37428); + assert_eq!(LOCAL_CONTROL_PORT, 37429); + assert_eq!(JOB_INTERVAL, 300); + assert_eq!(CLEAN_INTERVAL, 900); + assert_eq!(PERSIST_INTERVAL, 43200); + assert_eq!(RESOURCE_CACHE, 86400); + assert_eq!(LOG_MAXSIZE, 5_242_880); + } +} diff --git a/crates/rns-runtime/src/interface_factory.rs b/crates/rns-runtime/src/interface_factory.rs new file mode 100644 index 0000000..28800d7 --- /dev/null +++ b/crates/rns-runtime/src/interface_factory.rs @@ -0,0 +1,1986 @@ +//! Mirrors `Reticulum._synthesize_interface` in the Python reference but +//! rejects external-program interfaces. + +use crate::config::ConfigSection; +use rns_interface::tcp::{TcpClientConfig, TcpServerConfig}; +use rns_interface::traits::InterfaceMode; +use rns_interface::udp::UdpInterfaceConfig; +use thiserror::Error; +use tracing::{debug, warn}; + +#[derive(Debug, Error)] +pub enum InterfaceFactoryError { + #[error("unknown interface type: {0}")] + UnknownType(String), + #[error("missing required field '{field}' for interface '{name}'")] + MissingField { name: String, field: String }, + #[error("invalid value for '{field}': {message}")] + InvalidValue { field: String, message: String }, + #[error("interface disabled: {0}")] + Disabled(String), +} + +#[derive(Debug, Clone)] +pub enum InterfaceConfig { + TcpClient(TcpClientConfig), + TcpServer(TcpServerConfig), + Udp(UdpInterfaceConfig), + #[cfg(feature = "serial")] + Serial(SerialInterfaceConfig), + #[cfg(feature = "serial")] + KissSerial(KissSerialConfig), + Auto(AutoInterfaceConfig), + #[cfg(feature = "serial")] + RNode(RNodeInterfaceConfig), + Local(LocalInterfaceConfig), + I2P(I2PInterfaceConfig), + Pipe(PipeInterfaceConfig), + #[cfg(feature = "serial")] + RNodeMulti(RNodeMultiInterfaceConfig), + #[cfg(feature = "serial")] + AX25KISS(AX25KISSInterfaceConfig), + Backbone(BackboneInterfaceConfig), + #[cfg(feature = "ble")] + BleRNode(BleRNodeInterfaceConfig), +} + +#[cfg(feature = "serial")] +#[derive(Debug, Clone)] +pub struct SerialInterfaceConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + pub data_bits: u8, + pub parity: String, + pub stop_bits: u8, + pub mode: InterfaceMode, +} + +#[cfg(feature = "serial")] +#[derive(Debug, Clone)] +pub struct KissSerialConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + pub mode: InterfaceMode, +} + +#[derive(Debug, Clone)] +pub struct AutoInterfaceConfig { + pub name: String, + pub group_id: String, + pub discovery_scope: rns_interface::auto::DiscoveryScope, + pub discovery_port: u16, + pub data_port: u16, + pub multicast_address_type: rns_interface::auto::McastAddrType, + pub devices: Option>, + pub ignored_devices: Vec, + pub configured_bitrate: Option, + pub mode: InterfaceMode, +} + +#[cfg(feature = "serial")] +#[derive(Debug, Clone)] +pub struct RNodeInterfaceConfig { + pub name: String, + pub port: String, + pub frequency: u32, + pub bandwidth: u32, + pub spreading_factor: u8, + pub coding_rate: u8, + pub tx_power: i8, + pub mode: InterfaceMode, +} + +/// LoRa RNode reached over Bluetooth LE. +#[cfg(feature = "ble")] +#[derive(Debug, Clone)] +pub struct BleRNodeInterfaceConfig { + pub name: String, + /// `ble://` URI: MAC, adapter-local name, or empty for any RNode. + pub port: String, + pub frequency: u32, + pub bandwidth: u32, + pub spreading_factor: u8, + pub coding_rate: u8, + pub tx_power: i8, + pub mode: InterfaceMode, +} + +#[derive(Debug, Clone)] +pub struct LocalInterfaceConfig { + pub name: String, + pub port: u16, + pub mode: InterfaceMode, +} + +/// Requires a local I2P router reachable via the SAM API. +#[derive(Debug, Clone)] +pub struct I2PInterfaceConfig { + pub name: String, + pub connectable: bool, + pub peers: Vec, + pub i2p_sam_host: String, + pub i2p_sam_port: u16, + pub mode: InterfaceMode, +} + +/// Subprocess; frames carried over its stdio. +#[derive(Debug, Clone)] +pub struct PipeInterfaceConfig { + pub name: String, + pub command: String, + /// Respawn delay after EOF, seconds. + pub respawn_delay: u64, + pub mode: InterfaceMode, +} + +/// Multi-transceiver RNode (e.g. OpenCom XL) with per-vport params. +#[cfg(feature = "serial")] +#[derive(Debug, Clone)] +pub struct RNodeMultiInterfaceConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + pub flow_control: bool, + pub subinterfaces: Vec, + pub mode: InterfaceMode, +} + +#[cfg(feature = "serial")] +#[derive(Debug, Clone)] +pub struct RNodeSubInterfaceConfig { + pub name: String, + pub frequency: u32, + pub bandwidth: u32, + pub spreading_factor: u8, + pub coding_rate: u8, + pub tx_power: u8, + pub vport: u8, + pub enabled: bool, + pub flow_control: bool, + pub outgoing: bool, + pub st_alock: Option, + pub lt_alock: Option, + pub mode: InterfaceMode, +} + +/// KISS serial wrapped in AX.25 frames for amateur-radio compliance; prefer +/// plain `KISSInterface` when AX.25 isn't required. +#[cfg(feature = "serial")] +#[derive(Debug, Clone)] +pub struct AX25KISSInterfaceConfig { + pub name: String, + pub port: String, + pub baud_rate: u32, + pub callsign: String, + pub ssid: u8, + pub preamble: u32, + pub txtail: u32, + pub persistence: u32, + pub slottime: u32, + pub flow_control: bool, + pub mode: InterfaceMode, +} + +/// Wire-compatible with Python `BackboneInterface`. Per-peer TCP keepalive + +/// `TCP_USER_TIMEOUT` tuning matches Python `set_timeouts_linux()`. +#[derive(Debug, Clone)] +pub struct BackboneInterfaceConfig { + pub name: String, + pub listen_on: Option, + pub target_host: Option, + pub port: u16, + pub device: Option, + pub prefer_ipv6: bool, + pub mode: InterfaceMode, + /// Initial connect timeout (seconds). Python default: 5. + pub connect_timeout: u64, + /// Client reconnection budget. `None` = retry forever (Python default). + pub max_reconnect_tries: Option, + /// Parsed for Python config compatibility; advisory only. + pub i2p_tunneled: bool, +} + +fn parse_interface_mode(s: &str) -> Option { + match s.to_lowercase().as_str() { + "full" => Some(InterfaceMode::Full), + "pointtopoint" | "point_to_point" => Some(InterfaceMode::PointToPoint), + "access_point" | "accesspoint" | "ap" => Some(InterfaceMode::AccessPoint), + "roaming" => Some(InterfaceMode::Roaming), + "boundary" => Some(InterfaceMode::Boundary), + "gateway" | "gw" => Some(InterfaceMode::Gateway), + _ => None, + } +} + +pub fn synthesize_interface( + name: &str, + section: &ConfigSection, +) -> Result { + let enabled = section + .get_bool("enabled") + .or_else(|| section.get_bool("interface_enabled")) + .unwrap_or(true); + + if !enabled { + debug!(interface = %name, "interface disabled in config, skipping"); + return Err(InterfaceFactoryError::Disabled(name.to_string())); + } + + let iface_type = section.get("type").ok_or_else(|| { + warn!(interface = %name, "interface missing 'type' field"); + InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "type".to_string(), + } + })?; + + debug!(interface = %name, kind = iface_type, "synthesizing interface"); + + let mode = section + .get("interface_mode") + .or_else(|| section.get("mode")) + .and_then(parse_interface_mode) + .unwrap_or(InterfaceMode::Full); + + match iface_type { + "TCPClientInterface" => synthesize_tcp_client(name, section, mode), + "TCPServerInterface" => synthesize_tcp_server(name, section, mode), + "UDPInterface" => synthesize_udp(name, section, mode), + #[cfg(feature = "serial")] + "SerialInterface" => synthesize_serial(name, section, mode), + #[cfg(feature = "serial")] + "KISSInterface" => synthesize_kiss_serial(name, section, mode), + "AutoInterface" => synthesize_auto(name, section, mode), + "RNodeInterface" => { + let port = section.get("port").unwrap_or(""); + if port.starts_with("ble://") { + #[cfg(feature = "ble")] + { + return synthesize_ble_rnode(name, section, mode); + } + #[cfg(not(feature = "ble"))] + { + return Err(InterfaceFactoryError::Disabled(format!( + "RNodeInterface '{name}' has ble:// port but 'ble' feature is not enabled" + ))); + } + } + // Android USB-OTG ports vanish on replug; add them at runtime after + // the device is present. + if port.starts_with("androidusb://") { + return Err(InterfaceFactoryError::Disabled(format!( + "RNodeInterface '{name}' is an Android USB-OTG entry — skipped at startup; re-add from the UI after plugging the device in" + ))); + } + #[cfg(feature = "serial")] + { + synthesize_rnode(name, section, mode) + } + #[cfg(not(feature = "serial"))] + { + Err(InterfaceFactoryError::Disabled(format!( + "RNodeInterface '{name}' requires 'serial' feature for serial ports" + ))) + } + } + "LocalInterface" => synthesize_local(name, section, mode), + "I2PInterface" => synthesize_i2p(name, section, mode), + "PipeInterface" => synthesize_pipe(name, section, mode), + #[cfg(feature = "serial")] + "RNodeMultiInterface" => synthesize_rnode_multi(name, section, mode), + #[cfg(feature = "serial")] + "AX25KISSInterface" => synthesize_ax25kiss(name, section, mode), + "BackboneInterface" => synthesize_backbone(name, section, mode), + other => Err(InterfaceFactoryError::UnknownType(other.to_string())), + } +} + +fn synthesize_tcp_client( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let host = section + .get("target_host") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "target_host".to_string(), + })?; + + let port = + section + .get_uint("target_port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "target_port".to_string(), + })? as u16; + + let mut config = TcpClientConfig::new(name, host, port); + config.mode = mode; + + if let Some(kiss) = section.get_bool("kiss_framing") { + config.kiss_framing = kiss; + } + if let Some(timeout) = section.get_uint("connect_timeout") { + config.connect_timeout_secs = timeout; + } + if let Some(retries) = section.get_uint("max_reconnect_tries") { + config.max_reconnect_tries = Some(retries as usize); + } + + Ok(InterfaceConfig::TcpClient(config)) +} + +fn synthesize_tcp_server( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let ip = section.get("listen_ip").unwrap_or("0.0.0.0"); + + let port = + section + .get_uint("listen_port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "listen_port".to_string(), + })? as u16; + + let mut config = TcpServerConfig::new(name, ip, port); + config.mode = mode; + + if let Some(kiss) = section.get_bool("kiss_framing") { + config.kiss_framing = kiss; + } + if let Some(ipv6) = section.get_bool("prefer_ipv6") { + config.prefer_ipv6 = ipv6; + } + + Ok(InterfaceConfig::TcpServer(config)) +} + +fn synthesize_udp( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let mut config = UdpInterfaceConfig::new(name); + config.mode = mode; + + if let Some(ip) = section.get("listen_ip") { + config.listen_ip = Some(ip.to_string()); + } + if let Some(port) = section.get_uint("listen_port") { + config.listen_port = Some(port as u16); + } + if let Some(ip) = section.get("forward_ip") { + config.forward_ip = Some(ip.to_string()); + } + if let Some(port) = section.get_uint("forward_port") { + config.forward_port = Some(port as u16); + } + if let Some(device) = section.get("device") { + config.device = Some(device.to_string()); + } + + Ok(InterfaceConfig::Udp(config)) +} + +#[cfg(feature = "serial")] +fn synthesize_serial( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let port = section + .get("port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "port".to_string(), + })? + .to_string(); + + let baud_rate = section + .get_uint("speed") + .or_else(|| section.get_uint("baud_rate")) + .unwrap_or(9600) as u32; + + let data_bits = section + .get_uint("databits") + .or_else(|| section.get_uint("data_bits")) + .unwrap_or(8) as u8; + + let parity = section.get("parity").unwrap_or("N").to_string(); + + let stop_bits = section + .get_uint("stopbits") + .or_else(|| section.get_uint("stop_bits")) + .unwrap_or(1) as u8; + + Ok(InterfaceConfig::Serial(SerialInterfaceConfig { + name: name.to_string(), + port, + baud_rate, + data_bits, + parity, + stop_bits, + mode, + })) +} + +#[cfg(feature = "serial")] +fn synthesize_kiss_serial( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let port = section + .get("port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "port".to_string(), + })? + .to_string(); + + let baud_rate = section + .get_uint("speed") + .or_else(|| section.get_uint("baud_rate")) + .unwrap_or(9600) as u32; + + Ok(InterfaceConfig::KissSerial(KissSerialConfig { + name: name.to_string(), + port, + baud_rate, + mode, + })) +} + +fn synthesize_auto( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + use std::str::FromStr; + + let group_id = section.get("group_id").unwrap_or("reticulum").to_string(); + + let discovery_scope = match section.get("discovery_scope") { + Some(s) => rns_interface::auto::DiscoveryScope::from_str(s).map_err(|message| { + InterfaceFactoryError::InvalidValue { + field: "discovery_scope".to_string(), + message, + } + })?, + None => rns_interface::auto::DiscoveryScope::Link, + }; + + let discovery_port = section.get_uint("discovery_port").unwrap_or(29716) as u16; + let data_port = section.get_uint("data_port").unwrap_or(42671) as u16; + + let multicast_address_type = match section.get("multicast_address_type") { + Some(s) => rns_interface::auto::McastAddrType::from_str(s).map_err(|message| { + InterfaceFactoryError::InvalidValue { + field: "multicast_address_type".to_string(), + message, + } + })?, + None => rns_interface::auto::McastAddrType::Temporary, + }; + + // Python: comma-separated `devices` (whitelist) and `ignored_devices` (blacklist). + let devices = section.get("devices").map(|s| { + s.split(',') + .map(|n| n.trim().to_string()) + .filter(|n| !n.is_empty()) + .collect::>() + }); + let ignored_devices = section + .get("ignored_devices") + .map(|s| { + s.split(',') + .map(|n| n.trim().to_string()) + .filter(|n| !n.is_empty()) + .collect::>() + }) + .unwrap_or_default(); + + let configured_bitrate = section + .get_uint("configured_bitrate") + .or_else(|| section.get_uint("bitrate")); + + Ok(InterfaceConfig::Auto(AutoInterfaceConfig { + name: name.to_string(), + group_id, + discovery_scope, + discovery_port, + data_port, + multicast_address_type, + devices, + ignored_devices, + configured_bitrate, + mode, + })) +} + +#[cfg(feature = "serial")] +fn synthesize_rnode( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let port = section + .get("port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "port".to_string(), + })? + .to_string(); + + let frequency = + section + .get_uint("frequency") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "frequency".to_string(), + })? as u32; + + let bandwidth = section.get_uint("bandwidth").unwrap_or(125000) as u32; + + let spreading_factor = section + .get_uint("spreadingfactor") + .or_else(|| section.get_uint("spreading_factor")) + .unwrap_or(7) as u8; + + let coding_rate = section + .get_uint("codingrate") + .or_else(|| section.get_uint("coding_rate")) + .unwrap_or(5) as u8; + + let tx_power = section + .get_int("txpower") + .or_else(|| section.get_int("tx_power")) + .unwrap_or(17) as i8; + + Ok(InterfaceConfig::RNode(RNodeInterfaceConfig { + name: name.to_string(), + port, + frequency, + bandwidth, + spreading_factor, + coding_rate, + tx_power, + mode, + })) +} + +#[cfg(feature = "ble")] +fn synthesize_ble_rnode( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let port = section + .get("port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "port".to_string(), + })? + .to_string(); + + let frequency = + section + .get_uint("frequency") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "frequency".to_string(), + })? as u32; + + let bandwidth = section.get_uint("bandwidth").unwrap_or(125000) as u32; + + let spreading_factor = section + .get_uint("spreadingfactor") + .or_else(|| section.get_uint("spreading_factor")) + .unwrap_or(7) as u8; + + let coding_rate = section + .get_uint("codingrate") + .or_else(|| section.get_uint("coding_rate")) + .unwrap_or(5) as u8; + + let tx_power = section + .get_int("txpower") + .or_else(|| section.get_int("tx_power")) + .unwrap_or(17) as i8; + + Ok(InterfaceConfig::BleRNode(BleRNodeInterfaceConfig { + name: name.to_string(), + port, + frequency, + bandwidth, + spreading_factor, + coding_rate, + tx_power, + mode, + })) +} + +fn synthesize_local( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let port = section + .get_uint("port") + .unwrap_or(crate::constants::LOCAL_INTERFACE_PORT as u64) as u16; + + Ok(InterfaceConfig::Local(LocalInterfaceConfig { + name: name.to_string(), + port, + mode, + })) +} + +fn synthesize_i2p( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let connectable = section.get_bool("connectable").unwrap_or(false); + let peers = section + .get("peers") + .map(|s| { + s.split(',') + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()) + .collect() + }) + .unwrap_or_default(); + let i2p_sam_host = section + .get("i2p_sam_host") + .unwrap_or("127.0.0.1") + .to_string(); + let i2p_sam_port = section.get_uint("i2p_sam_port").unwrap_or(7656) as u16; + + Ok(InterfaceConfig::I2P(I2PInterfaceConfig { + name: name.to_string(), + connectable, + peers, + i2p_sam_host, + i2p_sam_port, + mode, + })) +} + +fn synthesize_pipe( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let command = section + .get("command") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "command".to_string(), + })? + .to_string(); + + let respawn_delay = section.get_uint("respawn_delay").unwrap_or(5); + + Ok(InterfaceConfig::Pipe(PipeInterfaceConfig { + name: name.to_string(), + command, + respawn_delay, + mode, + })) +} + +#[cfg(feature = "serial")] +fn synthesize_rnode_multi( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let port = section + .get("port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "port".to_string(), + })? + .to_string(); + + let baud_rate = section + .get_uint("speed") + .or_else(|| section.get_uint("baud_rate")) + .unwrap_or(115200) as u32; + let parent_flow_control = section.get_bool("flow_control").unwrap_or(false); + + let mut subinterfaces = Vec::new(); + let mut seen_vports = std::collections::HashSet::new(); + for (sub_name, sub_section) in §ion.subsections { + let enabled = sub_section + .get_bool("interface_enabled") + .or_else(|| sub_section.get_bool("enabled")) + .unwrap_or(true); + if !enabled { + continue; + } + + let vport = + sub_section + .get_uint("vport") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: format!("{name}/{sub_name}"), + field: "vport".to_string(), + })? as u8; + if vport as usize > rns_interface::rnode_multi::MAX_SUBINTERFACES { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{sub_name}.vport"), + message: format!( + "virtual port {} exceeds max {}", + vport, + rns_interface::rnode_multi::MAX_SUBINTERFACES + ), + }); + } + if !seen_vports.insert(vport) { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{sub_name}.vport"), + message: format!("duplicate virtual port {vport}"), + }); + } + + let frequency = sub_section.get_uint("frequency").ok_or_else(|| { + InterfaceFactoryError::MissingField { + name: format!("{name}/{sub_name}"), + field: "frequency".to_string(), + } + })? as u32; + let bandwidth = sub_section.get_uint("bandwidth").unwrap_or(125000) as u32; + let spreading_factor = sub_section + .get_uint("spreadingfactor") + .or_else(|| sub_section.get_uint("spreading_factor")) + .unwrap_or(7) as u8; + let coding_rate = sub_section + .get_uint("codingrate") + .or_else(|| sub_section.get_uint("coding_rate")) + .unwrap_or(5) as u8; + let tx_power = sub_section + .get_uint("txpower") + .or_else(|| sub_section.get_uint("tx_power")) + .unwrap_or(14) as u8; + let flow_control = sub_section + .get_bool("flow_control") + .unwrap_or(parent_flow_control); + let outgoing = sub_section.get_bool("outgoing").unwrap_or(true); + let st_alock = sub_section + .get_float("airtime_limit_short") + .or_else(|| sub_section.get_float("st_alock")) + .map(|v| v as f32); + let lt_alock = sub_section + .get_float("airtime_limit_long") + .or_else(|| sub_section.get_float("lt_alock")) + .map(|v| v as f32); + let sub_mode = sub_section + .get("interface_mode") + .or_else(|| sub_section.get("mode")) + .and_then(parse_interface_mode) + .unwrap_or(mode); + + let parsed = RNodeSubInterfaceConfig { + name: sub_name.clone(), + frequency, + bandwidth, + spreading_factor, + coding_rate, + tx_power, + vport, + enabled, + flow_control, + outgoing, + st_alock, + lt_alock, + mode: sub_mode, + }; + validate_rnode_multi_subinterface(name, &parsed)?; + subinterfaces.push(parsed); + } + + if subinterfaces.is_empty() { + return Err(InterfaceFactoryError::InvalidValue { + field: "subinterfaces".to_string(), + message: format!("RNodeMultiInterface '{name}' has no enabled subinterfaces"), + }); + } + + if subinterfaces.len() > rns_interface::rnode_multi::MAX_SUBINTERFACES { + return Err(InterfaceFactoryError::InvalidValue { + field: "subinterfaces".to_string(), + message: format!( + "{} enabled subinterfaces exceeds max {}", + subinterfaces.len(), + rns_interface::rnode_multi::MAX_SUBINTERFACES + ), + }); + } + subinterfaces.sort_by_key(|sub| sub.vport); + + Ok(InterfaceConfig::RNodeMulti(RNodeMultiInterfaceConfig { + name: name.to_string(), + port, + baud_rate, + flow_control: parent_flow_control, + subinterfaces, + mode, + })) +} + +#[cfg(feature = "serial")] +fn validate_rnode_multi_subinterface( + parent: &str, + sub: &RNodeSubInterfaceConfig, +) -> Result<(), InterfaceFactoryError> { + if sub.tx_power > 37 { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.txpower", sub.name), + message: format!("{} exceeds max 37 dBm", sub.tx_power), + }); + } + if !(7_800..=1_625_000).contains(&sub.bandwidth) { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.bandwidth", sub.name), + message: format!("{} is outside 7800..=1625000 Hz", sub.bandwidth), + }); + } + if !(5..=12).contains(&sub.spreading_factor) { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.spreadingfactor", sub.name), + message: format!("{} is outside 5..=12", sub.spreading_factor), + }); + } + if !(5..=8).contains(&sub.coding_rate) { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.codingrate", sub.name), + message: format!("{} is outside 5..=8", sub.coding_rate), + }); + } + if let Some(v) = sub.st_alock + && !(0.0..=100.0).contains(&v) + { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.airtime_limit_short", sub.name), + message: format!("{v} is outside 0..=100 percent"), + }); + } + if let Some(v) = sub.lt_alock + && !(0.0..=100.0).contains(&v) + { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.airtime_limit_long", sub.name), + message: format!("{v} is outside 0..=100 percent"), + }); + } + if sub.frequency == 0 { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.frequency", sub.name), + message: format!( + "RNodeMultiInterface '{parent}' subinterface frequency must be non-zero" + ), + }); + } + Ok(()) +} + +#[cfg(feature = "serial")] +fn synthesize_ax25kiss( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let port = section + .get("port") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "port".to_string(), + })? + .to_string(); + + let callsign = section + .get("callsign") + .ok_or_else(|| InterfaceFactoryError::MissingField { + name: name.to_string(), + field: "callsign".to_string(), + })? + .to_string(); + + let baud_rate = section + .get_uint("speed") + .or_else(|| section.get_uint("baud_rate")) + .unwrap_or(9600) as u32; + + let ssid = section.get_uint("ssid").unwrap_or(0) as u8; + let preamble = section.get_uint("preamble").unwrap_or(150) as u32; + let txtail = section.get_uint("txtail").unwrap_or(10) as u32; + let persistence = section.get_uint("persistence").unwrap_or(200) as u32; + let slottime = section.get_uint("slottime").unwrap_or(20) as u32; + let flow_control = section.get_bool("flow_control").unwrap_or(false); + + Ok(InterfaceConfig::AX25KISS(AX25KISSInterfaceConfig { + name: name.to_string(), + port, + baud_rate, + callsign, + ssid, + preamble, + txtail, + persistence, + slottime, + flow_control, + mode, + })) +} + +// `target_host`/`remote` selects client mode; otherwise listen. +fn synthesize_backbone( + name: &str, + section: &ConfigSection, + mode: InterfaceMode, +) -> Result { + let listen_on = section.get("listen_on").map(|s| s.to_string()); + let target_host = section + .get("target_host") + .or_else(|| section.get("remote")) + .map(|s| s.to_string()); + let port = section + .get_uint("port") + .or_else(|| section.get_uint("listen_port")) + .or_else(|| section.get_uint("target_port")) + .unwrap_or(4242) as u16; + let device = section.get("device").map(|s| s.to_string()); + let prefer_ipv6 = section.get_bool("prefer_ipv6").unwrap_or(false); + let connect_timeout = section.get_uint("connect_timeout").unwrap_or(5); + let max_reconnect_tries = section.get_uint("max_reconnect_tries").map(|v| v as usize); + let i2p_tunneled = section.get_bool("i2p_tunneled").unwrap_or(false); + + Ok(InterfaceConfig::Backbone(BackboneInterfaceConfig { + name: name.to_string(), + listen_on, + target_host, + port, + device, + prefer_ipv6, + mode, + connect_timeout, + max_reconnect_tries, + i2p_tunneled, + })) +} + +/// Options shared across interface variants, applied post-construction. +pub struct InterfacePostInit { + pub outgoing: bool, + pub bitrate: Option, + pub announce_cap: Option, + pub announce_rate_target: Option, + pub announce_rate_grace: Option, + pub announce_rate_penalty: Option, + pub ifac_network_name: Option, + pub ifac_passphrase: Option, + pub ifac_size: Option, + /// Fallback when `ifac_size` is unset; per-class in Python. + pub default_ifac_size: usize, + pub ingress_control: bool, + /// Per-interface overrides for Python `ic_*` ingress knobs. + pub ingress_overrides: rns_transport::ingress::IngressOverrides, +} + +impl InterfacePostInit { + pub fn from_section(section: &ConfigSection) -> Self { + let ingress_control = section.get_bool("ingress_control").unwrap_or(true); + let announce_rate_target = section.get_uint("announce_rate_target"); + let ingress_overrides = rns_transport::ingress::IngressOverrides { + enabled: if ingress_control { None } else { Some(false) }, + burst_freq_new: section.get_float("ic_burst_freq_new"), + burst_freq: section.get_float("ic_burst_freq"), + new_time: section.get_float("ic_new_time"), + burst_hold: section.get_float("ic_burst_hold"), + burst_penalty: section.get_float("ic_burst_penalty"), + max_held: section + .get_uint("ic_max_held_announces") + .map(|v| v as usize), + held_release_interval: section.get_float("ic_held_release_interval"), + }; + Self { + outgoing: section.get_bool("outgoing").unwrap_or(true), + bitrate: section.get_uint("bitrate"), + announce_cap: section.get_float("announce_cap"), + announce_rate_target, + announce_rate_grace: section + .get_uint("announce_rate_grace") + .map(|v| v as u32) + .or_else(|| announce_rate_target.map(|_| 0)), + announce_rate_penalty: section + .get_uint("announce_rate_penalty") + .or_else(|| announce_rate_target.map(|_| 0)), + ifac_network_name: section + .get("networkname") + .or_else(|| section.get("network_name")) + .map(|s| s.to_string()), + ifac_passphrase: section + .get("passphrase") + .or_else(|| section.get("pass_phrase")) + .map(|s| s.to_string()), + ifac_size: section.get_uint("ifac_size").map(|v| v as usize), + default_ifac_size: 8, + ingress_control, + ingress_overrides, + } + } + + pub fn with_default_ifac_size(mut self, size: usize) -> Self { + self.default_ifac_size = size; + self + } +} + +/// Python `DEFAULT_IFAC_SIZE`: network interfaces 16 bytes, serial/packet-radio 8. +pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize { + match config { + InterfaceConfig::TcpClient(_) + | InterfaceConfig::TcpServer(_) + | InterfaceConfig::Udp(_) + | InterfaceConfig::Auto(_) + | InterfaceConfig::I2P(_) + | InterfaceConfig::Backbone(_) => 16, + #[cfg(feature = "serial")] + InterfaceConfig::Serial(_) + | InterfaceConfig::KissSerial(_) + | InterfaceConfig::RNode(_) + | InterfaceConfig::RNodeMulti(_) + | InterfaceConfig::AX25KISS(_) => 8, + InterfaceConfig::Local(_) | InterfaceConfig::Pipe(_) => 8, + #[cfg(feature = "ble")] + InterfaceConfig::BleRNode(_) => 8, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_synthesize_tcp_client() { + let mut section = ConfigSection::new(); + section.set("type", "TCPClientInterface"); + section.set("target_host", "127.0.0.1"); + section.set("target_port", "4242"); + + let config = synthesize_interface("test_tcp", §ion).unwrap(); + match config { + InterfaceConfig::TcpClient(c) => { + assert_eq!(c.target_host, "127.0.0.1"); + assert_eq!(c.target_port, 4242); + assert!(!c.kiss_framing); + } + _ => panic!("expected TcpClient"), + } + } + + #[test] + fn test_synthesize_tcp_server() { + let mut section = ConfigSection::new(); + section.set("type", "TCPServerInterface"); + section.set("listen_port", "4242"); + + let config = synthesize_interface("test_srv", §ion).unwrap(); + match config { + InterfaceConfig::TcpServer(c) => { + assert_eq!(c.listen_ip, "0.0.0.0"); + assert_eq!(c.listen_port, 4242); + } + _ => panic!("expected TcpServer"), + } + } + + #[test] + fn test_synthesize_udp() { + let mut section = ConfigSection::new(); + section.set("type", "UDPInterface"); + section.set("listen_ip", "0.0.0.0"); + section.set("listen_port", "4242"); + section.set("forward_ip", "255.255.255.255"); + section.set("forward_port", "4242"); + + let config = synthesize_interface("test_udp", §ion).unwrap(); + match config { + InterfaceConfig::Udp(c) => { + assert_eq!(c.listen_ip.as_deref(), Some("0.0.0.0")); + assert_eq!(c.listen_port, Some(4242)); + assert_eq!(c.forward_ip.as_deref(), Some("255.255.255.255")); + } + _ => panic!("expected Udp"), + } + } + + #[test] + fn test_disabled_interface() { + let mut section = ConfigSection::new(); + section.set("type", "TCPClientInterface"); + section.set("enabled", "no"); + section.set("target_host", "127.0.0.1"); + section.set("target_port", "4242"); + + match synthesize_interface("disabled", §ion) { + Err(InterfaceFactoryError::Disabled(_)) => {} + other => panic!("expected Disabled, got {other:?}"), + } + } + + #[test] + fn test_unknown_type() { + let mut section = ConfigSection::new(); + section.set("type", "FooInterface"); + + match synthesize_interface("unknown", §ion) { + Err(InterfaceFactoryError::UnknownType(t)) => assert_eq!(t, "FooInterface"), + other => panic!("expected UnknownType, got {other:?}"), + } + } + + #[test] + fn test_missing_type() { + let section = ConfigSection::new(); + match synthesize_interface("no_type", §ion) { + Err(InterfaceFactoryError::MissingField { field, .. }) => { + assert_eq!(field, "type"); + } + other => panic!("expected MissingField, got {other:?}"), + } + } + + #[test] + fn test_interface_mode_parsing() { + assert_eq!(parse_interface_mode("full"), Some(InterfaceMode::Full)); + assert_eq!( + parse_interface_mode("access_point"), + Some(InterfaceMode::AccessPoint) + ); + assert_eq!( + parse_interface_mode("accesspoint"), + Some(InterfaceMode::AccessPoint) + ); + assert_eq!(parse_interface_mode("ap"), Some(InterfaceMode::AccessPoint)); + assert_eq!( + parse_interface_mode("pointtopoint"), + Some(InterfaceMode::PointToPoint) + ); + assert_eq!( + parse_interface_mode("roaming"), + Some(InterfaceMode::Roaming) + ); + assert_eq!( + parse_interface_mode("boundary"), + Some(InterfaceMode::Boundary) + ); + assert_eq!( + parse_interface_mode("gateway"), + Some(InterfaceMode::Gateway) + ); + assert_eq!(parse_interface_mode("gw"), Some(InterfaceMode::Gateway)); + assert_eq!(parse_interface_mode("unknown"), None); + } + + #[test] + fn test_tcp_client_with_options() { + let mut section = ConfigSection::new(); + section.set("type", "TCPClientInterface"); + section.set("target_host", "10.0.0.1"); + section.set("target_port", "5555"); + section.set("kiss_framing", "yes"); + section.set("connect_timeout", "10"); + section.set("max_reconnect_tries", "3"); + section.set("interface_mode", "gateway"); + + let config = synthesize_interface("tcp_opts", §ion).unwrap(); + match config { + InterfaceConfig::TcpClient(c) => { + assert!(c.kiss_framing); + assert_eq!(c.connect_timeout_secs, 10); + assert_eq!(c.max_reconnect_tries, Some(3)); + assert_eq!(c.mode, InterfaceMode::Gateway); + } + _ => panic!("expected TcpClient"), + } + } + + #[test] + fn test_post_init_defaults() { + let section = ConfigSection::new(); + let pi = InterfacePostInit::from_section(§ion); + assert!(pi.outgoing); + assert!(pi.ingress_control); + assert!(pi.bitrate.is_none()); + assert!(pi.ifac_network_name.is_none()); + } + + #[test] + fn test_announce_rate_target_defaults_grace_and_penalty() { + let mut section = ConfigSection::new(); + section.set("announce_rate_target", "2"); + + let pi = InterfacePostInit::from_section(§ion); + + assert_eq!(pi.announce_rate_target, Some(2)); + assert_eq!(pi.announce_rate_grace, Some(0)); + assert_eq!(pi.announce_rate_penalty, Some(0)); + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_serial() { + let mut section = ConfigSection::new(); + section.set("type", "SerialInterface"); + section.set("port", "/dev/ttyUSB0"); + section.set("speed", "115200"); + section.set("databits", "8"); + section.set("parity", "N"); + section.set("stopbits", "1"); + + let config = synthesize_interface("test_serial", §ion).unwrap(); + match config { + InterfaceConfig::Serial(c) => { + assert_eq!(c.name, "test_serial"); + assert_eq!(c.port, "/dev/ttyUSB0"); + assert_eq!(c.baud_rate, 115200); + assert_eq!(c.data_bits, 8); + assert_eq!(c.parity, "N"); + assert_eq!(c.stop_bits, 1); + } + _ => panic!("expected Serial"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_serial_defaults() { + let mut section = ConfigSection::new(); + section.set("type", "SerialInterface"); + section.set("port", "/dev/ttyS0"); + + let config = synthesize_interface("serial_defaults", §ion).unwrap(); + match config { + InterfaceConfig::Serial(c) => { + assert_eq!(c.baud_rate, 9600); + assert_eq!(c.data_bits, 8); + assert_eq!(c.parity, "N"); + assert_eq!(c.stop_bits, 1); + } + _ => panic!("expected Serial"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_serial_missing_port() { + let mut section = ConfigSection::new(); + section.set("type", "SerialInterface"); + + match synthesize_interface("serial_no_port", §ion) { + Err(InterfaceFactoryError::MissingField { field, .. }) => { + assert_eq!(field, "port"); + } + other => panic!("expected MissingField, got {other:?}"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_kiss_serial() { + let mut section = ConfigSection::new(); + section.set("type", "KISSInterface"); + section.set("port", "/dev/ttyUSB1"); + section.set("speed", "57600"); + + let config = synthesize_interface("test_kiss", §ion).unwrap(); + match config { + InterfaceConfig::KissSerial(c) => { + assert_eq!(c.name, "test_kiss"); + assert_eq!(c.port, "/dev/ttyUSB1"); + assert_eq!(c.baud_rate, 57600); + } + _ => panic!("expected KissSerial"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_kiss_serial_defaults() { + let mut section = ConfigSection::new(); + section.set("type", "KISSInterface"); + section.set("port", "/dev/ttyS0"); + + let config = synthesize_interface("kiss_defaults", §ion).unwrap(); + match config { + InterfaceConfig::KissSerial(c) => { + assert_eq!(c.baud_rate, 9600); + } + _ => panic!("expected KissSerial"), + } + } + + #[test] + fn test_synthesize_auto() { + let mut section = ConfigSection::new(); + section.set("type", "AutoInterface"); + section.set("group_id", "mygroup"); + section.set("discovery_port", "30000"); + section.set("data_port", "40000"); + + let config = synthesize_interface("test_auto", §ion).unwrap(); + match config { + InterfaceConfig::Auto(c) => { + assert_eq!(c.name, "test_auto"); + assert_eq!(c.group_id, "mygroup"); + assert_eq!(c.discovery_port, 30000); + assert_eq!(c.data_port, 40000); + } + _ => panic!("expected Auto"), + } + } + + #[test] + fn test_synthesize_auto_defaults() { + let mut section = ConfigSection::new(); + section.set("type", "AutoInterface"); + + let config = synthesize_interface("auto_defaults", §ion).unwrap(); + match config { + InterfaceConfig::Auto(c) => { + assert_eq!(c.group_id, "reticulum"); + assert_eq!(c.discovery_port, 29716); + assert_eq!(c.data_port, 42671); + assert_eq!(c.discovery_scope, rns_interface::auto::DiscoveryScope::Link); + assert_eq!( + c.multicast_address_type, + rns_interface::auto::McastAddrType::Temporary + ); + assert!(c.devices.is_none()); + assert!(c.ignored_devices.is_empty()); + assert!(c.configured_bitrate.is_none()); + } + _ => panic!("expected Auto"), + } + } + + #[test] + fn test_synthesize_auto_advanced_options() { + let mut section = ConfigSection::new(); + section.set("type", "AutoInterface"); + section.set("group_id", "campus"); + section.set("discovery_scope", "site"); + section.set("multicast_address_type", "permanent"); + section.set("devices", "eth0, wlan0 ,br-lan"); + section.set("ignored_devices", "vmnet1,docker0"); + section.set("configured_bitrate", "100000000"); + + let config = synthesize_interface("campus_auto", §ion).unwrap(); + match config { + InterfaceConfig::Auto(c) => { + assert_eq!(c.group_id, "campus"); + assert_eq!(c.discovery_scope, rns_interface::auto::DiscoveryScope::Site); + assert_eq!( + c.multicast_address_type, + rns_interface::auto::McastAddrType::Permanent + ); + let devices = c.devices.expect("devices set"); + assert_eq!(devices, vec!["eth0", "wlan0", "br-lan"]); + assert_eq!(c.ignored_devices, vec!["vmnet1", "docker0"]); + assert_eq!(c.configured_bitrate, Some(100_000_000)); + } + _ => panic!("expected Auto"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeInterface"); + section.set("port", "/dev/ttyACM0"); + section.set("frequency", "868000000"); + section.set("bandwidth", "125000"); + section.set("spreadingfactor", "7"); + section.set("codingrate", "5"); + section.set("txpower", "14"); + section.set("interface_mode", "access_point"); + + let config = synthesize_interface("test_rnode", §ion).unwrap(); + match config { + InterfaceConfig::RNode(c) => { + assert_eq!(c.name, "test_rnode"); + assert_eq!(c.port, "/dev/ttyACM0"); + assert_eq!(c.frequency, 868000000); + assert_eq!(c.bandwidth, 125000); + assert_eq!(c.spreading_factor, 7); + assert_eq!(c.coding_rate, 5); + assert_eq!(c.tx_power, 14); + assert_eq!(c.mode, InterfaceMode::AccessPoint); + } + _ => panic!("expected RNode"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_defaults() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeInterface"); + section.set("port", "/dev/ttyACM0"); + section.set("frequency", "915000000"); + + let config = synthesize_interface("rnode_defaults", §ion).unwrap(); + match config { + InterfaceConfig::RNode(c) => { + assert_eq!(c.bandwidth, 125000); + assert_eq!(c.spreading_factor, 7); + assert_eq!(c.coding_rate, 5); + assert_eq!(c.tx_power, 17); + } + _ => panic!("expected RNode"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_missing_port() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeInterface"); + section.set("frequency", "868000000"); + + match synthesize_interface("rnode_no_port", §ion) { + Err(InterfaceFactoryError::MissingField { field, .. }) => { + assert_eq!(field, "port"); + } + other => panic!("expected MissingField, got {other:?}"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_missing_frequency() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeInterface"); + section.set("port", "/dev/ttyACM0"); + + match synthesize_interface("rnode_no_freq", §ion) { + Err(InterfaceFactoryError::MissingField { field, .. }) => { + assert_eq!(field, "frequency"); + } + other => panic!("expected MissingField, got {other:?}"), + } + } + + #[test] + fn test_synthesize_local() { + let mut section = ConfigSection::new(); + section.set("type", "LocalInterface"); + section.set("port", "12345"); + + let config = synthesize_interface("test_local", §ion).unwrap(); + match config { + InterfaceConfig::Local(c) => { + assert_eq!(c.name, "test_local"); + assert_eq!(c.port, 12345); + } + _ => panic!("expected Local"), + } + } + + #[test] + fn test_synthesize_local_default_port() { + let mut section = ConfigSection::new(); + section.set("type", "LocalInterface"); + + let config = synthesize_interface("local_defaults", §ion).unwrap(); + match config { + InterfaceConfig::Local(c) => { + assert_eq!(c.port, 37428); + assert_eq!(c.mode, InterfaceMode::Full); + } + _ => panic!("expected Local"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_interface_config_variants_construction() { + let _tcp_client = InterfaceConfig::TcpClient(TcpClientConfig::new("tc", "127.0.0.1", 4242)); + let _tcp_server = InterfaceConfig::TcpServer(TcpServerConfig::new("ts", "0.0.0.0", 4242)); + let _udp = InterfaceConfig::Udp(UdpInterfaceConfig::new("udp")); + let _serial = InterfaceConfig::Serial(SerialInterfaceConfig { + name: "s".to_string(), + port: "/dev/ttyS0".to_string(), + baud_rate: 9600, + data_bits: 8, + parity: "N".to_string(), + stop_bits: 1, + mode: InterfaceMode::Full, + }); + let _kiss = InterfaceConfig::KissSerial(KissSerialConfig { + name: "k".to_string(), + port: "/dev/ttyS0".to_string(), + baud_rate: 9600, + mode: InterfaceMode::Full, + }); + let _auto = InterfaceConfig::Auto(AutoInterfaceConfig { + name: "a".to_string(), + group_id: "test".to_string(), + discovery_scope: rns_interface::auto::DiscoveryScope::Link, + discovery_port: 29716, + data_port: 42671, + multicast_address_type: rns_interface::auto::McastAddrType::Temporary, + devices: None, + ignored_devices: Vec::new(), + configured_bitrate: None, + mode: InterfaceMode::Full, + }); + let _rnode = InterfaceConfig::RNode(RNodeInterfaceConfig { + name: "r".to_string(), + port: "/dev/ttyACM0".to_string(), + frequency: 868000000, + bandwidth: 125000, + spreading_factor: 7, + coding_rate: 5, + tx_power: 17, + mode: InterfaceMode::Full, + }); + let _local = InterfaceConfig::Local(LocalInterfaceConfig { + name: "l".to_string(), + port: 37428, + mode: InterfaceMode::Full, + }); + } + + #[test] + fn test_post_init_with_values() { + let mut section = ConfigSection::new(); + section.set("outgoing", "no"); + section.set("bitrate", "115200"); + section.set("networkname", "testnet"); + section.set("passphrase", "secret"); + section.set("ifac_size", "16"); + section.set("ingress_control", "false"); + section.set("announce_cap", "5.0"); + + let pi = InterfacePostInit::from_section(§ion); + assert!(!pi.outgoing); + assert_eq!(pi.bitrate, Some(115200)); + assert_eq!(pi.ifac_network_name.as_deref(), Some("testnet")); + assert_eq!(pi.ifac_passphrase.as_deref(), Some("secret")); + assert_eq!(pi.ifac_size, Some(16)); + assert!(!pi.ingress_control); + assert!((pi.announce_cap.unwrap() - 5.0).abs() < f64::EPSILON); + } + + #[test] + fn test_synthesize_i2p() { + let mut section = ConfigSection::new(); + section.set("type", "I2PInterface"); + section.set("connectable", "yes"); + section.set("peers", "abc123.b32.i2p, def456.b32.i2p"); + + let config = synthesize_interface("test_i2p", §ion).unwrap(); + match config { + InterfaceConfig::I2P(c) => { + assert_eq!(c.name, "test_i2p"); + assert!(c.connectable); + assert_eq!(c.peers.len(), 2); + assert_eq!(c.peers[0], "abc123.b32.i2p"); + assert_eq!(c.peers[1], "def456.b32.i2p"); + assert_eq!(c.i2p_sam_host, "127.0.0.1"); + assert_eq!(c.i2p_sam_port, 7656); + } + _ => panic!("expected I2P"), + } + } + + #[test] + fn test_synthesize_i2p_defaults() { + let mut section = ConfigSection::new(); + section.set("type", "I2PInterface"); + + let config = synthesize_interface("i2p_defaults", §ion).unwrap(); + match config { + InterfaceConfig::I2P(c) => { + assert!(!c.connectable); + assert!(c.peers.is_empty()); + assert_eq!(c.i2p_sam_host, "127.0.0.1"); + assert_eq!(c.i2p_sam_port, 7656); + } + _ => panic!("expected I2P"), + } + } + + #[test] + fn test_synthesize_pipe() { + let mut section = ConfigSection::new(); + section.set("type", "PipeInterface"); + section.set("command", "netcat -l 5757"); + section.set("respawn_delay", "10"); + + let config = synthesize_interface("test_pipe", §ion).unwrap(); + match config { + InterfaceConfig::Pipe(c) => { + assert_eq!(c.name, "test_pipe"); + assert_eq!(c.command, "netcat -l 5757"); + assert_eq!(c.respawn_delay, 10); + } + _ => panic!("expected Pipe"), + } + } + + #[test] + fn test_synthesize_pipe_defaults() { + let mut section = ConfigSection::new(); + section.set("type", "PipeInterface"); + section.set("command", "cat"); + + let config = synthesize_interface("pipe_defaults", §ion).unwrap(); + match config { + InterfaceConfig::Pipe(c) => { + assert_eq!(c.respawn_delay, 5); + } + _ => panic!("expected Pipe"), + } + } + + #[test] + fn test_synthesize_pipe_missing_command() { + let mut section = ConfigSection::new(); + section.set("type", "PipeInterface"); + + match synthesize_interface("pipe_no_cmd", §ion) { + Err(InterfaceFactoryError::MissingField { field, .. }) => { + assert_eq!(field, "command"); + } + other => panic!("expected MissingField, got {other:?}"), + } + } + + #[test] + fn test_synthesize_backbone_client() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + section.set("target_host", "amsterdam.connect.reticulum.network"); + section.set("target_port", "4251"); + + let config = synthesize_interface("test_backbone", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => { + assert_eq!(c.name, "test_backbone"); + assert_eq!( + c.target_host.as_deref(), + Some("amsterdam.connect.reticulum.network") + ); + assert_eq!(c.port, 4251); + assert!(c.listen_on.is_none()); + } + _ => panic!("expected Backbone"), + } + } + + #[test] + fn test_synthesize_backbone_listener() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + section.set("listen_on", "0.0.0.0"); + section.set("port", "4242"); + + let config = synthesize_interface("backbone_listen", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => { + assert_eq!(c.listen_on.as_deref(), Some("0.0.0.0")); + assert_eq!(c.port, 4242); + assert!(c.target_host.is_none()); + } + _ => panic!("expected Backbone"), + } + } + + #[test] + fn test_synthesize_backbone_with_remote() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + section.set("remote", "some.host.network"); + section.set("target_port", "4343"); + section.set("prefer_ipv6", "yes"); + + let config = synthesize_interface("backbone_remote", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => { + assert_eq!(c.target_host.as_deref(), Some("some.host.network")); + assert_eq!(c.port, 4343); + assert!(c.prefer_ipv6); + } + _ => panic!("expected Backbone"), + } + } + + #[test] + fn test_synthesize_backbone_defaults() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + + let config = synthesize_interface("backbone_defaults", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => { + assert_eq!(c.port, 4242); + assert!(!c.prefer_ipv6); + assert!(c.listen_on.is_none()); + assert!(c.target_host.is_none()); + assert!(c.device.is_none()); + assert_eq!(c.connect_timeout, 5); + assert!(c.max_reconnect_tries.is_none()); + assert!(!c.i2p_tunneled); + } + _ => panic!("expected Backbone"), + } + } + + #[test] + fn test_synthesize_backbone_connect_timeout() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + section.set("target_host", "host.example"); + section.set("connect_timeout", "12"); + + let config = synthesize_interface("bb_to", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => assert_eq!(c.connect_timeout, 12), + _ => panic!("expected Backbone"), + } + } + + #[test] + fn test_synthesize_backbone_max_reconnect_tries() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + section.set("target_host", "host.example"); + section.set("max_reconnect_tries", "7"); + + let config = synthesize_interface("bb_retries", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => assert_eq!(c.max_reconnect_tries, Some(7)), + _ => panic!("expected Backbone"), + } + } + + #[test] + fn test_synthesize_backbone_i2p_tunneled() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + section.set("target_host", "host.example"); + section.set("i2p_tunneled", "yes"); + + let config = synthesize_interface("bb_i2p", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => assert!(c.i2p_tunneled), + _ => panic!("expected Backbone"), + } + } + + #[test] + fn test_synthesize_backbone_listen_port_alias() { + let mut section = ConfigSection::new(); + section.set("type", "BackboneInterface"); + section.set("listen_on", "0.0.0.0"); + section.set("listen_port", "5151"); + + let config = synthesize_interface("bb_listen_alias", §ion).unwrap(); + match config { + InterfaceConfig::Backbone(c) => assert_eq!(c.port, 5151), + _ => panic!("expected Backbone"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_ax25kiss() { + let mut section = ConfigSection::new(); + section.set("type", "AX25KISSInterface"); + section.set("port", "/dev/ttyUSB2"); + section.set("callsign", "NO1CLL"); + section.set("ssid", "0"); + section.set("speed", "115200"); + section.set("preamble", "150"); + section.set("txtail", "10"); + section.set("persistence", "200"); + section.set("slottime", "20"); + + let config = synthesize_interface("test_ax25", §ion).unwrap(); + match config { + InterfaceConfig::AX25KISS(c) => { + assert_eq!(c.name, "test_ax25"); + assert_eq!(c.port, "/dev/ttyUSB2"); + assert_eq!(c.callsign, "NO1CLL"); + assert_eq!(c.ssid, 0); + assert_eq!(c.baud_rate, 115200); + assert_eq!(c.preamble, 150); + assert_eq!(c.txtail, 10); + assert_eq!(c.persistence, 200); + assert_eq!(c.slottime, 20); + assert!(!c.flow_control); + } + _ => panic!("expected AX25KISS"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_ax25kiss_missing_callsign() { + let mut section = ConfigSection::new(); + section.set("type", "AX25KISSInterface"); + section.set("port", "/dev/ttyUSB2"); + + match synthesize_interface("ax25_no_call", §ion) { + Err(InterfaceFactoryError::MissingField { field, .. }) => { + assert_eq!(field, "callsign"); + } + other => panic!("expected MissingField, got {other:?}"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_multi() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeMultiInterface"); + section.set("port", "/dev/ttyACM0"); + section.set("baud_rate", "230400"); + section.set("flow_control", "yes"); + + let mut high = ConfigSection::new(); + high.set("enabled", "yes"); + high.set("vport", "1"); + high.set("frequency", "2400000000"); + high.set("bandwidth", "1625000"); + high.set("txpower", "0"); + high.set("spreadingfactor", "5"); + high.set("codingrate", "5"); + high.set("flow_control", "no"); + high.set("outgoing", "no"); + high.set("airtime_limit_short", "33.5"); + high.set("airtime_limit_long", "88"); + section + .subsections + .insert("High Datarate".to_string(), high); + + let mut low = ConfigSection::new(); + low.set("enabled", "yes"); + low.set("vport", "0"); + low.set("frequency", "865600000"); + low.set("bandwidth", "125000"); + low.set("tx_power", "14"); + low.set("spreading_factor", "7"); + low.set("coding_rate", "5"); + section.subsections.insert("Low Datarate".to_string(), low); + + let config = synthesize_interface("test_rnodemulti", §ion).unwrap(); + match config { + InterfaceConfig::RNodeMulti(c) => { + assert_eq!(c.name, "test_rnodemulti"); + assert_eq!(c.port, "/dev/ttyACM0"); + assert_eq!(c.baud_rate, 230400); + assert!(c.flow_control); + assert_eq!(c.subinterfaces.len(), 2); + + let low = &c.subinterfaces[0]; + assert_eq!(low.name, "Low Datarate"); + assert_eq!(low.vport, 0); + assert_eq!(low.frequency, 865600000); + assert_eq!(low.bandwidth, 125000); + assert_eq!(low.spreading_factor, 7); + assert_eq!(low.coding_rate, 5); + assert_eq!(low.tx_power, 14); + assert!(low.flow_control, "parent flow_control is inherited"); + assert!(low.outgoing); + + let high = &c.subinterfaces[1]; + assert_eq!(high.name, "High Datarate"); + assert_eq!(high.vport, 1); + assert_eq!(high.frequency, 2400000000); + assert_eq!(high.bandwidth, 1625000); + assert_eq!(high.spreading_factor, 5); + assert_eq!(high.coding_rate, 5); + assert_eq!(high.tx_power, 0); + assert!( + !high.flow_control, + "subinterface can override parent flow_control" + ); + assert!(!high.outgoing); + assert_eq!(high.st_alock, Some(33.5)); + assert_eq!(high.lt_alock, Some(88.0)); + } + _ => panic!("expected RNodeMulti"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_multi_no_enabled_subinterfaces() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeMultiInterface"); + section.set("port", "/dev/ttyACM0"); + + let mut disabled = ConfigSection::new(); + disabled.set("enabled", "no"); + disabled.set("vport", "0"); + disabled.set("frequency", "865600000"); + section.subsections.insert("Disabled".to_string(), disabled); + + match synthesize_interface("test_rnodemulti", §ion) { + Err(InterfaceFactoryError::InvalidValue { field, .. }) => { + assert_eq!(field, "subinterfaces"); + } + other => panic!("expected InvalidValue, got {other:?}"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_multi_duplicate_vport() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeMultiInterface"); + section.set("port", "/dev/ttyACM0"); + + for name in ["a", "b"] { + let mut sub = ConfigSection::new(); + sub.set("vport", "0"); + sub.set("frequency", "865600000"); + section.subsections.insert(name.to_string(), sub); + } + + match synthesize_interface("test_rnodemulti", §ion) { + Err(InterfaceFactoryError::InvalidValue { field, message }) => { + assert!(field.ends_with(".vport")); + assert!(message.contains("duplicate")); + } + other => panic!("expected InvalidValue, got {other:?}"), + } + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_multi_missing_port() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeMultiInterface"); + + match synthesize_interface("rnodemulti_no_port", §ion) { + Err(InterfaceFactoryError::MissingField { field, .. }) => { + assert_eq!(field, "port"); + } + other => panic!("expected MissingField, got {other:?}"), + } + } +} diff --git a/crates/rns-runtime/src/jobs.rs b/crates/rns-runtime/src/jobs.rs new file mode 100644 index 0000000..28dbdcd --- /dev/null +++ b/crates/rns-runtime/src/jobs.rs @@ -0,0 +1,112 @@ +//! Cache cleaning every 15 minutes, persistence every 12 hours (or next +//! 5-minute gracious interval on explicit request). Python: `Reticulum.py`. + +use std::time::{Duration, Instant}; + +use crate::constants::*; + +pub struct JobScheduler { + last_clean: Instant, + last_persist: Instant, + persist_requested: bool, + last_gracious_persist: Instant, +} + +impl JobScheduler { + pub fn new() -> Self { + let now = Instant::now(); + Self { + last_clean: now, + last_persist: now, + persist_requested: false, + last_gracious_persist: now, + } + } + + pub fn tick(&mut self) -> Vec { + self.tick_at(Instant::now()) + } + + fn tick_at(&mut self, now: Instant) -> Vec { + let mut jobs = Vec::new(); + + if now.duration_since(self.last_clean) >= Duration::from_secs(CLEAN_INTERVAL) { + jobs.push(Job::CleanCache); + self.last_clean = now; + } + + if now.duration_since(self.last_persist) >= Duration::from_secs(PERSIST_INTERVAL) { + jobs.push(Job::PersistData); + self.last_persist = now; + self.persist_requested = false; + } + + if self.persist_requested + && now.duration_since(self.last_gracious_persist) + >= Duration::from_secs(GRACIOUS_PERSIST_INTERVAL) + { + jobs.push(Job::PersistData); + self.last_gracious_persist = now; + self.persist_requested = false; + } + + jobs + } + + pub fn request_persist(&mut self) { + self.persist_requested = true; + } +} + +impl Default for JobScheduler { + fn default() -> Self { + Self::new() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Job { + CleanCache, + PersistData, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_scheduler_initial_tick() { + let mut scheduler = JobScheduler::new(); + let jobs = scheduler.tick(); + assert!(jobs.is_empty()); + } + + #[test] + fn test_scheduler_persist_request() { + let mut scheduler = JobScheduler::new(); + assert!(!scheduler.persist_requested); + scheduler.request_persist(); + assert!(scheduler.persist_requested); + } + + #[test] + fn test_scheduler_forced_persist() { + let mut scheduler = JobScheduler::new(); + let now = Instant::now(); + scheduler.last_gracious_persist = now; + scheduler.request_persist(); + + let jobs = scheduler.tick_at(now + Duration::from_secs(GRACIOUS_PERSIST_INTERVAL + 1)); + assert!(jobs.contains(&Job::PersistData)); + assert!(!scheduler.persist_requested); + } + + #[test] + fn test_scheduler_clean_due() { + let mut scheduler = JobScheduler::new(); + let now = Instant::now(); + scheduler.last_clean = now; + let jobs = scheduler.tick_at(now + Duration::from_secs(CLEAN_INTERVAL + 1)); + assert!(jobs.contains(&Job::CleanCache)); + } +} diff --git a/crates/rns-runtime/src/lib.rs b/crates/rns-runtime/src/lib.rs new file mode 100644 index 0000000..a1a40ce --- /dev/null +++ b/crates/rns-runtime/src/lib.rs @@ -0,0 +1,19 @@ +//! Reticulum runtime: config, lifecycle, RPC, and the [`reticulum::ReticulumHandle`] +//! that user code holds. Python reference: `RNS/Reticulum.py`. + +pub mod config; +pub mod constants; +pub mod interface_factory; +pub mod jobs; +pub mod lifecycle; +pub mod link_client; +pub mod link_manager; +pub mod platform; +pub mod probe; +pub mod remote_management; +pub mod remote_management_schema; +pub mod reticulum; +pub mod rncp; +pub mod rnsh; +pub mod rpc; +pub mod rpc_server; diff --git a/crates/rns-runtime/src/lifecycle.rs b/crates/rns-runtime/src/lifecycle.rs new file mode 100644 index 0000000..2281d6b --- /dev/null +++ b/crates/rns-runtime/src/lifecycle.rs @@ -0,0 +1,147 @@ +//! Ctrl-C / SIGTERM flip a shared flag that all runtime tasks observe, +//! allowing them to detach interfaces and flush state cleanly before exit. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use tokio::sync::mpsc; + +#[derive(Clone)] +pub struct ShutdownSignal { + flag: Arc, + notify: Arc, +} + +impl ShutdownSignal { + pub fn new() -> Self { + Self { + flag: Arc::new(AtomicBool::new(false)), + notify: Arc::new(tokio::sync::Notify::new()), + } + } + + pub fn trigger(&self) { + if !self.flag.swap(true, Ordering::SeqCst) { + tracing::debug!("shutdown triggered, notifying waiters"); + } + self.notify.notify_waiters(); + } + + pub fn is_triggered(&self) -> bool { + self.flag.load(Ordering::SeqCst) + } + + pub async fn wait(&self) { + if self.is_triggered() { + return; + } + self.notify.notified().await; + } +} + +impl Default for ShutdownSignal { + fn default() -> Self { + Self::new() + } +} + +pub struct ExitHandler { + actions: Vec>, +} + +impl ExitHandler { + pub fn new() -> Self { + Self { + actions: Vec::new(), + } + } + + pub fn register(&mut self, action: impl FnOnce() + Send + 'static) { + self.actions.push(Box::new(action)); + } + + pub fn execute(self) { + let n = self.actions.len(); + tracing::debug!(actions = n, "running exit handlers"); + for action in self.actions { + action(); + } + } +} + +impl Default for ExitHandler { + fn default() -> Self { + Self::new() + } +} + +/// Install Ctrl-C / SIGTERM handlers that trip `shutdown`. Returned receiver +/// yields once on signal for await-based callers. +pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> { + let (tx, rx) = mpsc::channel(1); + + let shutdown_clone = shutdown.clone(); + tokio::spawn(async move { + let ctrl_c = tokio::signal::ctrl_c(); + ctrl_c.await.ok(); + tracing::info!("received shutdown signal"); + shutdown_clone.trigger(); + let _ = tx.send(()).await; + }); + + rx +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_shutdown_signal() { + let signal = ShutdownSignal::new(); + assert!(!signal.is_triggered()); + signal.trigger(); + assert!(signal.is_triggered()); + } + + #[test] + fn test_shutdown_signal_clone() { + let signal = ShutdownSignal::new(); + let clone = signal.clone(); + signal.trigger(); + assert!(clone.is_triggered()); + } + + #[test] + fn test_exit_handler() { + use std::sync::atomic::{AtomicU32, Ordering}; + let counter = Arc::new(AtomicU32::new(0)); + + let mut handler = ExitHandler::new(); + let c1 = counter.clone(); + handler.register(move || { + c1.fetch_add(1, Ordering::SeqCst); + }); + let c2 = counter.clone(); + handler.register(move || { + c2.fetch_add(10, Ordering::SeqCst); + }); + + handler.execute(); + assert_eq!(counter.load(Ordering::SeqCst), 11); + } + + #[tokio::test] + async fn test_shutdown_wait() { + let signal = ShutdownSignal::new(); + let signal_clone = signal.clone(); + + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + signal_clone.trigger(); + }); + + signal.wait().await; + assert!(signal.is_triggered()); + } +} diff --git a/crates/rns-runtime/src/link_client.rs b/crates/rns-runtime/src/link_client.rs new file mode 100644 index 0000000..b89bde2 --- /dev/null +++ b/crates/rns-runtime/src/link_client.rs @@ -0,0 +1,680 @@ +//! Initiator-side Link client for `rnstatus -R` / `rnpath -R`. Each `query` +//! does the full handshake (pubkey discovery → link → identify → request → +//! response → close) over its own destination channel. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use tokio::sync::mpsc; +use tokio::time::timeout; + +use rns_crypto::ed25519::Ed25519PublicKey; +use rns_identity::destination::Destination; +use rns_identity::identity::Identity; +use rns_link::link::{CloseReason, Link}; +use rns_protocol::resource::{InboundTransfer, TransferAction}; +use rns_protocol::resource_adv::ResourceAdvertisement; +use rns_transport::link_messages::DestinationEvent; +use rns_transport::messages::{AnnounceHandlerEvent, OutboundRequest, TransportMessage}; + +#[derive(Debug, thiserror::Error)] +pub enum LinkClientError { + #[error("transport channel closed or full")] + TransportUnavailable, + #[error("timed out waiting for {0}")] + Timeout(&'static str), + #[error("could not discover remote identity public key for destination")] + PubkeyNotDiscovered, + #[error("link proof validation failed: {0}")] + ProofInvalid(String), + #[error("link establishment failed: {0}")] + HandshakeFailed(String), + #[error("local identity has no signing key (cannot identify on link)")] + NoSigningKey, + #[error("encryption failure on link: {0}")] + LinkCrypto(String), + #[error("unexpected response from remote: {0}")] + UnexpectedResponse(String), +} + +#[derive(Clone)] +pub struct LinkClient { + transport_tx: mpsc::Sender, + identity: Arc, +} + +impl LinkClient { + pub fn new(transport_tx: mpsc::Sender, identity: Identity) -> Self { + Self { + transport_tx, + identity: Arc::new(identity), + } + } + + /// Open a Link to `app_name` on `remote_transport_hash`, send one + /// request, return the response. + pub async fn query( + &self, + remote_transport_hash: [u8; 16], + app_name: &str, + path: &str, + payload: Vec, + hops: u8, + overall_timeout: Duration, + ) -> Result, LinkClientError> { + let started = Instant::now(); + let deadline = started + overall_timeout; + + let dest_hash = + Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash)); + + // Register the handler before the path request so the answering + // announce (carrying the pubkey) is observed. + let (ann_tx, mut ann_rx) = mpsc::channel::(64); + self.send_msg(TransportMessage::RegisterAnnounceHandler { + aspect_filter: Some(app_name.to_string()), + receive_path_responses: true, + callback_tx: ann_tx, + }) + .await?; + + self.send_msg(TransportMessage::RequestPath { + destination_hash: dest_hash, + }) + .await?; + + let pubkey = wait_for_pubkey(&mut ann_rx, dest_hash, time_remaining(deadline)?).await?; + let _ = self + .transport_tx + .try_send(TransportMessage::DeregisterAnnounceHandler { + aspect_filter: Some(app_name.to_string()), + }); + + let (mut link, request_data) = Link::new_initiator(dest_hash, hops); + let link_id = link.link_id; + + // Register link_id as a destination so inbound LRPROOF / Response + // packets route back to this task via dest_rx. + let (dest_tx, mut dest_rx) = mpsc::channel::(128); + self.send_msg(TransportMessage::RegisterDestination { + hash: link_id, + app_name: "rnstatus.linkclient".to_string(), + delivery_tx: Some(dest_tx), + }) + .await?; + + let req_pkt = build_link_request_packet(dest_hash, &request_data); + self.send_msg(TransportMessage::Outbound(OutboundRequest { + raw: req_pkt, + destination_hash: dest_hash, + })) + .await?; + + let proof_data = wait_for_proof(&mut dest_rx, link_id, time_remaining(deadline)?).await?; + + let identity_ed25519_pub: [u8; 32] = pubkey[32..64].try_into().map_err(|_| { + LinkClientError::ProofInvalid("remote public key is not 64 bytes".into()) + })?; + let identity_verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub) + .map_err(|e| LinkClientError::ProofInvalid(format!("verify key: {e}")))?; + + let rtt_data = link + .validate_proof(&proof_data, &identity_verify_key, &identity_ed25519_pub) + .map_err(|e| LinkClientError::ProofInvalid(format!("{e:?}")))?; + + let rtt_pkt = + build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data); + self.send_msg(TransportMessage::Outbound(OutboundRequest { + raw: rtt_pkt, + destination_hash: link_id, + })) + .await?; + + let our_pub = self.identity.get_public_key(); + let our_priv = self + .identity + .get_signing_key() + .ok_or(LinkClientError::NoSigningKey)?; + let identify_data = link + .identify(&our_pub, &our_priv) + .map_err(|e| LinkClientError::LinkCrypto(format!("identify: {e:?}")))?; + let identify_pkt = build_data_packet( + link_id, + rns_wire::context::PacketContext::LinkIdentify, + &identify_data, + ); + self.send_msg(TransportMessage::Outbound(OutboundRequest { + raw: identify_pkt, + destination_hash: link_id, + })) + .await?; + + let req_timeout = Duration::from_secs(5); + let (encrypted_req, request_id) = link + .request(path, Some(&payload), req_timeout) + .map_err(|e| LinkClientError::LinkCrypto(format!("request: {e:?}")))?; + let request_pkt = build_data_packet( + link_id, + rns_wire::context::PacketContext::Request, + &encrypted_req, + ); + let packet_request_id = rns_wire::hash::truncated_packet_hash( + &request_pkt, + rns_wire::flags::HeaderType::Header1, + ); + link.update_pending_request_id(&request_id, packet_request_id); + self.send_msg(TransportMessage::Outbound(OutboundRequest { + raw: request_pkt, + destination_hash: link_id, + })) + .await?; + + let response = wait_for_response( + &self.transport_tx, + &mut dest_rx, + &mut link, + link_id, + packet_request_id, + time_remaining(deadline)?, + ) + .await; + + // Tear down even on failure so the remote doesn't keep link state. + let _ = self.send_close(&mut link).await; + let _ = self + .transport_tx + .try_send(TransportMessage::DeregisterDestination { hash: link_id }); + + response + } + + async fn send_msg(&self, msg: TransportMessage) -> Result<(), LinkClientError> { + self.transport_tx + .send(msg) + .await + .map_err(|_| LinkClientError::TransportUnavailable) + } + + async fn send_close(&self, link: &mut Link) -> Result<(), LinkClientError> { + let link_id = link.link_id; + let Some(teardown_data) = link.teardown(CloseReason::InitiatorClosed) else { + return Ok(()); + }; + let close_pkt = build_data_packet( + link_id, + rns_wire::context::PacketContext::LinkClose, + &teardown_data, + ); + self.send_msg(TransportMessage::Outbound(OutboundRequest { + raw: close_pkt, + destination_hash: link_id, + })) + .await + } +} + +fn time_remaining(deadline: Instant) -> Result { + let now = Instant::now(); + if now >= deadline { + Err(LinkClientError::Timeout("overall query")) + } else { + Ok(deadline - now) + } +} + +async fn wait_for_pubkey( + rx: &mut mpsc::Receiver, + target_dest_hash: [u8; 16], + deadline: Duration, +) -> Result<[u8; 64], LinkClientError> { + let fut = async { + while let Some(ev) = rx.recv().await { + if ev.destination_hash == target_dest_hash + && let Some(pk) = ev.public_key + { + return Ok(pk); + } + } + Err(LinkClientError::PubkeyNotDiscovered) + }; + timeout(deadline, fut) + .await + .map_err(|_| LinkClientError::Timeout("path/announce discovery"))? +} + +async fn wait_for_proof( + rx: &mut mpsc::Receiver, + link_id: [u8; 16], + deadline: Duration, +) -> Result, 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, + rx: &mut mpsc::Receiver, + link: &mut Link, + link_id: [u8; 16], + request_id: [u8; 16], + deadline: Duration, +) -> Result, LinkClientError> { + let fut = async { + let mut inbound_resources: HashMap<[u8; 32], InboundTransfer> = HashMap::new(); + + while let Some(ev) = rx.recv().await { + match ev { + DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => { + return Err(LinkClientError::HandshakeFailed("link closed".into())); + } + DestinationEvent::InboundPacket { raw, .. } => { + let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) { + Ok(h) => h, + Err(_) => continue, + }; + if header.destination_hash != link_id { + continue; + } + let body = &raw[data_offset..]; + match header.context { + rns_wire::context::PacketContext::Response => { + match link.handle_response(body) { + Ok((id, response_data)) => { + if id == request_id { + return Ok(response_data); + } + } + Err(e) => { + return Err(LinkClientError::LinkCrypto(format!( + "response decrypt: {e:?}" + ))); + } + } + } + rns_wire::context::PacketContext::ResourceAdv => { + let plaintext = link.decrypt(body).map_err(|e| { + LinkClientError::LinkCrypto(format!( + "resource advertisement decrypt: {e:?}" + )) + })?; + let adv = ResourceAdvertisement::unpack(&plaintext).map_err(|e| { + LinkClientError::UnexpectedResponse(format!( + "resource advertisement: {e}" + )) + })?; + + if !adv.flags.is_response + || adv.request_id.as_deref() != Some(request_id.as_slice()) + { + continue; + } + + let mut random_hash = [0u8; rns_protocol::resource::RANDOM_HASH_SIZE]; + let copy_len = adv.random_hash.len().min(random_hash.len()); + random_hash[..copy_len].copy_from_slice(&adv.random_hash[..copy_len]); + + let rtt = link.rtt.unwrap_or(Duration::from_millis(500)); + let mut transfer = InboundTransfer::from_advertisement( + adv.num_parts, + adv.transfer_size, + adv.data_size, + random_hash, + adv.resource_hash, + adv.flags, + adv.get_map_hashes(), + rtt, + ) + .map_err(|e| { + LinkClientError::UnexpectedResponse(format!( + "resource transfer: {e:?}" + )) + })?; + + if let TransferAction::SendRequest(req) = transfer.request_next() { + send_link_data( + transport_tx, + link, + link_id, + rns_wire::context::PacketContext::ResourceReq, + &req, + true, + )?; + } + + inbound_resources.insert(adv.resource_hash, transfer); + } + rns_wire::context::PacketContext::Resource => { + let mut action_to_send = None; + let mut completed_rh = None; + + for (rh, transfer) in &mut inbound_resources { + let action = transfer.receive_part(body.to_vec()); + match action { + TransferAction::SendHmu(_) | TransferAction::SendRequest(_) => { + action_to_send = Some(action); + } + TransferAction::Complete => { + completed_rh = Some(*rh); + } + TransferAction::Failed(reason) => { + return Err(LinkClientError::UnexpectedResponse(format!( + "resource transfer failed: {reason}" + ))); + } + _ => {} + } + + if completed_rh.is_none() && transfer.resource.is_complete() { + completed_rh = Some(*rh); + } + if action_to_send.is_some() || completed_rh.is_some() { + break; + } + } + + if let Some(action) = action_to_send { + let (context, payload) = match action { + TransferAction::SendHmu(hmu) => { + (rns_wire::context::PacketContext::ResourceHmu, hmu) + } + TransferAction::SendRequest(req) => { + (rns_wire::context::PacketContext::ResourceReq, req) + } + _ => unreachable!(), + }; + send_link_data( + transport_tx, + link, + link_id, + context, + &payload, + true, + )?; + } + + if let Some(rh) = completed_rh { + let (assembled, proof) = { + let transfer = + inbound_resources.get_mut(&rh).ok_or_else(|| { + LinkClientError::UnexpectedResponse( + "completed resource disappeared".into(), + ) + })?; + let keys = link.session_keys().ok_or_else(|| { + LinkClientError::LinkCrypto( + "resource response missing link keys".into(), + ) + })?; + let decrypt_fn = move |data: &[u8]| { + rns_link::encryption::link_decrypt(&keys, data).map_err( + |_| { + rns_protocol::resource::ResourceError::DecryptFailed + }, + ) + }; + transfer.complete(Some(&decrypt_fn)).map_err(|e| { + LinkClientError::UnexpectedResponse(format!( + "resource assemble: {e:?}" + )) + })? + }; + + send_link_proof(transport_tx, link_id, &proof)?; + inbound_resources.remove(&rh); + match link.handle_response_plaintext(&assembled) { + Ok((id, response_data)) => { + if id == request_id { + return Ok(response_data); + } + } + Err(e) => { + return Err(LinkClientError::LinkCrypto(format!( + "resource response decode: {e:?}" + ))); + } + } + } + } + rns_wire::context::PacketContext::ResourceHmu => { + let plaintext = link.decrypt(body).map_err(|e| { + LinkClientError::LinkCrypto(format!( + "resource hashmap update decrypt: {e:?}" + )) + })?; + let (rh, segment, hashmap) = + rns_protocol::resource::parse_hashmap_update(&plaintext).map_err( + |e| { + LinkClientError::UnexpectedResponse(format!( + "resource hashmap update: {e:?}" + )) + }, + )?; + let Some(transfer) = inbound_resources.get_mut(&rh) else { + continue; + }; + if let TransferAction::SendRequest(req) = + transfer.hashmap_update(segment, &hashmap) + { + send_link_data( + transport_tx, + link, + link_id, + rns_wire::context::PacketContext::ResourceReq, + &req, + true, + )?; + } + } + rns_wire::context::PacketContext::LinkClose + if link.receive_teardown(body) => + { + return Err(LinkClientError::HandshakeFailed( + "link closed by remote".into(), + )); + } + _ => {} + } + } + _ => {} + } + } + Err(LinkClientError::HandshakeFailed( + "destination channel closed".into(), + )) + }; + timeout(deadline, fut) + .await + .map_err(|_| LinkClientError::Timeout("response"))? +} + +fn send_link_data( + transport_tx: &mpsc::Sender, + link: &Link, + link_id: [u8; 16], + context: rns_wire::context::PacketContext, + body: &[u8], + encrypt: bool, +) -> Result<(), LinkClientError> { + let payload = if encrypt { + link.encrypt(body) + .map_err(|e| LinkClientError::LinkCrypto(format!("resource control: {e:?}")))? + } else { + body.to_vec() + }; + let packet = build_data_packet(link_id, context, &payload); + transport_tx + .try_send(TransportMessage::Outbound(OutboundRequest { + raw: packet, + destination_hash: link_id, + })) + .map_err(|_| LinkClientError::TransportUnavailable) +} + +fn send_link_proof( + transport_tx: &mpsc::Sender, + link_id: [u8; 16], + proof: &[u8], +) -> Result<(), LinkClientError> { + let packet = build_proof_packet( + link_id, + rns_wire::context::PacketContext::ResourcePrf, + proof, + ); + transport_tx + .try_send(TransportMessage::Outbound(OutboundRequest { + raw: packet, + destination_hash: link_id, + })) + .map_err(|_| LinkClientError::TransportUnavailable) +} + +fn build_link_request_packet(dest_hash: [u8; 16], request_data: &[u8]) -> Bytes { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::LinkRequest, + }, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(request_data); + Bytes::from(raw) +} + +fn build_proof_packet( + link_id: [u8; 16], + context: rns_wire::context::PacketContext, + body: &[u8], +) -> Bytes { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Proof, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(body); + Bytes::from(raw) +} + +fn build_data_packet( + link_id: [u8; 16], + context: rns_wire::context::PacketContext, + body: &[u8], +) -> Bytes { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(body); + Bytes::from(raw) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn build_link_request_packet_has_link_request_type() { + let pkt = build_link_request_packet([0xAA; 16], &[0x01, 0x02, 0x03]); + let (header, _) = rns_wire::header::PacketHeader::unpack(&pkt).unwrap(); + assert_eq!( + header.flags.packet_type, + rns_wire::flags::PacketType::LinkRequest + ); + assert_eq!(header.destination_hash, [0xAA; 16]); + } + + #[test] + fn build_data_packet_carries_context() { + let pkt = build_data_packet([0xBB; 16], rns_wire::context::PacketContext::Lrrtt, &[0x42]); + let (header, _) = rns_wire::header::PacketHeader::unpack(&pkt).unwrap(); + assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt); + assert_eq!(header.flags.packet_type, rns_wire::flags::PacketType::Data); + } + + #[tokio::test] + async fn time_remaining_returns_err_after_deadline() { + let past = Instant::now(); + tokio::time::sleep(Duration::from_millis(1)).await; + assert!(matches!( + time_remaining(past), + Err(LinkClientError::Timeout(_)) + )); + } + + #[tokio::test] + async fn send_close_uses_authenticated_teardown_payload() { + let dest_hash = [0xCC; 16]; + let responder_key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let responder_pub = responder_key.public_key(); + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut responder, proof_data) = + Link::new_responder(&request_data, &responder_key, dest_hash, 1).unwrap(); + let rtt_data = initiator + .validate_proof(&proof_data, &responder_pub, &responder_pub.to_bytes()) + .unwrap(); + responder.receive_rtt_packet(&rtt_data).unwrap(); + + let (transport_tx, mut transport_rx) = mpsc::channel(4); + let client = LinkClient::new(transport_tx, Identity::new()); + client.send_close(&mut initiator).await.unwrap(); + + let TransportMessage::Outbound(request) = transport_rx.try_recv().unwrap() else { + panic!("expected outbound close packet"); + }; + let (header, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + assert_eq!(header.context, rns_wire::context::PacketContext::LinkClose); + assert!(responder.receive_teardown(&request.raw[offset..])); + } +} diff --git a/crates/rns-runtime/src/link_manager.rs b/crates/rns-runtime/src/link_manager.rs new file mode 100644 index 0000000..f48c50b --- /dev/null +++ b/crates/rns-runtime/src/link_manager.rs @@ -0,0 +1,3435 @@ +//! Responder side of Reticulum links: accepts link requests, holds per-link +//! state (session keys, channel, in/outbound transfers), drives keepalives +//! and teardown. Lives here to break the rns-transport ↔ rns-link cycle. + +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex}; + +use bytes::Bytes; +use tokio::sync::{mpsc, oneshot}; + +use rns_crypto::ed25519::Ed25519PrivateKey; +use rns_identity::destination::{DestType, Destination, Direction}; +use rns_identity::identity::Identity; +use rns_link::link::{CloseReason, Link, LinkAction, LinkState}; +use rns_protocol::channel::{ChannelError, LinkChannel}; +use rns_protocol::channel_message::MessageBase; +use rns_protocol::resource::{ + InboundTransfer, MAX_EFFICIENT_SIZE, MAX_SEGMENTS, MultiSegmentInbound, MultiSegmentOutbound, + OutboundTransfer, TransferAction, +}; +use rns_protocol::resource_adv::ResourceAdvertisement; +use rns_transport::link_messages::{AnnounceRequest, DestinationEvent}; +use rns_transport::messages::{OutboundRequest, TransportMessage}; + +struct ActiveLink { + link: Link, + _interface_id: u64, + /// Created lazily on first CHANNEL packet. + channel: Option, + inbound_resources: HashMap<[u8; 32], InboundTransfer>, + outbound_resources: HashMap<[u8; 32], OutboundTransfer>, + outbound_split_queues: HashMap<[u8; 32], VecDeque>, + /// Split-resource reassembly keyed by `original_hash`; dropped on full delivery or cancel. + inbound_split_resources: HashMap<[u8; 32], MultiSegmentInbound>, + /// Reverse index per-segment `resource_hash` → coordinator; routes assembled + /// bytes without re-parsing the ADV. + segment_routing: HashMap<[u8; 32], SegmentRoute>, +} + +#[derive(Debug, Clone, Copy)] +struct SegmentRoute { + original_hash: [u8; 32], + segment_index: usize, +} + +#[derive(Debug)] +pub struct LinkResponse { + pub link_id: [u8; 16], + pub request_id: [u8; 16], + pub data: Vec, +} + +#[derive(Debug, Clone)] +pub struct LinkChannelMessage { + pub link_id: [u8; 16], + pub msg_type: u16, + pub payload: Vec, +} + +#[derive(Debug, Clone)] +pub struct ChannelSendReceipt { + pub link_id: [u8; 16], + pub sequence: u16, + pub packet_hash: [u8; 32], +} + +#[derive(Debug, thiserror::Error)] +pub enum ChannelSendError { + #[error("link not found")] + LinkNotFound, + #[error("link is not active")] + LinkNotActive, + #[error("link session keys are unavailable")] + NoSessionKeys, + #[error("channel error: {0}")] + Channel(#[from] ChannelError), + #[error("transport channel is full or closed")] + TransportUnavailable, +} + +pub enum LinkManagerCommand { + SendChannelMessage { + link_id: [u8; 16], + message: Box, + result_tx: Option>>, + }, + CloseLink { + link_id: [u8; 16], + reason: CloseReason, + send_teardown: bool, + }, + Announce, + Shutdown, +} + +/// Resource hash + sender metadata (e.g. rncp filename). +#[derive(Debug, Clone)] +pub struct ResourceCompletion { + pub link_id: [u8; 16], + pub resource_hash: [u8; 32], + pub data: Vec, + /// msgpack-encoded metadata, if the sender attached any. + pub metadata: Option>, +} + +/// Result of an extended request handler. `Reply` is the ordinary response; +/// `ReplyWithResource` sends an inline ack followed by a resource transfer +/// (rncp --fetch). Python: `RNS.Resource(..., target_link=link)`. +#[derive(Debug, Clone)] +pub enum RequestOutcome { + Reply(Vec), + ReplyWithResource { + ack: Vec, + data: Vec, + /// Optional msgpack-encoded metadata (e.g. `{"name": "file.bin"}`). + metadata: Option>, + auto_compress: bool, + }, + /// Silently drop; caller sees a timeout. Useful for ACL denies. + Drop, +} + +type RequestHandler = Box) -> Option> + Send>; +type RequestHandlerEx = Box) -> RequestOutcome + Send>; +type LinkIdentityGate = Box bool + Send>; + +struct ResourceTransferStart { + data: Vec, + metadata: Option>, + auto_compress: bool, + request_id: Option>, + is_response: bool, + allow_handshake: bool, +} + +pub struct LinkManager { + transport_tx: mpsc::Sender, + event_rx: mpsc::Receiver, + active_links: HashMap<[u8; 16], ActiveLink>, + /// `None` rejects all links. + identity_key: Option, + pub destination_hash: [u8; 16], + destination: Option, + identity: Option, + /// `(link_id, path_hash, data) -> Option`. + request_handler: Option, + /// Wins over `request_handler` when set; can schedule a resource transfer. + request_handler_ex: Option, + /// Called when the transport actor asks this destination to re-announce. + announce_handler: Option>, + response_tx: Option>, + /// Legacy LXMF completion notifier. + resource_completed_tx: Option, [u8; 16])>>, + /// Resource hash + metadata. + resource_completion_tx: Option>, + /// Fires when a link reaches the active state. + link_established_tx: Option>, + /// Fires on LinkIdentify before a resource ADV can race it. + link_identified_tx: Option>, + /// Synchronous LinkIdentify gate. Returning false closes the link before + /// later resource packets can be accepted. + link_identity_gate: Option, + /// Decrypted link-packet stream (LXMF DIRECT). + link_packet_tx: Option, [u8; 16])>>, + /// Decrypted channel envelopes as `(link_id, msg_type, payload)`. + channel_message_tx: Option>, + /// Fires when an active link is closed or torn down. + link_closed_tx: Option>, + /// Raw pass-through for non-link packets (e.g. opportunistic LXMF). + inbound_raw_tx: Option>>, + /// Remote identity hash → link_id; populated on LinkIdentify for outbound reuse. + backchannel_links: HashMap<[u8; 16], [u8; 16]>, + /// Shared reverse map so sync request handlers can look up the authenticated peer. + link_identities: Arc>>, +} + +impl LinkManager { + pub fn new( + transport_tx: mpsc::Sender, + event_rx: mpsc::Receiver, + destination_hash: [u8; 16], + identity_key: Option, + ) -> Self { + Self { + transport_tx, + event_rx, + active_links: HashMap::new(), + identity_key, + destination_hash, + destination: None, + identity: None, + request_handler: None, + request_handler_ex: None, + announce_handler: None, + response_tx: None, + resource_completed_tx: None, + resource_completion_tx: None, + link_established_tx: None, + link_identified_tx: None, + link_identity_gate: None, + link_packet_tx: None, + channel_message_tx: None, + link_closed_tx: None, + inbound_raw_tx: None, + backchannel_links: HashMap::new(), + link_identities: Arc::new(Mutex::new(HashMap::new())), + } + } + + /// Wraps its own [`Destination`] so acceptance gating + dest callbacks are active. + pub fn with_destination( + transport_tx: mpsc::Sender, + event_rx: mpsc::Receiver, + identity: &Identity, + app_name: &str, + identity_key: Ed25519PrivateKey, + ) -> Self { + let dest = match Destination::new(Some(identity), Direction::In, DestType::Single, app_name) + { + Ok(d) => Some(d), + Err(e) => { + tracing::error!(error = %e, app_name, "Destination::new() failed — link manager will not accept links"); + None + } + }; + + let destination_hash = dest.as_ref().map(|d| d.hash).unwrap_or([0; 16]); + let manager_identity = clone_identity(identity); + + Self { + transport_tx, + event_rx, + active_links: HashMap::new(), + identity_key: Some(identity_key), + destination_hash, + destination: dest, + identity: manager_identity, + request_handler: None, + request_handler_ex: None, + announce_handler: None, + response_tx: None, + resource_completed_tx: None, + resource_completion_tx: None, + link_established_tx: None, + link_identified_tx: None, + link_identity_gate: None, + link_packet_tx: None, + channel_message_tx: None, + link_closed_tx: None, + inbound_raw_tx: None, + backchannel_links: HashMap::new(), + link_identities: Arc::new(Mutex::new(HashMap::new())), + } + } + + pub fn get_backchannel_link(&self, identity_hash: &[u8; 16]) -> Option<[u8; 16]> { + self.backchannel_links.get(identity_hash).copied() + } + + /// Shared auth map for sync request handlers (which can't borrow `self`). + /// Populated on `LinkIdentify`, pruned on link close. + pub fn link_identities_handle(&self) -> Arc>> { + Arc::clone(&self.link_identities) + } + + pub fn try_step(&mut self) -> bool { + match self.event_rx.try_recv() { + Ok(event) => { + self.handle_event(event); + true + } + Err(mpsc::error::TryRecvError::Empty | mpsc::error::TryRecvError::Disconnected) => { + false + } + } + } + + pub async fn step(&mut self) -> bool { + let Some(event) = self.event_rx.recv().await else { + return false; + }; + self.handle_event(event); + true + } + + pub fn tick(&mut self) { + self.on_tick(); + } + + pub async fn run(mut self) { + let mut tick_interval = tokio::time::interval(std::time::Duration::from_secs(1)); + + loop { + tokio::select! { + event = self.event_rx.recv() => { + match event { + Some(evt) => self.handle_event(evt), + None => break, + } + } + _ = tick_interval.tick() => { + self.tick(); + } + } + } + } + + pub async fn run_with_commands(mut self, mut command_rx: mpsc::Receiver) { + let mut last_tick = std::time::Instant::now(); + loop { + while let Ok(command) = command_rx.try_recv() { + if !self.handle_command(command) { + return; + } + } + + while self.try_step() {} + + if last_tick.elapsed() >= std::time::Duration::from_secs(1) { + self.tick(); + last_tick = std::time::Instant::now(); + } + + if command_rx.is_closed() && command_rx.is_empty() { + return; + } + + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + } + + fn handle_command(&mut self, command: LinkManagerCommand) -> bool { + match command { + LinkManagerCommand::SendChannelMessage { + link_id, + message, + result_tx, + } => { + let result = self.send_channel_message(&link_id, message.as_ref()); + if let Some(tx) = result_tx { + let _ = tx.send(result); + } + true + } + LinkManagerCommand::CloseLink { + link_id, + reason, + send_teardown, + } => { + self.close_active_link(link_id, reason, send_teardown); + true + } + LinkManagerCommand::Announce => { + if let Some(handler) = self.announce_handler.as_mut() { + handler(); + } + true + } + LinkManagerCommand::Shutdown => false, + } + } + + fn handle_event(&mut self, event: DestinationEvent) { + match event { + DestinationEvent::LinkRequest { raw, interface_id } => { + self.handle_link_request(&raw, interface_id); + } + DestinationEvent::InboundPacket { raw, interface_id } => { + self.handle_inbound_packet(&raw, interface_id); + } + DestinationEvent::LinkEstablished { link_id } => { + if let Some(ref tx) = self.link_established_tx { + let _ = tx.try_send(link_id); + } + tracing::debug!(link_id = hex::encode(link_id), "link established event"); + } + DestinationEvent::LinkClosed { link_id } => { + if self.close_active_link(link_id, CloseReason::InitiatorClosed, true) { + tracing::debug!(link_id = hex::encode(link_id), "link closed"); + } + } + DestinationEvent::DeliveryProof { msg_id, .. } => { + tracing::debug!(msg_id = %msg_id, "delivery proof (unhandled in link manager)"); + } + DestinationEvent::AnnounceRequested(request) => { + if request.path_response { + self.send_destination_announce(request); + } else if let Some(handler) = self.announce_handler.as_mut() { + handler(); + } else { + self.send_destination_announce(request); + } + } + } + } + + fn send_destination_announce(&mut self, request: AnnounceRequest) { + let Some(destination) = self.destination.as_mut() else { + tracing::debug!( + app_name = %request.app_name, + path_response = request.path_response, + "announce requested but no destination is configured" + ); + return; + }; + let Some(identity) = self.identity.as_ref() else { + tracing::warn!( + app_name = %request.app_name, + path_response = request.path_response, + "announce requested but no private identity is available" + ); + return; + }; + + let raw = match destination.announce_packet( + identity, + None, + None, + request.path_response, + request.tag.as_deref(), + unix_now(), + ) { + Ok(raw) => raw, + Err(e) => { + tracing::warn!( + error = %e, + app_name = %request.app_name, + path_response = request.path_response, + "failed to build requested announce" + ); + return; + } + }; + + let outbound = OutboundRequest { + raw: Bytes::from(raw), + destination_hash: self.destination_hash, + }; + let message = if let Some(interface_id) = request.attached_interface { + TransportMessage::OutboundAttached { + request: outbound, + interface_id, + } + } else { + TransportMessage::Outbound(outbound) + }; + if let Err(e) = self.transport_tx.try_send(message) { + tracing::warn!( + app_name = %request.app_name, + path_response = request.path_response, + err = %e, + "failed to queue requested announce" + ); + } + } + + fn handle_link_request(&mut self, raw: &[u8], interface_id: u64) { + let identity_key = match &self.identity_key { + Some(k) => k, + None => { + tracing::warn!("link request received but no identity key configured"); + return; + } + }; + + let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(raw) { + Ok(h) => h, + Err(_) => return, + }; + + if raw.len() <= data_offset { + tracing::warn!("link request has no payload data"); + return; + } + let request_data = &raw[data_offset..]; + + let hops = header.hops; + + if let Some(ref dest) = self.destination + && !dest.accept_link_requests + { + tracing::debug!("link request rejected — destination not accepting links"); + return; + } + + let (link, proof_data) = + match Link::new_responder(request_data, identity_key, self.destination_hash, hops) { + Ok(result) => result, + Err(e) => { + tracing::warn!(error = %e, "link handshake failed"); + return; + } + }; + + let link_id = link.link_id; + + let proof_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 at origin (Python `Packet.__init__`). + let proof_hops = 0; + let proof_header = rns_wire::header::PacketHeader { + flags: proof_flags, + hops: proof_hops, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Lrproof, + }; + let mut proof_raw = proof_header.pack(); + proof_raw.extend_from_slice(&proof_data); + + tracing::info!( + link_id = hex::encode(link_id), + proof_len = proof_raw.len(), + proof_data_len = proof_data.len(), + "link proof packet built" + ); + + let _ = self + .transport_tx + .try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(proof_raw), + destination_hash: link_id, + })); + + // Required: transport drops link-addressed packets (LRRTT, Resource, + // Keepalive...) as unroutable without this registration. + let _ = self.transport_tx.try_send(TransportMessage::RegisterLink { + link_id, + destination_hash: self.destination_hash, + interface_id, + next_hop: None, + remaining_hops: 0, + initiator: false, + }); + + tracing::info!( + link_id = hex::encode(link_id), + dest = hex::encode(self.destination_hash), + request_hops = hops, + "link request handled — ECDH handshake complete, proof sent, link registered" + ); + + if let Some(ref mut dest) = self.destination { + dest.incoming_link_request(link_id); + } + + // LXMF DIRECT uses resource transfer past `LINK_PACKET_MAX_CONTENT`; + // AcceptAll skips Python's `ACCEPT_APP` hook. + let mut link = link; + link.resource_strategy = rns_link::link::ResourceStrategy::AcceptAll; + + self.active_links.insert( + link_id, + ActiveLink { + link, + _interface_id: interface_id, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + } + + fn handle_inbound_packet(&mut self, raw: &[u8], _interface_id: u64) { + let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(raw) { + Ok(h) => h, + Err(e) => { + tracing::warn!(error = %e, raw_len = raw.len(), "link_manager: packet header parse failed"); + return; + } + }; + + let data = if raw.len() > data_offset { + &raw[data_offset..] + } else { + &[] + }; + + // For link packets `destination_hash` is the link_id; otherwise it's + // a destination-level packet for app decryption (opportunistic LXMF). + let link_id = header.destination_hash; + + if !self.active_links.contains_key(&link_id) { + if let Some(ref tx) = self.inbound_raw_tx { + let _ = tx.try_send(raw.to_vec()); + } + tracing::debug!( + dest = hex::encode(link_id), + data_len = data.len(), + "link_manager: non-link packet forwarded to application (raw)" + ); + return; + } + + tracing::info!( + link_id = hex::encode(link_id), + context = ?header.context, + data_len = data.len(), + "inbound link packet" + ); + + if header.flags.packet_type == rns_wire::flags::PacketType::Proof + && matches!( + header.context, + rns_wire::context::PacketContext::None + | rns_wire::context::PacketContext::LinkProof + ) + { + self.handle_link_packet_proof(link_id, data); + return; + } + + match header.context { + rns_wire::context::PacketContext::Lrrtt => { + if let Some(active) = self.active_links.get_mut(&link_id) + && active.link.state == LinkState::Handshake + { + match active.link.receive_rtt_packet(data) { + Ok(()) => { + tracing::info!( + link_id = hex::encode(link_id), + rtt_ms = active.link.rtt.map(|r| r.as_millis()).unwrap_or(0), + "link activated via LRRTT" + ); + + if let Some(ref cb) = active.link.link_established_callback { + cb(&active.link); + } + if let Some(ref dest) = self.destination { + dest.on_link_established(link_id); + } + if let Some(ref tx) = self.link_established_tx { + let _ = tx.try_send(link_id); + } + } + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + error = %e, + "LRRTT processing failed" + ); + } + } + } + } + rns_wire::context::PacketContext::LinkIdentify => { + let mut close_rejected_link = false; + if let Some(active) = self.active_links.get_mut(&link_id) { + match active.link.handle_identification(data) { + Ok(remote_pub) => { + let identity_hash = rns_crypto::sha::truncated_hash(&remote_pub); + let accepted = self + .link_identity_gate + .as_ref() + .map(|gate| gate(link_id, identity_hash)) + .unwrap_or(true); + self.backchannel_links.insert(identity_hash, link_id); + if let Ok(mut ids) = self.link_identities.lock() { + ids.insert(link_id, identity_hash); + } + if let Some(ref tx) = self.link_identified_tx { + let _ = tx.try_send((link_id, identity_hash)); + } + tracing::info!( + link_id = hex::encode(link_id), + remote_pub = hex::encode(&remote_pub[..8]), + identity_hash = hex::encode(identity_hash), + "remote peer identified on link — backchannel tracked" + ); + if let Some(ref cb) = active.link.remote_identified_callback { + cb(&active.link, &remote_pub); + } + if !accepted { + close_rejected_link = true; + } + } + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + error = %e, + "link identification failed" + ); + } + } + } + if close_rejected_link { + let _ = self.close_active_link(link_id, CloseReason::InitiatorClosed, true); + } + } + rns_wire::context::PacketContext::Keepalive => { + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + + // Keepalives are NOT encrypted (Packet.py:205-208). + if data.first() == Some(&rns_link::constants::KEEPALIVE_REQUEST) { + // Only the responder replies. + if active.link.is_initiator { + tracing::trace!( + link_id = hex::encode(link_id), + "ignoring keepalive request on initiator side" + ); + } else { + let resp_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Keepalive, + }; + let mut resp_raw = resp_header.pack(); + resp_raw.push(rns_link::constants::KEEPALIVE_RESPONSE); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(resp_raw), + destination_hash: link_id, + }, + )); + } + } + } + } + rns_wire::context::PacketContext::LinkClose => { + let verified = self + .active_links + .get_mut(&link_id) + .is_some_and(|active| active.link.receive_teardown(data)); + if verified { + tracing::info!(link_id = hex::encode(link_id), "link torn down by remote"); + self.close_active_link(link_id, CloseReason::DestinationClosed, false); + } + } + rns_wire::context::PacketContext::Channel => { + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + active.link.record_rx(data.len()); + + if !matches!(active.link.state, LinkState::Active | LinkState::Stale) { + tracing::debug!( + link_id = hex::encode(link_id), + state = ?active.link.state, + "channel data received before active link" + ); + return; + } + + if active.channel.is_none() + && Self::ensure_link_channel(active, link_id).is_none() + { + tracing::debug!( + link_id = hex::encode(link_id), + "channel data received before session keys were available" + ); + return; + } + + let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type); + if let Ok(proof_data) = active.link.prove_packet_with_link_key(&pkt_hash) { + Self::send_link_packet_proof( + &self.transport_tx, + &link_id, + &proof_data, + rns_wire::context::PacketContext::None, + ); + tracing::debug!( + link_id = hex::encode(link_id), + proof_len = proof_data.len(), + "delivery proof sent for channel packet" + ); + } + + if let Some(ref mut channel) = active.channel { + match channel.receive_data(data) { + Ok(messages) => { + if let Some(ref tx) = self.channel_message_tx { + for (msg_type, payload) in messages { + let _ = tx.try_send(LinkChannelMessage { + link_id, + msg_type, + payload, + }); + } + } + } + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + error = %e, + "channel data processing failed" + ); + } + } + } + } + } + rns_wire::context::PacketContext::ResourceAdv => { + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + + if let Ok(plaintext) = active.link.decrypt(data) { + match ResourceAdvertisement::unpack(&plaintext) { + Ok(adv) => { + // Split-resource routing set up before the per-segment + // transfer. The MAX_SEGMENTS cap is load-bearing: a peer + // could otherwise advertise u32::MAX and OOM + // `MultiSegmentInbound::new`. + if adv.total_segments > 1 { + if adv.total_segments > MAX_SEGMENTS + || adv.segment_index == 0 + || adv.segment_index > adv.total_segments + { + tracing::warn!( + link_id = hex::encode(link_id), + total_segments = adv.total_segments, + segment_index = adv.segment_index, + max_segments = MAX_SEGMENTS, + "rejecting split-resource ADV with out-of-range segment metadata" + ); + return; + } + // Mid-stream changes to `total_segments` are rejected. + let entry = active + .inbound_split_resources + .entry(adv.original_hash) + .or_insert_with(|| { + MultiSegmentInbound::new( + adv.total_segments, + adv.original_hash, + ) + }); + if entry.total_segments != adv.total_segments { + tracing::warn!( + link_id = hex::encode(link_id), + original = hex::encode(&adv.original_hash[..8]), + coord_total = entry.total_segments, + adv_total = adv.total_segments, + "split-resource ADV total_segments mismatched coordinator; ignoring" + ); + return; + } + active.segment_routing.insert( + adv.resource_hash, + SegmentRoute { + original_hash: adv.original_hash, + segment_index: adv.segment_index, + }, + ); + } + + let map_hashes = adv.get_map_hashes(); + let mut transfer_flags = adv.flags; + if adv.total_segments > 1 && adv.segment_index > 1 { + transfer_flags.has_metadata = false; + } + let rtt = active + .link + .rtt + .unwrap_or(std::time::Duration::from_millis(500)); + let mut rh = [0u8; rns_protocol::resource::RANDOM_HASH_SIZE]; + let copy_len = adv.random_hash.len().min(rh.len()); + rh[..copy_len].copy_from_slice(&adv.random_hash[..copy_len]); + + if let Ok(mut transfer) = InboundTransfer::from_advertisement( + adv.num_parts, + adv.transfer_size, + adv.data_size, + rh, + adv.resource_hash, + transfer_flags, + map_hashes, + rtt, + ) { + // Python Resource.accept → request_next: initial request + // accepts the ADV and names the parts. + let action = transfer.request_next(); + if let TransferAction::SendRequest(req_data) = action + && let Ok(encrypted) = active.link.encrypt(&req_data) + { + let req_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: + rns_wire::flags::TransportType::Broadcast, + destination_type: + rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::ResourceReq, + }; + let mut req_raw = req_header.pack(); + req_raw.extend_from_slice(&encrypted); + let _ = self.transport_tx.try_send( + TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(req_raw), + destination_hash: link_id, + }), + ); + } + + active.link.track_incoming_resource(adv.resource_hash); + active.inbound_resources.insert(adv.resource_hash, transfer); + tracing::info!( + link_id = hex::encode(link_id), + resource = hex::encode(&adv.resource_hash[..8]), + parts = adv.num_parts, + "inbound resource accepted — initial request sent" + ); + } + } + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + error = %e, + "failed to parse resource advertisement" + ); + } + } + } + } + } + rns_wire::context::PacketContext::Resource => { + // Python encrypts payload ONCE before chunking (Resource.py:424); + // chunks ride raw. Decrypt happens in InboundTransfer::complete. + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + active.link.record_rx(data.len()); + + { + let plaintext = data.to_vec(); + let mut resource_action_to_send = None; + let mut completed_rh = None; + for (rh, transfer) in &mut active.inbound_resources { + let action = transfer.receive_part(plaintext.clone()); + tracing::info!( + link_id = hex::encode(link_id), + resource = hex::encode(&rh[..8]), + action = ?action, + is_complete = transfer.resource.is_complete(), + total_parts = transfer.resource.total_parts, + received = transfer.resource.consecutive_completed, + "resource part received — action" + ); + match action { + TransferAction::SendHmu(_) | TransferAction::SendRequest(_) => { + resource_action_to_send = Some(action); + } + TransferAction::Complete => { + completed_rh = Some(*rh); + } + _ => {} + } + if completed_rh.is_none() && transfer.resource.is_complete() { + completed_rh = Some(*rh); + } + if resource_action_to_send.is_some() || completed_rh.is_some() { + break; + } + } + + if let Some(action) = resource_action_to_send { + let (context, payload) = match action { + TransferAction::SendHmu(hmu) => { + (rns_wire::context::PacketContext::ResourceHmu, hmu) + } + TransferAction::SendRequest(req) => { + (rns_wire::context::PacketContext::ResourceReq, req) + } + _ => unreachable!(), + }; + if let Ok(encrypted) = active.link.encrypt(&payload) { + let hmu_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut hmu_raw = hmu_header.pack(); + hmu_raw.extend_from_slice(&encrypted); + active.link.record_tx(hmu_raw.len()); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(hmu_raw), + destination_hash: link_id, + }, + )); + } + } + + if let Some(rh) = completed_rh { + // Reverses pre-chunk encryption (Resource.py:424). + let decrypt_fn = |data: &[u8]| -> Result< + Vec, + rns_protocol::resource::ResourceError, + > { + active.link.decrypt(data).map_err(|_| { + rns_protocol::resource::ResourceError::DecryptFailed + }) + }; + + if let Some(transfer) = active.inbound_resources.get_mut(&rh) + && let Ok((assembled_data, proof)) = + transfer.complete(Some(&decrypt_fn)) + { + // PROOF+RESOURCE_PRF = plaintext, PacketType::Proof + // (Packet.py:195-197). Each split segment still needs its + // own proof or the sender retries. + let prf_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::ResourcePrf, + }; + let mut prf_raw = prf_header.pack(); + prf_raw.extend_from_slice(&proof); + active.link.record_tx(prf_raw.len()); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(prf_raw), + destination_hash: link_id, + }, + )); + + // Split resources route to a coordinator keyed by + // `original_hash`; completion fires only on full reassembly. + if let Some(route) = active.segment_routing.remove(&rh) { + let seg_meta = active + .inbound_resources + .get(&rh) + .and_then(|t| t.resource.metadata.clone()); + + if let Some(coord) = + active.inbound_split_resources.get_mut(&route.original_hash) + { + match coord + .set_segment_data(route.segment_index, assembled_data) + { + Ok(()) => { + if let Some(meta) = seg_meta { + coord.set_metadata(meta); + } + } + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + original = hex::encode( + &route.original_hash[..8] + ), + segment = route.segment_index, + error = ?e, + "split-resource coordinator rejected segment" + ); + } + } + + if coord.is_complete() { + match coord.reassemble() { + Ok(blob) => { + let metadata = coord.metadata.take(); + let total_segments = coord.total_segments; + if let Some(ref tx) = + self.resource_completion_tx + { + let _ = tx.try_send(ResourceCompletion { + link_id, + resource_hash: route.original_hash, + data: blob.clone(), + metadata, + }); + } + if let Some(ref tx) = self.resource_completed_tx + { + let _ = tx.try_send((blob, link_id)); + } + tracing::info!( + link_id = hex::encode(link_id), + original = + hex::encode(&route.original_hash[..8]), + total_segments, + "split-resource reassembly complete" + ); + } + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + original = hex::encode( + &route.original_hash[..8] + ), + error = ?e, + "split-resource reassembly failed" + ); + } + } + active + .inbound_split_resources + .remove(&route.original_hash); + } else { + tracing::debug!( + link_id = hex::encode(link_id), + original = hex::encode(&route.original_hash[..8]), + segment = route.segment_index, + progress = coord.assembled_count(), + total = coord.total_segments, + "split-resource segment received — awaiting more" + ); + } + } else { + tracing::warn!( + link_id = hex::encode(link_id), + original = hex::encode(&route.original_hash[..8]), + "split-resource coordinator missing for completed segment" + ); + } + } else { + // Single-segment path: rncp channel keeps metadata + + // resource hash; the legacy LXMF channel drops both. + if let Some(ref tx) = self.resource_completion_tx { + let metadata = active + .inbound_resources + .get(&rh) + .and_then(|t| t.resource.metadata.clone()); + let _ = tx.try_send(ResourceCompletion { + link_id, + resource_hash: rh, + data: assembled_data.clone(), + metadata, + }); + } + + if let Some(ref tx) = self.resource_completed_tx { + let _ = tx.try_send((assembled_data, link_id)); + } + + tracing::debug!( + link_id = hex::encode(link_id), + resource = hex::encode(&rh[..8]), + "inbound resource transfer completed — proof sent" + ); + } + } + active.link.untrack_resource(&rh); + active.inbound_resources.remove(&rh); + } + } + } + } + rns_wire::context::PacketContext::ResourceReq => { + // Receiver's HMU for outbound transfer (Link.py:1104-1124). + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + if let Ok(plaintext) = active.link.decrypt(data) + && plaintext.len() > 32 + { + // Exhaustion flag shifts the resource hash by MAPHASH_LEN. + let resource_hash_start = + if plaintext[0] == rns_protocol::resource::HASHMAP_IS_EXHAUSTED { + 1 + rns_protocol::resource::MAPHASH_LEN + } else { + 1 + }; + if plaintext.len() >= resource_hash_start + 32 { + let mut rh = [0u8; 32]; + rh.copy_from_slice( + &plaintext[resource_hash_start..resource_hash_start + 32], + ); + let packet_hash = + rns_wire::hash::packet_hash(raw, header.flags.header_type); + let actions = active + .outbound_resources + .get_mut(&rh) + .map(|transfer| { + transfer.handle_request_packet(packet_hash, &plaintext) + }) + .unwrap_or_default(); + for action in actions { + let (context, body) = match action { + TransferAction::SendPart(idx, part_data) => { + tracing::trace!( + link_id = hex::encode(link_id), + part = idx, + "sent resource part (request response)" + ); + ( + rns_wire::context::PacketContext::Resource, + Bytes::from(part_data), + ) + } + TransferAction::SendHmu(hmu) => { + let Ok(encrypted) = active.link.encrypt(&hmu) else { + continue; + }; + ( + rns_wire::context::PacketContext::ResourceHmu, + Bytes::from(encrypted), + ) + } + TransferAction::SendRequest(req) => { + let Ok(encrypted) = active.link.encrypt(&req) else { + continue; + }; + ( + rns_wire::context::PacketContext::ResourceReq, + Bytes::from(encrypted), + ) + } + TransferAction::SendCancel(cancel_type, resource_hash) => { + let Ok(encrypted) = active.link.encrypt(&resource_hash) + else { + continue; + }; + 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 + } + }; + (context, Bytes::from(encrypted)) + } + _ => continue, + }; + let part_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut raw = part_header.pack(); + raw.extend_from_slice(&body); + active.link.record_tx(raw.len()); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(raw), + destination_hash: link_id, + }, + )); + } + } + } + } + } + rns_wire::context::PacketContext::ResourceIcl => { + // Sender-initiated cancel of an inbound transfer (Link.py:1135-1142). + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + if let Ok(plaintext) = active.link.decrypt(data) + && plaintext.len() >= 32 + { + let mut rh = [0u8; 32]; + rh.copy_from_slice(&plaintext[..32]); + if let Some(transfer) = active.inbound_resources.get_mut(&rh) { + transfer.handle_cancel(); + tracing::debug!( + link_id = hex::encode(link_id), + "RESOURCE_ICL — inbound transfer cancelled" + ); + } + active.inbound_resources.remove(&rh); + + // Sender-cancel of a split-segment tears down the whole + // reassembly state (coordinator + sibling segments) so + // the coordinator isn't orphaned forever. + if let Some(route) = active.segment_routing.remove(&rh) { + let oh = route.original_hash; + active.inbound_split_resources.remove(&oh); + let siblings: Vec<[u8; 32]> = active + .segment_routing + .iter() + .filter_map(|(seg_rh, r)| { + if r.original_hash == oh { + Some(*seg_rh) + } else { + None + } + }) + .collect(); + for sibling_rh in siblings { + active.segment_routing.remove(&sibling_rh); + active.inbound_resources.remove(&sibling_rh); + active.link.untrack_resource(&sibling_rh); + } + tracing::debug!( + link_id = hex::encode(link_id), + original = hex::encode(&oh[..8]), + "split-resource cancelled by sender — coordinator + siblings dropped" + ); + } + } + } + } + rns_wire::context::PacketContext::ResourceRcl => { + // Receiver-initiated reject of an outbound transfer (Link.py:1144-1151). + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + if let Ok(plaintext) = active.link.decrypt(data) + && plaintext.len() >= 32 + { + let mut rh = [0u8; 32]; + rh.copy_from_slice(&plaintext[..32]); + if let Some(transfer) = active.outbound_resources.get_mut(&rh) { + transfer.resource.handle_cancel(); + tracing::debug!( + link_id = hex::encode(link_id), + "RESOURCE_RCL — outbound transfer rejected" + ); + } + active.outbound_resources.remove(&rh); + } + } + } + rns_wire::context::PacketContext::ResourceHmu => { + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + if let Ok(plaintext) = active.link.decrypt(data) + && let Ok((rh, segment, hashmap)) = + rns_protocol::resource::parse_hashmap_update(&plaintext) + && let Some(transfer) = active.inbound_resources.get_mut(&rh) + { + let action = transfer.hashmap_update(segment, &hashmap); + if let TransferAction::SendRequest(req) = action + && let Ok(encrypted) = active.link.encrypt(&req) + { + let req_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::ResourceReq, + }; + let mut req_raw = req_header.pack(); + req_raw.extend_from_slice(&encrypted); + active.link.record_tx(req_raw.len()); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(req_raw), + destination_hash: link_id, + }, + )); + } + } + } + } + rns_wire::context::PacketContext::ResourcePrf => { + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + if data.len() >= 64 { + let mut rh = [0u8; 32]; + rh.copy_from_slice(&data[..32]); + let queue_key = active + .outbound_resources + .get(&rh) + .and_then(|transfer| transfer.resource.original_hash); + let complete = active + .outbound_resources + .get_mut(&rh) + .is_some_and(|transfer| transfer.handle_proof(data)); + if complete { + active.outbound_resources.remove(&rh); + if let Some(key) = queue_key { + let (next, empty) = if let Some(queue) = + active.outbound_split_queues.get_mut(&key) + { + let next = queue.pop_front(); + (next, queue.is_empty()) + } else { + (None, false) + }; + if empty { + active.outbound_split_queues.remove(&key); + } + if let Some(next) = next { + let _ = Self::start_outbound_transfer( + &self.transport_tx, + active, + &link_id, + next, + ); + } + } + } + } + } + } + rns_wire::context::PacketContext::Request => { + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + + if let Ok((_request_id, path_hash, _timestamp, data)) = + active.link.handle_request(data) + { + // Python Reticulum uses the truncated RNS packet hash + // as the request id for packet-sized Link requests. + // The packed-request hash is only used for request + // resources, where the request id is carried in the + // Resource advertisement. + let request_id = + rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type); + // request_handler_ex wins; it can schedule a resource transfer. + let outcome = if let Some(ref handler) = self.request_handler_ex { + handler(link_id, path_hash, data.clone()) + } else if let Some(ref handler) = self.request_handler { + match handler(link_id, path_hash, data.clone()) { + Some(r) => RequestOutcome::Reply(r), + None => RequestOutcome::Drop, + } + } else { + RequestOutcome::Drop + }; + + let (resp_bytes_opt, fetch_spec) = match outcome { + RequestOutcome::Reply(r) => (Some(r), None), + RequestOutcome::ReplyWithResource { + ack, + data, + metadata, + auto_compress, + } => (Some(ack), Some((data, metadata, auto_compress))), + RequestOutcome::Drop => (None, None), + }; + + let mut response_resource = None; + if let Some(resp_bytes) = resp_bytes_opt { + if let Ok(packed_response) = + rns_link::link::Link::pack_response(&request_id, &resp_bytes) + { + if packed_response.len() <= active.link.mdu { + if let Ok(encrypted) = active.link.encrypt(&packed_response) { + let resp_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: + rns_wire::flags::TransportType::Broadcast, + destination_type: + rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Response, + }; + let mut resp_raw = resp_header.pack(); + resp_raw.extend_from_slice(&encrypted); + let _ = self.transport_tx.try_send( + TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(resp_raw), + destination_hash: link_id, + }), + ); + tracing::debug!( + link_id = hex::encode(link_id), + request_id = hex::encode(request_id), + resp_len = resp_bytes.len(), + "link request handled — response sent" + ); + } + } else { + response_resource = Some((packed_response, request_id)); + } + } + } else { + tracing::debug!( + link_id = hex::encode(link_id), + request_id = hex::encode(request_id), + path = hex::encode(path_hash), + "link request received — no handler response" + ); + } + + if let Some((packed_response, request_id)) = response_resource { + let _ = + self.start_response_resource(&link_id, packed_response, request_id); + tracing::debug!( + link_id = hex::encode(link_id), + request_id = hex::encode(request_id), + "link request handled — response sent as resource" + ); + } + + if let Some((data, metadata, auto_compress)) = fetch_spec + && self + .start_resource_transfer_inner( + &link_id, + ResourceTransferStart { + data, + metadata, + auto_compress, + request_id: None, + is_response: false, + allow_handshake: true, + }, + ) + .is_none() + { + tracing::warn!( + link_id = hex::encode(link_id), + "link request resource response could not be started" + ); + } + } + } + } + rns_wire::context::PacketContext::Response => { + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + + if let Ok((request_id, response_data)) = active.link.handle_response(data) { + tracing::debug!( + link_id = hex::encode(link_id), + request_id = hex::encode(request_id), + response_len = response_data.len(), + "link response received — delivering to caller" + ); + + if let Some(ref tx) = self.response_tx { + let _ = tx.try_send(LinkResponse { + link_id, + request_id, + data: response_data, + }); + } + } + } + } + _ => { + // Application data on a link (LXMF DIRECT). + if let Some(active) = self.active_links.get_mut(&link_id) { + active.link.record_inbound(); + active.link.record_rx(data.len()); + if let Ok(plaintext) = active.link.decrypt(data) { + if let Some(ref cb) = active.link.packet_callback { + cb(&plaintext); + } + if let Some(ref tx) = self.link_packet_tx { + let _ = tx.try_send((plaintext, link_id)); + } + tracing::debug!( + link_id = hex::encode(link_id), + "link data packet decrypted and forwarded" + ); + + // Link proofs are unencrypted (Packet.py:198-200). + if let Some(ref signing_key) = self.identity_key { + let pkt_hash = + rns_wire::hash::packet_hash(raw, header.flags.header_type); + if let Ok(proof_data) = active.link.prove_packet(&pkt_hash, signing_key) + { + let proof_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::LinkProof, + }; + let mut proof_raw = proof_header.pack(); + proof_raw.extend_from_slice(&proof_data); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(proof_raw), + destination_hash: link_id, + }, + )); + tracing::info!( + link_id = hex::encode(link_id), + proof_len = proof_data.len(), + "delivery proof sent for link data packet (unencrypted)" + ); + } + } + } + } + } + } + } + + fn on_tick(&mut self) { + let mut to_remove = Vec::new(); + + for (link_id, active) in &mut self.active_links { + let timed_out_channel_sequences = active + .channel + .as_ref() + .map(LinkChannel::timed_out_sequences) + .unwrap_or_default(); + for sequence in timed_out_channel_sequences { + let resend = + active + .channel + .as_mut() + .and_then(|channel| match channel.timeout(sequence) { + Ok(resend) => resend, + Err(ChannelError::MaxRetriesExceeded) => { + tracing::warn!( + link_id = hex::encode(link_id), + sequence, + "channel packet exceeded max retries" + ); + to_remove.push(*link_id); + None + } + Err(error) => { + tracing::warn!( + link_id = hex::encode(link_id), + sequence, + error = %error, + "channel packet retry failed" + ); + None + } + }); + let Some(data) = resend else { + continue; + }; + + let (packet_hash, raw_len) = + Self::resend_channel_data(&self.transport_tx, link_id, sequence, &data); + if let Some(channel) = active.channel.as_mut() { + channel.track_outbound_packet_hash(packet_hash, sequence); + } + active.link.record_tx(raw_len); + } + + if !active.inbound_resources.is_empty() || !active.outbound_resources.is_empty() { + active.link.record_inbound(); + } + let action = active.link.tick(); + match action { + LinkAction::SendKeepalive => { + Self::send_keepalive_packet(&self.transport_tx, link_id); + } + LinkAction::TransitionedToStale => { + // Python double-sends on stale transition (Link.py:797-802, initiator only). + if active.link.is_initiator { + Self::send_keepalive_packet(&self.transport_tx, link_id); + } + tracing::debug!(link_id = hex::encode(link_id), "link transitioned to stale"); + } + LinkAction::SendTeardownAndClose(ref teardown_data) => { + if !teardown_data.is_empty() { + let td_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: *link_id, + context: rns_wire::context::PacketContext::LinkClose, + }; + let mut td_raw = td_header.pack(); + td_raw.extend_from_slice(teardown_data); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(td_raw), + destination_hash: *link_id, + }, + )); + } + to_remove.push(*link_id); + tracing::info!( + link_id = hex::encode(link_id), + "link stale timeout, teardown sent" + ); + } + LinkAction::Closed(_) => { + to_remove.push(*link_id); + } + LinkAction::None => {} + } + } + + for link_id in to_remove { + if self.close_active_link(link_id, CloseReason::Timeout, false) { + tracing::debug!(link_id = hex::encode(link_id), "link removed by tick"); + } + } + } + + fn close_active_link( + &mut self, + link_id: [u8; 16], + reason: CloseReason, + send_teardown: bool, + ) -> bool { + let Some(mut active) = self.active_links.remove(&link_id) else { + return false; + }; + + if send_teardown { + if let Some(teardown_data) = active.link.teardown(reason) { + Self::send_link_close_packet(&self.transport_tx, &link_id, &teardown_data); + } + } else { + active.link.mark_closed(reason); + } + + if let Some(ref cb) = active.link.link_closed_callback { + cb(&active.link); + } + + self.backchannel_links.retain(|_, lid| *lid != link_id); + if let Ok(mut ids) = self.link_identities.lock() { + ids.remove(&link_id); + } + let _ = self + .transport_tx + .try_send(TransportMessage::DeregisterDestination { hash: link_id }); + if let Some(ref tx) = self.link_closed_tx { + let _ = tx.try_send(link_id); + } + + true + } + + fn send_link_close_packet( + transport_tx: &mpsc::Sender, + link_id: &[u8; 16], + teardown_data: &[u8], + ) { + let td_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: *link_id, + context: rns_wire::context::PacketContext::LinkClose, + }; + let mut td_raw = td_header.pack(); + td_raw.extend_from_slice(teardown_data); + let _ = transport_tx.try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(td_raw), + destination_hash: *link_id, + })); + } + + fn send_keepalive_packet(transport_tx: &mpsc::Sender, link_id: &[u8; 16]) { + let ka_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: *link_id, + context: rns_wire::context::PacketContext::Keepalive, + }; + let mut ka_raw = ka_header.pack(); + ka_raw.push(rns_link::constants::KEEPALIVE_REQUEST); + let _ = transport_tx.try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(ka_raw), + destination_hash: *link_id, + })); + } + + fn send_link_packet_proof( + transport_tx: &mpsc::Sender, + link_id: &[u8; 16], + proof_data: &[u8], + context: rns_wire::context::PacketContext, + ) { + let proof_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Proof, + }, + hops: 0, + transport_id: None, + destination_hash: *link_id, + context, + }; + let mut proof_raw = proof_header.pack(); + proof_raw.extend_from_slice(proof_data); + let _ = transport_tx.try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(proof_raw), + destination_hash: *link_id, + })); + } + + fn resend_channel_data( + transport_tx: &mpsc::Sender, + link_id: &[u8; 16], + sequence: u16, + data: &[u8], + ) -> ([u8; 32], usize) { + let channel_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: *link_id, + context: rns_wire::context::PacketContext::Channel, + }; + let mut raw = channel_header.pack(); + raw.extend_from_slice(data); + let packet_hash = rns_wire::hash::packet_hash(&raw, channel_header.flags.header_type); + let raw_len = raw.len(); + let _ = transport_tx.try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: *link_id, + })); + tracing::debug!( + link_id = hex::encode(link_id), + sequence, + packet_hash = hex::encode(&packet_hash[..8]), + "channel packet retransmitted" + ); + (packet_hash, raw_len) + } + + fn ensure_link_channel(active: &mut ActiveLink, link_id: [u8; 16]) -> Option<&mut LinkChannel> { + if active.channel.is_none() { + let rtt = active.link.rtt_secs(); + let keys = active.link.session_keys()?; + active.channel = Some(LinkChannel::new_encrypted(link_id, rtt, keys)); + active.link.mark_channel_created(); + } + active.channel.as_mut() + } + + fn handle_link_packet_proof(&mut self, link_id: [u8; 16], proof_data: &[u8]) { + let Some(active) = self.active_links.get_mut(&link_id) else { + return; + }; + + active.link.record_inbound(); + if proof_data.len() < 96 { + tracing::warn!( + link_id = hex::encode(link_id), + proof_len = proof_data.len(), + "short link packet proof ignored" + ); + return; + } + + let mut packet_hash = [0u8; 32]; + packet_hash.copy_from_slice(&proof_data[..32]); + if !active.link.validate_packet_proof(&packet_hash, proof_data) { + tracing::warn!( + link_id = hex::encode(link_id), + packet_hash = hex::encode(&packet_hash[..8]), + "invalid link packet proof ignored" + ); + return; + } + + let rtt = active.link.rtt_secs(); + if let Some(channel) = active.channel.as_mut() + && let Some(sequence) = channel.delivered_by_packet_hash(&packet_hash, rtt) + { + active.link.keepalive.record_proof(); + tracing::debug!( + link_id = hex::encode(link_id), + sequence, + packet_hash = hex::encode(&packet_hash[..8]), + "channel packet delivery proof accepted" + ); + } + } + + pub fn set_request_handler(&mut self, handler: F) + where + F: Fn([u8; 16], [u8; 16], Vec) -> Option> + Send + 'static, + { + self.request_handler = Some(Box::new(handler)); + } + + /// Handler that may schedule a follow-up resource transfer (rncp --fetch). + /// Takes precedence over [`Self::set_request_handler`]. + pub fn set_request_handler_ex(&mut self, handler: F) + where + F: Fn([u8; 16], [u8; 16], Vec) -> RequestOutcome + Send + 'static, + { + self.request_handler_ex = Some(Box::new(handler)); + } + + pub fn set_announce_handler(&mut self, handler: F) + where + F: FnMut() + Send + 'static, + { + self.announce_handler = Some(Box::new(handler)); + } + + pub fn set_response_channel(&mut self, tx: mpsc::Sender) { + self.response_tx = Some(tx); + } + + pub fn set_resource_completed_channel(&mut self, tx: mpsc::Sender<(Vec, [u8; 16])>) { + self.resource_completed_tx = Some(tx); + } + + pub fn set_resource_completion_channel(&mut self, tx: mpsc::Sender) { + self.resource_completion_tx = Some(tx); + } + + /// Fires when a link reaches the active state. + pub fn set_link_established_channel(&mut self, tx: mpsc::Sender<[u8; 16]>) { + self.link_established_tx = Some(tx); + } + + /// Fires on LinkIdentify before any resource ADV can race it. + pub fn set_link_identified_channel(&mut self, tx: mpsc::Sender<([u8; 16], [u8; 16])>) { + self.link_identified_tx = Some(tx); + } + + pub fn set_link_identity_gate(&mut self, gate: F) + where + F: Fn([u8; 16], [u8; 16]) -> bool + Send + 'static, + { + self.link_identity_gate = Some(Box::new(gate)); + } + + pub fn set_link_packet_channel(&mut self, tx: mpsc::Sender<(Vec, [u8; 16])>) { + self.link_packet_tx = Some(tx); + } + + pub fn set_channel_message_channel(&mut self, tx: mpsc::Sender) { + self.channel_message_tx = Some(tx); + } + + pub fn set_link_closed_channel(&mut self, tx: mpsc::Sender<[u8; 16]>) { + self.link_closed_tx = Some(tx); + } + + /// Raw destination-encrypted packets for app-level decryption (opportunistic LXMF). + pub fn set_inbound_raw_channel(&mut self, tx: mpsc::Sender>) { + self.inbound_raw_tx = Some(tx); + } + + pub fn active_link_count(&self) -> usize { + self.active_links.len() + } + + pub fn get_link(&self, link_id: &[u8; 16]) -> Option<&Link> { + self.active_links.get(link_id).map(|a| &a.link) + } + + pub fn get_link_mut(&mut self, link_id: &[u8; 16]) -> Option<&mut Link> { + self.active_links.get_mut(link_id).map(|a| &mut a.link) + } + + pub fn get_channel(&mut self, link_id: &[u8; 16]) -> Option<&mut LinkChannel> { + let active = self.active_links.get_mut(link_id)?; + Self::ensure_link_channel(active, *link_id) + } + + pub fn send_channel_message( + &mut self, + link_id: &[u8; 16], + msg: &dyn MessageBase, + ) -> Result { + let active = self + .active_links + .get(link_id) + .ok_or(ChannelSendError::LinkNotFound)?; + if !matches!(active.link.state, LinkState::Active | LinkState::Stale) { + return Err(ChannelSendError::LinkNotActive); + } + + let transport_tx = self.transport_tx.clone(); + let permit = transport_tx + .try_reserve() + .map_err(|_| ChannelSendError::TransportUnavailable)?; + + let active = self + .active_links + .get_mut(link_id) + .ok_or(ChannelSendError::LinkNotFound)?; + let prepared = Self::ensure_link_channel(active, *link_id) + .ok_or(ChannelSendError::NoSessionKeys)? + .prepare_send_tracked(msg)?; + + let channel_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: *link_id, + context: rns_wire::context::PacketContext::Channel, + }; + let mut raw = channel_header.pack(); + raw.extend_from_slice(&prepared.data); + + let packet_hash = rns_wire::hash::packet_hash(&raw, channel_header.flags.header_type); + if let Some(channel) = active.channel.as_mut() { + channel.track_outbound_packet_hash(packet_hash, prepared.sequence); + } + active.link.record_tx(raw.len()); + + permit.send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: *link_id, + })); + + Ok(ChannelSendReceipt { + link_id: *link_id, + sequence: prepared.sequence, + packet_hash, + }) + } + + pub fn process_destination_packet(&self, raw: &[u8], identity: &Identity) -> Option> { + let dest = self.destination.as_ref()?; + let (header, data_offset) = rns_wire::header::PacketHeader::unpack(raw).ok()?; + let data = &raw[data_offset..]; + let packet_type = header.flags.packet_type as u8; + + match dest.receive(packet_type, data, identity) { + Ok(Some(plaintext)) => Some(plaintext), + _ => None, + } + } + + /// Sends ADV + initial window, registers transfer so later HMU drives the rest. + pub fn start_resource_transfer( + &mut self, + link_id: &[u8; 16], + data: Vec, + auto_compress: bool, + ) -> Option<[u8; 32]> { + self.start_resource_transfer_with_metadata(link_id, data, None, auto_compress) + } + + /// As [`Self::start_resource_transfer`] but attaches msgpack metadata + /// (e.g. `{"name": "file.bin"}`). Used by rncp --fetch. + pub fn start_resource_transfer_with_metadata( + &mut self, + link_id: &[u8; 16], + data: Vec, + metadata: Option>, + auto_compress: bool, + ) -> Option<[u8; 32]> { + self.start_resource_transfer_inner( + link_id, + ResourceTransferStart { + data, + metadata, + auto_compress, + request_id: None, + is_response: false, + allow_handshake: false, + }, + ) + } + + fn start_response_resource( + &mut self, + link_id: &[u8; 16], + packed_response: Vec, + request_id: [u8; 16], + ) -> Option<[u8; 32]> { + self.start_resource_transfer_inner( + link_id, + ResourceTransferStart { + data: packed_response, + metadata: None, + auto_compress: false, + request_id: Some(request_id.to_vec()), + is_response: true, + allow_handshake: false, + }, + ) + } + + fn start_resource_transfer_inner( + &mut self, + link_id: &[u8; 16], + request: ResourceTransferStart, + ) -> Option<[u8; 32]> { + let ResourceTransferStart { + data, + metadata, + auto_compress, + request_id, + is_response, + allow_handshake, + } = request; + let active = self.active_links.get_mut(link_id)?; + let state_allows_transfer = active.link.state == LinkState::Active + || (allow_handshake && active.link.state == LinkState::Handshake); + if !state_allows_transfer { + return None; + } + + let rtt = active + .link + .rtt + .unwrap_or(std::time::Duration::from_millis(500)); + // Pre-encrypt before chunking so each part is raw ciphertext under MTU + // (matches Python Resource over a link). + let session_keys = active.link.session_keys()?; + let encrypt_fn = |plaintext: &[u8]| -> Vec { + rns_link::encryption::link_encrypt(&session_keys, plaintext) + .unwrap_or_else(|_| plaintext.to_vec()) + }; + let metadata_wire_size = metadata.as_ref().map(|m| 3 + m.len()).unwrap_or(0); + let resources = if metadata_wire_size + data.len() <= MAX_EFFICIENT_SIZE { + let mut resource = if metadata.is_some() { + rns_protocol::resource::OutboundResource::with_options( + data, + auto_compress, + metadata, + None, + Some(&encrypt_fn), + ) + .ok()? + } else { + rns_protocol::resource::OutboundResource::new( + data, + auto_compress, + Some(&encrypt_fn), + ) + .ok()? + }; + resource.flags.is_response = is_response; + resource.request_id = request_id.clone(); + vec![resource] + } else { + MultiSegmentOutbound::with_options( + data, + auto_compress, + metadata, + request_id.clone(), + is_response, + Some(&encrypt_fn), + ) + .ok()? + .segments + }; + + let resource_key = resources + .first() + .map(|r| r.original_hash.unwrap_or(r.resource_hash))?; + + let mut transfers: VecDeque = resources + .into_iter() + .map(|resource| OutboundTransfer::from_prebuilt(resource, rtt)) + .collect(); + let first = transfers.pop_front()?; + Self::start_outbound_transfer(&self.transport_tx, active, link_id, first)?; + if !transfers.is_empty() { + active.outbound_split_queues.insert(resource_key, transfers); + } + + Some(resource_key) + } + + fn start_outbound_transfer( + transport_tx: &mpsc::Sender, + active: &mut ActiveLink, + link_id: &[u8; 16], + mut transfer: OutboundTransfer, + ) -> Option<[u8; 32]> { + let action = transfer.tick(); + let adv_data = match action { + TransferAction::SendAdvertisement(adv) => adv, + _ => return None, + }; + + let resource_hash = transfer.resource.resource_hash; + let encrypted = active.link.encrypt(&adv_data).ok()?; + let adv_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: *link_id, + context: rns_wire::context::PacketContext::ResourceAdv, + }; + let mut raw = adv_header.pack(); + raw.extend_from_slice(&encrypted); + active.link.record_tx(raw.len()); + let _ = transport_tx.try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: *link_id, + })); + + active.outbound_resources.insert(resource_hash, transfer); + tracing::debug!( + link_id = hex::encode(link_id), + resource = hex::encode(&resource_hash[..8]), + "outbound resource transfer started" + ); + Some(resource_hash) + } + + pub fn complete_resource( + &mut self, + link_id: &[u8; 16], + resource_hash: &[u8; 32], + ) -> Option<(Vec, Vec)> { + let active = self.active_links.get_mut(link_id)?; + let transfer = active.inbound_resources.get_mut(resource_hash)?; + match transfer.complete(None) { + Ok((data, proof)) => { + active.link.untrack_resource(resource_hash); + active.inbound_resources.remove(resource_hash); + Some((data, proof)) + } + Err(_) => None, + } + } +} + +fn clone_identity(identity: &Identity) -> Option { + let private_key = identity.get_private_key()?; + Identity::from_private_key(&*private_key).ok() +} + +fn unix_now() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64() +} + +pub fn register_destination( + transport_tx: &mpsc::Sender, + dest_hash: [u8; 16], + app_name: &str, +) -> mpsc::Receiver { + let (tx, rx) = mpsc::channel(256); + if let Err(e) = transport_tx.try_send(TransportMessage::RegisterDestination { + hash: dest_hash, + app_name: app_name.to_string(), + delivery_tx: Some(tx), + }) { + tracing::warn!(dest = hex::encode(dest_hash), err = %e, + "failed to register destination with transport; packets will not be delivered"); + } + rx +} + +#[cfg(test)] +mod tests { + use super::*; + + const TEST_CHANNEL_MSG_TYPE: u16 = 0x1234; + + struct TestChannelNoop; + + impl rns_protocol::channel_message::MessageBase for TestChannelNoop { + fn msg_type(&self) -> u16 { + TEST_CHANNEL_MSG_TYPE + } + + fn pack(&self) -> Vec { + Vec::new() + } + + fn unpack( + &mut self, + _raw: &[u8], + ) -> Result<(), rns_protocol::channel_message::ChannelMessageError> { + Ok(()) + } + } + + #[test] + fn test_link_manager_creation() { + let (tx, _rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let lm = LinkManager::new(tx, event_rx, [0xAA; 16], None); + assert_eq!(lm.active_link_count(), 0); + } + + #[tokio::test] + async fn test_register_destination_channel() { + let (actor, tx) = rns_transport::actor::TransportActor::new(); + tokio::spawn(actor.run()); + + let dest_hash = [0xAA; 16]; + let _rx = register_destination(&tx, dest_hash, "test.app"); + + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + + let _ = tx.send(TransportMessage::Shutdown).await; + } + + #[test] + fn test_link_manager_handles_link_closed() { + let (tx, mut rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(tx, event_rx, [0xCC; 16], None); + let (closed_tx, mut closed_rx) = mpsc::channel(1); + lm.set_link_closed_channel(closed_tx); + + let identity_key = Ed25519PrivateKey::generate(); + let dest_hash = [0xCC; 16]; + let (link, _proof) = rns_link::link::Link::new_initiator(dest_hash, 1); + let link_id = link.link_id; + + lm.active_links.insert( + link_id, + ActiveLink { + link, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + assert_eq!(lm.active_link_count(), 1); + + lm.handle_event(DestinationEvent::LinkClosed { link_id }); + assert_eq!(lm.active_link_count(), 0); + assert_eq!(closed_rx.try_recv().unwrap(), link_id); + assert!( + matches!( + rx.try_recv().unwrap(), + TransportMessage::DeregisterDestination { hash } if hash == link_id + ), + "link manager must deregister closed link destination" + ); + + let _ = identity_key; + } + + #[test] + fn remote_link_close_runs_full_cleanup() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + + let dest_hash = [0xD0; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut responder, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + let rtt_data = initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + responder.receive_rtt_packet(&rtt_data).unwrap(); + let link_id = responder.link_id; + + let callback_fired = Arc::new(AtomicBool::new(false)); + let callback_fired_clone = Arc::clone(&callback_fired); + responder.set_link_closed_callback(move |link| { + assert_eq!(link.state, LinkState::Closed); + callback_fired_clone.store(true, Ordering::SeqCst); + }); + + let close_body = initiator.teardown(CloseReason::InitiatorClosed).unwrap(); + let close_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::LinkClose, + }; + let mut close_raw = close_header.pack(); + close_raw.extend_from_slice(&close_body); + + let (transport_tx, mut transport_rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, dest_hash, None); + let (closed_tx, mut closed_rx) = mpsc::channel(1); + lm.set_link_closed_channel(closed_tx); + lm.backchannel_links.insert([0xAB; 16], link_id); + lm.link_identities + .lock() + .unwrap() + .insert(link_id, [0xAB; 16]); + lm.active_links.insert( + link_id, + ActiveLink { + link: responder, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + lm.handle_inbound_packet(&close_raw, 1); + + assert_eq!(lm.active_link_count(), 0); + assert!(callback_fired.load(Ordering::SeqCst)); + assert_eq!(closed_rx.try_recv().unwrap(), link_id); + assert!(lm.backchannel_links.is_empty()); + assert!(lm.link_identities.lock().unwrap().get(&link_id).is_none()); + assert!( + matches!( + transport_rx.try_recv().unwrap(), + TransportMessage::DeregisterDestination { hash } if hash == link_id + ), + "verified remote close must deregister link destination" + ); + } + + #[test] + fn try_step_processes_queued_destination_event_without_consuming_manager() { + let (tx, _rx) = mpsc::channel(16); + let (event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(tx, event_rx, [0xCE; 16], None); + + let dest_hash = [0xCE; 16]; + let (link, _proof) = rns_link::link::Link::new_initiator(dest_hash, 1); + let link_id = link.link_id; + lm.active_links.insert( + link_id, + ActiveLink { + link, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + event_tx + .try_send(DestinationEvent::LinkClosed { link_id }) + .unwrap(); + + assert!(lm.try_step()); + assert_eq!(lm.active_link_count(), 0); + assert!(!lm.try_step()); + } + + #[test] + fn test_link_request_without_identity_rejected() { + let (tx, _rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(tx, event_rx, [0xDD; 16], None); + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::LinkRequest, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: [0xDD; 16], + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xAA; 67]); + + lm.handle_link_request(&raw, 1); + + assert_eq!(lm.active_link_count(), 0); + } + + #[test] + fn test_with_destination_constructor() { + let (tx, _rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + + let identity = Identity::new(); + let signing_key = identity.get_signing_key().unwrap(); + + let lm = LinkManager::with_destination(tx, event_rx, &identity, "test.app", signing_key); + + assert!(lm.destination.is_some()); + assert_eq!(lm.active_link_count(), 0); + } + + #[test] + fn path_response_announce_request_sends_attached_path_response() { + let (tx, mut rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + + let identity = Identity::new(); + let signing_key = identity.get_signing_key().unwrap(); + let mut lm = + LinkManager::with_destination(tx, event_rx, &identity, "test.app", signing_key); + + let tag = vec![0xA5; 16]; + lm.handle_event(DestinationEvent::AnnounceRequested(AnnounceRequest { + app_name: "test.app".to_string(), + path_response: true, + tag: Some(tag.clone()), + attached_interface: Some(7), + })); + + let first = rx + .try_recv() + .expect("path response announce should be queued"); + let TransportMessage::OutboundAttached { + request, + interface_id, + } = first + else { + panic!("expected attached outbound path response"); + }; + assert_eq!(interface_id, 7); + let first_raw = request.raw.clone(); + let (header, _offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + assert_eq!(header.destination_hash, lm.destination_hash); + assert_eq!( + header.context, + rns_wire::context::PacketContext::PathResponse + ); + assert_eq!( + header.flags.header_type, + rns_wire::flags::HeaderType::Header1 + ); + + lm.handle_event(DestinationEvent::AnnounceRequested(AnnounceRequest { + app_name: "test.app".to_string(), + path_response: true, + tag: Some(tag), + attached_interface: Some(7), + })); + + let second = rx + .try_recv() + .expect("cached path response announce should be queued"); + let TransportMessage::OutboundAttached { + request: second_request, + interface_id: second_interface_id, + } = second + else { + panic!("expected attached outbound path response"); + }; + assert_eq!(second_interface_id, 7); + assert_eq!( + second_request.raw, first_raw, + "same path-response tag should reuse cached announce bytes" + ); + } + + #[test] + fn link_established_channel_fires_when_responder_activates() { + let dest_hash = [0x35; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (responder, proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + let rtt_data = initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .unwrap(); + let link_id = responder.link_id; + + let (transport_tx, _transport_rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, dest_hash, None); + let (established_tx, mut established_rx) = mpsc::channel(1); + lm.set_link_established_channel(established_tx); + lm.active_links.insert( + link_id, + ActiveLink { + link: responder, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Lrrtt, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&rtt_data); + + lm.handle_inbound_packet(&raw, 1); + + assert_eq!(established_rx.try_recv().unwrap(), link_id); + assert_eq!(lm.get_link(&link_id).unwrap().state, LinkState::Active); + } + + #[test] + fn request_resource_transfer_can_start_before_responder_lrrtt_activation() { + let dest_hash = [0x36; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let (_initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (responder, _proof_data) = + Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap(); + let link_id = responder.link_id; + assert_eq!(responder.state, LinkState::Handshake); + + let (transport_tx, mut transport_rx) = mpsc::channel(64); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, dest_hash, None); + + lm.active_links.insert( + link_id, + ActiveLink { + link: responder, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + assert!( + lm.start_resource_transfer(&link_id, b"direct".to_vec(), false) + .is_none(), + "ordinary callers still require an active link" + ); + + let resource_hash = lm + .start_resource_transfer_inner( + &link_id, + ResourceTransferStart { + data: b"fetch-response".to_vec(), + metadata: None, + auto_compress: false, + request_id: None, + is_response: false, + allow_handshake: true, + }, + ) + .expect("request-triggered resource can start during handshake"); + + let outbound = transport_rx.try_recv().expect("resource adv queued"); + let TransportMessage::Outbound(request) = outbound else { + panic!("expected outbound resource advertisement"); + }; + let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + assert_eq!(header.destination_hash, link_id); + assert_eq!( + header.context, + rns_wire::context::PacketContext::ResourceAdv + ); + + assert!( + lm.active_links + .get(&link_id) + .unwrap() + .outbound_resources + .contains_key(&resource_hash) + ); + } + + #[test] + fn test_destination_link_acceptance_gating() { + let (tx, _transport_rx) = mpsc::channel(64); + let (_event_tx, event_rx) = mpsc::channel(16); + + let identity = Identity::new(); + let signing_key = identity.get_signing_key().unwrap(); + + let mut lm = + LinkManager::with_destination(tx, event_rx, &identity, "test.gate", signing_key); + + if let Some(ref mut dest) = lm.destination { + dest.set_accepts_links(false); + } + + let dest_hash = lm.destination_hash; + let (_initiator, request_data) = Link::new_initiator(dest_hash, 1); + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::LinkRequest, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&request_data); + + lm.handle_link_request(&raw, 1); + + assert_eq!(lm.active_link_count(), 0); + } + + /// Drives a full handshake; returns both ends `Active` with matching keys. + fn handshaken_link_pair_with_identity() -> (Link, Link, Ed25519PrivateKey) { + let dest_hash = [0x77u8; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut responder, proof_data) = + rns_link::link::Link::new_responder(&request_data, &identity_key, dest_hash, 1) + .expect("responder"); + let rtt_data = initiator + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .expect("validate proof"); + responder + .receive_rtt_packet(&rtt_data) + .expect("receive rtt"); + assert_eq!(initiator.state, LinkState::Active); + assert_eq!(responder.state, LinkState::Active); + (initiator, responder, identity_key) + } + + /// Drives a full handshake; returns both ends `Active` with matching keys. + fn handshaken_link_pair() -> (Link, Link) { + let (initiator, responder, _identity_key) = handshaken_link_pair_with_identity(); + (initiator, responder) + } + + #[test] + fn channel_packet_is_proved_and_dispatched() { + let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity(); + let link_id = receiver_link.link_id; + let receiver_rtt = receiver_link.rtt_secs(); + let receiver_keys = receiver_link.session_keys().unwrap(); + let mut sender_channel = rns_protocol::channel::LinkChannel::new_encrypted( + link_id, + sender_link.rtt_secs(), + sender_link.session_keys().unwrap(), + ); + let payload = sender_channel.prepare_send(&TestChannelNoop).unwrap(); + + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Channel, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type); + + let (transport_tx, mut transport_rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, [0xBB; 16], None); + let (channel_tx, mut channel_rx) = mpsc::channel(4); + lm.set_channel_message_channel(channel_tx); + lm.active_links.insert( + link_id, + ActiveLink { + link: receiver_link, + _interface_id: 1, + channel: Some(rns_protocol::channel::LinkChannel::new_encrypted( + link_id, + receiver_rtt, + receiver_keys, + )), + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + lm.handle_inbound_packet(&raw, 1); + + let delivered = channel_rx.try_recv().expect("channel message dispatched"); + assert_eq!(delivered.link_id, link_id); + assert_eq!(delivered.msg_type, TEST_CHANNEL_MSG_TYPE); + assert!(delivered.payload.is_empty()); + + let outbound = transport_rx.try_recv().expect("channel proof queued"); + let TransportMessage::Outbound(request) = outbound else { + panic!("expected outbound proof"); + }; + let (proof_header, proof_offset) = + rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + assert_eq!(proof_header.destination_hash, link_id); + assert_eq!( + proof_header.flags.packet_type, + rns_wire::flags::PacketType::Proof + ); + assert_eq!(proof_header.context, rns_wire::context::PacketContext::None); + let proof_data = &request.raw[proof_offset..]; + assert_eq!(&proof_data[..32], &packet_hash); + assert!(sender_link.validate_packet_proof(&packet_hash, proof_data)); + } + + #[test] + fn channel_packet_opens_channel_before_proof_and_dispatch() { + let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity(); + let link_id = receiver_link.link_id; + let mut sender_channel = rns_protocol::channel::LinkChannel::new_encrypted( + link_id, + sender_link.rtt_secs(), + sender_link.session_keys().unwrap(), + ); + let payload = sender_channel.prepare_send(&TestChannelNoop).unwrap(); + + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Channel, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + + let (transport_tx, mut transport_rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, [0xBD; 16], None); + let (channel_tx, mut channel_rx) = mpsc::channel(4); + lm.set_channel_message_channel(channel_tx); + lm.active_links.insert( + link_id, + ActiveLink { + link: receiver_link, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + lm.handle_inbound_packet(&raw, 1); + + let delivered = channel_rx.try_recv().expect("channel message dispatched"); + assert_eq!(delivered.link_id, link_id); + assert_eq!(delivered.msg_type, TEST_CHANNEL_MSG_TYPE); + let outbound = transport_rx.try_recv().expect("channel proof queued"); + assert!(matches!(outbound, TransportMessage::Outbound(_))); + assert!(lm.active_links.get(&link_id).unwrap().channel.is_some()); + } + + #[test] + fn channel_packet_before_active_link_is_not_proved_or_dispatched() { + let dest_hash = [0x78u8; 16]; + let identity_key = Ed25519PrivateKey::generate(); + let identity_pub = identity_key.public_key(); + let (mut sender_link, request_data) = Link::new_initiator(dest_hash, 1); + let (receiver_link, proof_data) = + rns_link::link::Link::new_responder(&request_data, &identity_key, dest_hash, 1) + .expect("responder"); + let _rtt_data = sender_link + .validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes()) + .expect("validate proof"); + assert_eq!(sender_link.state, LinkState::Active); + assert_eq!(receiver_link.state, LinkState::Handshake); + + let link_id = receiver_link.link_id; + let receiver_keys = receiver_link.session_keys().unwrap(); + let mut sender_channel = rns_protocol::channel::LinkChannel::new_encrypted( + link_id, + sender_link.rtt_secs(), + sender_link.session_keys().unwrap(), + ); + let payload = sender_channel.prepare_send(&TestChannelNoop).unwrap(); + + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Channel, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + + let (transport_tx, mut transport_rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, [0xBE; 16], None); + let (channel_tx, mut channel_rx) = mpsc::channel(4); + lm.set_channel_message_channel(channel_tx); + lm.active_links.insert( + link_id, + ActiveLink { + link: receiver_link, + _interface_id: 1, + channel: Some(rns_protocol::channel::LinkChannel::new_encrypted( + link_id, + 0.0, + receiver_keys, + )), + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + lm.handle_inbound_packet(&raw, 1); + + assert!(channel_rx.try_recv().is_err()); + assert!(transport_rx.try_recv().is_err()); + assert!( + lm.active_links + .get(&link_id) + .unwrap() + .channel + .as_ref() + .unwrap() + .is_ready_to_send() + ); + } + + #[test] + fn link_packet_proof_marks_channel_sequence_delivered() { + let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity(); + let link_id = sender_link.link_id; + + let (transport_tx, mut transport_rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, [0xBC; 16], None); + lm.active_links.insert( + link_id, + ActiveLink { + link: sender_link, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + let receipt = lm + .send_channel_message(&link_id, &TestChannelNoop) + .expect("channel message sent"); + assert_eq!(receipt.sequence, 0); + + let outbound = transport_rx.try_recv().expect("channel packet queued"); + let TransportMessage::Outbound(request) = outbound else { + panic!("expected outbound channel packet"); + }; + let (sent_header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + assert_eq!( + sent_header.context, + rns_wire::context::PacketContext::Channel + ); + assert_eq!( + receipt.packet_hash, + rns_wire::hash::packet_hash(&request.raw, sent_header.flags.header_type) + ); + assert_eq!(lm.get_channel(&link_id).unwrap().outstanding_count(), 1); + + let proof_data = receiver_link + .prove_packet_with_link_key(&receipt.packet_hash) + .unwrap(); + let proof_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 proof_raw = proof_header.pack(); + proof_raw.extend_from_slice(&proof_data); + + lm.handle_inbound_packet(&proof_raw, 1); + + assert_eq!(lm.get_channel(&link_id).unwrap().outstanding_count(), 0); + assert!(lm.get_channel(&link_id).unwrap().is_ready_to_send()); + } + + #[test] + fn unmatched_valid_link_packet_proof_does_not_record_keepalive_proof() { + let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity(); + let link_id = sender_link.link_id; + + let (transport_tx, _transport_rx) = mpsc::channel(16); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, [0xBF; 16], None); + lm.active_links.insert( + link_id, + ActiveLink { + link: sender_link, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + let packet_hash = [0x5Au8; 32]; + let proof_data = receiver_link + .prove_packet_with_link_key(&packet_hash) + .expect("valid link-key proof"); + let proof_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 proof_raw = proof_header.pack(); + proof_raw.extend_from_slice(&proof_data); + + assert!( + lm.active_links + .get(&link_id) + .unwrap() + .link + .keepalive + .last_proof + .is_none() + ); + lm.handle_inbound_packet(&proof_raw, 1); + assert!( + lm.active_links + .get(&link_id) + .unwrap() + .link + .keepalive + .last_proof + .is_none() + ); + } + + /// Receive-side split-resource reassembly: two manually-marked segments + /// produce one `ResourceCompletion` keyed by `original_hash`. Synthesizing + /// segments avoids the >2000 parts that `MultiSegmentOutbound` would emit; + /// rncp_interop covers realistic sizes via the full HMU loop. + #[tokio::test(flavor = "current_thread")] + async fn test_split_resource_inbound_reassembles_via_coordinator() { + use rns_protocol::resource::{OutboundResource, OutboundTransfer, TransferAction}; + + let (sender_link, receiver_link) = handshaken_link_pair(); + let link_id = receiver_link.link_id; + + let (transport_tx, mut transport_rx) = mpsc::channel(4096); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, [0xBB; 16], None); + + let (completion_tx, mut completion_rx) = mpsc::channel(8); + lm.set_resource_completion_channel(completion_tx); + let (legacy_tx, mut legacy_rx) = mpsc::channel(8); + lm.set_resource_completed_channel(legacy_tx); + + lm.active_links.insert( + link_id, + ActiveLink { + link: receiver_link, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + // Two 8 KiB chunks; ~20 parts each fit in the ADV's initial hashmap + // (~70 entries) so no HMU round-trip is needed. + let chunk_size = 8 * 1024; + let chunk_a: Vec = (0..chunk_size).map(|i| (i % 251) as u8).collect(); + let chunk_b: Vec = (0..chunk_size).map(|i| ((i + 7) % 251) as u8).collect(); + let payload: Vec = chunk_a.iter().chain(chunk_b.iter()).copied().collect(); + + // `original_hash` is just the coordinator HashMap key; per-segment + // hashes enforce integrity. + let original_hash: [u8; 32] = [0x5A; 32]; + + let chunks = [chunk_a, chunk_b]; + let total_segments = chunks.len(); + + let encrypt_fn = |d: &[u8]| sender_link.encrypt(d).expect("link encrypt"); + let rtt = std::time::Duration::from_millis(50); + + for (i, chunk) in chunks.into_iter().enumerate() { + let mut segment = + OutboundResource::with_options(chunk, false, None, None, Some(&encrypt_fn)) + .expect("build segment"); + // Stamp split metadata so the ADV carries total_segments / segment_index / original_hash. + segment.flags.split = true; + segment.segment_index = i + 1; + segment.total_segments = total_segments; + segment.original_hash = Some(original_hash); + + let mut transfer = OutboundTransfer::from_prebuilt(segment, rtt); + let action = transfer.tick(); + let adv_bytes = match action { + TransferAction::SendAdvertisement(b) => b, + other => panic!("expected SendAdvertisement, got {other:?}"), + }; + + let encrypted_adv = sender_link.encrypt(&adv_bytes).expect("encrypt adv"); + let adv_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::ResourceAdv, + }; + let mut adv_raw = adv_header.pack(); + adv_raw.extend_from_slice(&encrypted_adv); + lm.handle_inbound_packet(&adv_raw, 1); + + // Widen the receiver's WINDOW_INITIAL=4 so the blast fits in one shot. + let segment_rh = transfer.resource.resource_hash; + let total_parts = transfer.resource.parts.len(); + if let Some(active) = lm.active_links.get_mut(&link_id) + && let Some(in_transfer) = active.inbound_resources.get_mut(&segment_rh) + { + in_transfer.resource.window.window = total_parts; + in_transfer.outstanding_parts = total_parts; + } + + for part in &transfer.resource.parts { + let part_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Resource, + }; + let mut part_raw = part_header.pack(); + part_raw.extend_from_slice(part); + lm.handle_inbound_packet(&part_raw, 1); + } + } + + // Drain the queued ResourceReq / ResourcePrf so the channel isn't pinned. + while transport_rx.try_recv().is_ok() {} + + let completion = completion_rx + .try_recv() + .expect("expected exactly one ResourceCompletion"); + assert_eq!( + completion.resource_hash, original_hash, + "completion must surface original_hash, not a per-segment hash" + ); + assert_eq!(completion.link_id, link_id); + assert_eq!(completion.data, payload, "reassembled bytes match input"); + assert!( + completion_rx.try_recv().is_err(), + "no per-segment completion events should fire for a split resource" + ); + + let (legacy_data, legacy_link) = legacy_rx + .try_recv() + .expect("legacy channel must also fire once"); + assert_eq!(legacy_link, link_id); + assert_eq!( + legacy_data, payload, + "legacy callback receives reassembled blob, not per-segment chunks" + ); + assert!( + legacy_rx.try_recv().is_err(), + "legacy channel must also collapse to one event per original" + ); + + // Coordinator + routing entries cleaned up after success. + let active = lm.active_links.get(&link_id).unwrap(); + assert!( + active.inbound_split_resources.is_empty(), + "coordinator must be removed after reassembly completes" + ); + assert!( + active.segment_routing.is_empty(), + "routing entries must be removed after each segment completes" + ); + assert!( + active.inbound_resources.is_empty(), + "per-segment transfers must be removed after each segment completes" + ); + } + + /// MAX_SEGMENTS cap: oversized `total_segments` is rejected without + /// allocating a coordinator (would OOM `Vec` otherwise). + #[tokio::test(flavor = "current_thread")] + async fn test_split_resource_rejects_oversized_total_segments() { + use rns_protocol::resource::{MAX_SEGMENTS, ResourceFlags}; + use rns_protocol::resource_adv::ResourceAdvertisement; + + let (sender_link, receiver_link) = handshaken_link_pair(); + let link_id = receiver_link.link_id; + + let (transport_tx, mut _transport_rx) = mpsc::channel(64); + let (_event_tx, event_rx) = mpsc::channel(16); + let mut lm = LinkManager::new(transport_tx, event_rx, [0xCC; 16], None); + lm.active_links.insert( + link_id, + ActiveLink { + link: receiver_link, + _interface_id: 1, + channel: None, + inbound_resources: HashMap::new(), + outbound_resources: HashMap::new(), + outbound_split_queues: HashMap::new(), + inbound_split_resources: HashMap::new(), + segment_routing: HashMap::new(), + }, + ); + + let evil_total = MAX_SEGMENTS + 1; + let mut adv = ResourceAdvertisement::with_metadata_size( + 64, + 32, + 1, + [0x42; 32], + vec![0x11; 4], + ResourceFlags { + split: true, + ..Default::default() + }, + &[], + rns_wire::constants::ENCRYPTED_MDU, + 0, + ); + adv.original_hash = [0x99; 32]; + adv.segment_index = 1; + adv.total_segments = evil_total; + + let adv_bytes = adv.pack(); + let encrypted = sender_link.encrypt(&adv_bytes).expect("encrypt"); + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::ResourceAdv, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&encrypted); + lm.handle_inbound_packet(&raw, 1); + + let active = lm.active_links.get(&link_id).expect("link still present"); + assert!( + active.inbound_split_resources.is_empty(), + "no coordinator must be allocated for an over-cap total_segments" + ); + assert!( + active.segment_routing.is_empty(), + "no routing must be inserted for a rejected ADV" + ); + assert!( + active.inbound_resources.is_empty(), + "no per-segment transfer must be opened for a rejected ADV" + ); + } + + #[test] + fn test_real_link_request_handshake() { + let (tx, mut transport_rx) = mpsc::channel(64); + let (_event_tx, event_rx) = mpsc::channel(16); + + let identity_key = Ed25519PrivateKey::generate(); + let dest_hash = [0xEE; 16]; + let mut lm = LinkManager::new(tx, event_rx, dest_hash, Some(identity_key)); + + let (initiator_link, request_data) = Link::new_initiator(dest_hash, 1); + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::LinkRequest, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&request_data); + + lm.handle_link_request(&raw, 1); + + assert_eq!(lm.active_link_count(), 1); + let link_id = initiator_link.link_id; + let active = lm.get_link(&link_id).unwrap(); + assert_eq!(active.state, LinkState::Handshake); + + let outbound = transport_rx.try_recv(); + assert!( + outbound.is_ok(), + "proof packet should be queued for sending" + ); + } +} diff --git a/crates/rns-runtime/src/platform.rs b/crates/rns-runtime/src/platform.rs new file mode 100644 index 0000000..8510b4a --- /dev/null +++ b/crates/rns-runtime/src/platform.rs @@ -0,0 +1,173 @@ +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Platform { + Linux, + MacOS, + Windows, + Android, + Other, +} + +impl Platform { + pub fn current() -> Self { + if cfg!(target_os = "android") { + Platform::Android + } else if cfg!(target_os = "linux") { + Platform::Linux + } else if cfg!(target_os = "macos") { + Platform::MacOS + } else if cfg!(target_os = "windows") { + Platform::Windows + } else { + Platform::Other + } + } + + pub fn has_unix_sockets(&self) -> bool { + matches!(self, Platform::Linux | Platform::MacOS | Platform::Android) + } + + pub fn config_dir(&self) -> PathBuf { + match self { + Platform::Windows => { + if let Ok(appdata) = std::env::var("APPDATA") { + PathBuf::from(appdata).join("rsReticulum") + } else { + PathBuf::from(".rsReticulum") + } + } + Platform::Android => { + // Android has no user HOME; callers must pass an explicit configdir. + tracing::warn!( + "Platform::config_dir() called on Android without explicit configdir" + ); + PathBuf::from("/data/local/tmp/.rsReticulum") + } + _ => { + if let Ok(home) = std::env::var("HOME") { + PathBuf::from(home).join(".rsReticulum") + } else { + PathBuf::from(".rsReticulum") + } + } + } + } + + pub fn display_name(&self) -> &'static str { + match self { + Platform::Linux => "linux", + Platform::MacOS => "darwin", + Platform::Windows => "win32", + Platform::Android => "android", + Platform::Other => "unknown", + } + } +} + +/// Explicit `configdir` wins. Without one, use rsReticulum-specific defaults: +/// `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then +/// `~/.rsReticulum` on Unix-like systems. Windows uses the appdata +/// `rsReticulum` directory. Pass `--config ~/.reticulum` explicitly when +/// intentionally sharing a Python Reticulum config. +pub fn resolve_config_dir(configdir: Option<&str>) -> PathBuf { + match configdir { + Some(dir) => PathBuf::from(dir), + None => { + let platform = Platform::current(); + if !matches!(platform, Platform::Windows | Platform::Android) { + let etc = PathBuf::from("/etc/rsReticulum"); + if etc.join("config").is_file() { + return etc; + } + if let Ok(home) = std::env::var("HOME") { + let xdg = PathBuf::from(home).join(".config/rsReticulum"); + if xdg.join("config").is_file() { + return xdg; + } + } + } + platform.config_dir() + } + } +} + +pub struct StoragePaths { + pub config_dir: PathBuf, + pub interface_dir: PathBuf, + pub storage_dir: PathBuf, + pub cache_dir: PathBuf, + pub resource_dir: PathBuf, + pub identity_dir: PathBuf, + pub blackhole_dir: PathBuf, + pub announce_cache_dir: PathBuf, +} + +impl StoragePaths { + pub fn from_config_dir(config_dir: &Path) -> Self { + let storage_dir = config_dir.join("storage"); + let cache_dir = storage_dir.join("cache"); + Self { + config_dir: config_dir.to_path_buf(), + interface_dir: config_dir.join("interfaces"), + storage_dir: storage_dir.clone(), + cache_dir: cache_dir.clone(), + resource_dir: storage_dir.join("resources"), + identity_dir: storage_dir.join("identities"), + blackhole_dir: storage_dir.join("blackhole"), + announce_cache_dir: cache_dir.join("announces"), + } + } + + pub fn ensure_dirs(&self) -> std::io::Result<()> { + std::fs::create_dir_all(&self.config_dir)?; + std::fs::create_dir_all(&self.interface_dir)?; + std::fs::create_dir_all(&self.storage_dir)?; + std::fs::create_dir_all(&self.cache_dir)?; + std::fs::create_dir_all(&self.resource_dir)?; + std::fs::create_dir_all(&self.identity_dir)?; + std::fs::create_dir_all(&self.blackhole_dir)?; + std::fs::create_dir_all(&self.announce_cache_dir)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_platform_detection() { + let platform = Platform::current(); + let _ = platform.display_name(); + let _ = platform.has_unix_sockets(); + let _ = platform.config_dir(); + } + + #[test] + fn test_explicit_config_dir() { + let dir = resolve_config_dir(Some("/tmp/test_reticulum")); + assert_eq!(dir, PathBuf::from("/tmp/test_reticulum")); + } + + #[test] + fn test_platform_config_dir_uses_rust_branded_name() { + let dir = Platform::current().config_dir(); + assert!( + dir.ends_with("rsReticulum") + || dir.ends_with(".rsReticulum") + || dir.ends_with("/data/local/tmp/.rsReticulum") + ); + } + + #[test] + fn test_storage_paths() { + let config_dir = PathBuf::from("/tmp/test_config"); + let paths = StoragePaths::from_config_dir(&config_dir); + assert_eq!(paths.interface_dir, config_dir.join("interfaces")); + assert_eq!(paths.storage_dir, config_dir.join("storage")); + assert_eq!(paths.cache_dir, config_dir.join("storage/cache")); + assert_eq!(paths.resource_dir, config_dir.join("storage/resources")); + assert_eq!(paths.identity_dir, config_dir.join("storage/identities")); + } +} diff --git a/crates/rns-runtime/src/probe.rs b/crates/rns-runtime/src/probe.rs new file mode 100644 index 0000000..730389a --- /dev/null +++ b/crates/rns-runtime/src/probe.rs @@ -0,0 +1,602 @@ +//! Wire-compatible with Python `rnprobe.py`. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use thiserror::Error; +use tokio::sync::{Mutex, mpsc, oneshot}; +use tokio::time::timeout; + +use rns_identity::destination::{DestType, Destination, Direction, ProofStrategy}; +use rns_identity::identity::Identity; +use rns_transport::link_messages::DestinationEvent; +use rns_transport::messages::{ + AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse, +}; +use rns_wire::constants::MTU; +use rns_wire::context::PacketContext; +use rns_wire::flags::{DestinationType, HeaderType, PacketFlags, PacketType, TransportType}; +use rns_wire::hash::packet_hash_pair; +use rns_wire::header::PacketHeader; + +#[derive(Debug, Error)] +pub enum ProbeError { + #[error("timed out waiting for path to destination")] + PathTimeout, + #[error("probe size {0} exceeds MTU {1}")] + MtuExceeded(usize, usize), + #[error("timed out waiting for proof")] + PacketTimeout, + #[error("encryption failed: {0}")] + EncryptError(String), + #[error("destination's identity is not in the local announce cache")] + NoIdentity, + #[error("transport channel closed")] + TransportClosed, + #[error("invalid destination name")] + InvalidName, + #[error("internal error: {0}")] + Internal(String), +} + +#[derive(Debug, Clone)] +pub struct ProbeOutcome { + pub rtt: Duration, + /// 0 for direct. + pub hops: u8, + pub via: Option<[u8; 16]>, + pub interface: Option, + pub destination_hash: [u8; 16], +} + +/// Signs every inbound DATA with a PROOF (Python `PROVE_ALL`). Callers must +/// persist `identity` (canonical `/probe_identity`) for a stable +/// destination hash across restarts. +pub async fn spawn_probe_responder( + transport_tx: mpsc::Sender, + identity: Identity, + app_name: &str, +) -> Result<[u8; 16], ProbeError> { + let mut dest = Destination::new(Some(&identity), Direction::In, DestType::Single, app_name) + .map_err(|e| ProbeError::Internal(format!("destination: {e}")))?; + dest.set_proof_strategy(ProofStrategy::ProveAll); + let dest_hash = dest.hash; + + let (event_tx, mut event_rx) = mpsc::channel::(64); + + transport_tx + .send(TransportMessage::RegisterDestination { + hash: dest_hash, + app_name: app_name.to_string(), + delivery_tx: Some(event_tx), + }) + .await + .map_err(|_| ProbeError::TransportClosed)?; + + let identity = Arc::new(identity); + // Implicit proof is Python's default (`use_implicit_proof = Yes`). + let implicit = true; + + tokio::spawn(async move { + while let Some(event) = event_rx.recv().await { + let DestinationEvent::InboundPacket { raw, .. } = event else { + continue; + }; + let (header, _) = match PacketHeader::unpack(&raw) { + Ok(h) => h, + Err(e) => { + tracing::debug!(error = %e, "probe responder: bad header"); + continue; + } + }; + if header.flags.packet_type != PacketType::Data { + continue; + } + + let (full_hash, trunc_hash) = packet_hash_pair(&raw, header.flags.header_type); + let proof_payload = match identity.prove(&full_hash, implicit) { + Ok(bytes) => bytes, + Err(e) => { + tracing::warn!(error = %e, "probe responder: sign failed"); + continue; + } + }; + + // Proof destination = truncated_packet_hash of source DATA; payload plaintext. + let proof_flags = PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Proof, + }; + let proof_header = PacketHeader { + flags: proof_flags, + hops: 0, + transport_id: None, + destination_hash: trunc_hash, + context: PacketContext::None, + }; + let mut proof_raw = proof_header.pack(); + proof_raw.extend_from_slice(&proof_payload); + + if transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(proof_raw), + destination_hash: trunc_hash, + })) + .await + .is_err() + { + tracing::debug!("probe responder: transport closed, exiting"); + break; + } + + tracing::debug!( + dest = hex::encode(dest_hash), + trunc = hex::encode(trunc_hash), + implicit, + "probe responder: sent proof" + ); + } + + tracing::debug!( + dest = hex::encode(dest_hash), + "probe responder: event loop exited" + ); + }); + + tracing::info!( + dest = %hex::encode(dest_hash), + app_name, + "probe responder registered" + ); + + Ok(dest_hash) +} + +/// Filters DeliveryProof fan-out down to this probe's `msg_id`. +struct DeliveryProofWaiter { + msg_id: String, + rx: Mutex>, + transport_tx: mpsc::Sender, + probe_dest_hash: [u8; 16], +} + +impl DeliveryProofWaiter { + async fn wait(&self, wait_for: Duration) -> Option> { + let mut rx = self.rx.lock().await; + let deadline = Instant::now() + wait_for; + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return None; + } + let ev = match timeout(remaining, rx.recv()).await { + Ok(Some(ev)) => ev, + Ok(None) => return None, + Err(_) => return None, + }; + if let DestinationEvent::DeliveryProof { msg_id, rtt } = ev + && msg_id == self.msg_id + { + return Some(rtt); + } + } + } +} + +impl Drop for DeliveryProofWaiter { + fn drop(&mut self) { + let _ = self + .transport_tx + .try_send(TransportMessage::DeregisterDestination { + hash: self.probe_dest_hash, + }); + } +} + +pub async fn probe_once( + transport_tx: mpsc::Sender, + dest_hash: [u8; 16], + app_name: &str, + size: usize, + proof_wait: Duration, + path_wait: Duration, + use_implicit_proof: bool, +) -> Result { + if size > MTU { + return Err(ProbeError::MtuExceeded(size, MTU)); + } + + let has_path = match query( + &transport_tx, + TransportQuery::GetNextHop { dest: dest_hash }, + ) + .await? + { + TransportQueryResponse::HashResult(h) => h.is_some(), + _ => false, + }; + // Local destinations have no next_hop but are still reachable. + let interface_id_resp = query( + &transport_tx, + TransportQuery::GetNextHopInterfaceId { dest: dest_hash }, + ) + .await?; + let has_interface = matches!(interface_id_resp, TransportQueryResponse::IntResult(n) if n >= 0); + + if !has_path && !has_interface { + transport_tx + .send(TransportMessage::RequestPath { + destination_hash: dest_hash, + }) + .await + .map_err(|_| ProbeError::TransportClosed)?; + + let (await_tx, await_rx) = oneshot::channel(); + transport_tx + .send(TransportMessage::AwaitPath { + dest: dest_hash, + reply: await_tx, + }) + .await + .map_err(|_| ProbeError::TransportClosed)?; + + let found = timeout(path_wait, await_rx) + .await + .map_err(|_| ProbeError::PathTimeout)? + .unwrap_or(false); + if !found { + return Err(ProbeError::PathTimeout); + } + } + + let announces = match query(&transport_tx, TransportQuery::GetRecentAnnounces).await? { + TransportQueryResponse::Announces(v) => v, + _ => Vec::new(), + }; + let pubkey = find_public_key(&announces, &dest_hash).ok_or(ProbeError::NoIdentity)?; + + let remote_identity = + Identity::from_public_key(&pubkey).map_err(|e| ProbeError::EncryptError(e.to_string()))?; + let out_dest = Destination::new( + Some(&remote_identity), + Direction::Out, + DestType::Single, + app_name, + ) + .map_err(|e| ProbeError::Internal(format!("out destination: {e}")))?; + debug_assert_eq!(out_dest.hash, dest_hash); + + let payload = rns_crypto::random::random_bytes(size); + let ciphertext = out_dest + .encrypt(&payload, &remote_identity, None) + .map_err(|e| ProbeError::EncryptError(e.to_string()))?; + + let flags = PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Data, + }; + let header = PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&ciphertext); + + if raw.len() > MTU { + return Err(ProbeError::MtuExceeded(raw.len(), MTU)); + } + + let (full_hash, trunc_hash) = packet_hash_pair(&raw, HeaderType::Header1); + + // trunc_hash keys `receipt_table`; unique msg_id filters fan-out. + let msg_id = format!( + "probe.{}.{:x}", + hex::encode(&trunc_hash[..4]), + std::process::id() + ); + transport_tx + .send(TransportMessage::RegisterReceipt { + truncated_hash: trunc_hash, + full_hash, + msg_id: msg_id.clone(), + timeout: Some(proof_wait + Duration::from_secs(1)), + }) + .await + .map_err(|_| ProbeError::TransportClosed)?; + + // Fresh identity avoids hash collision with real destinations. + let probe_listener = Destination::new(None, Direction::In, DestType::Single, "probe.client") + .map_err(|e| ProbeError::Internal(format!("listener dest: {e}")))?; + let listener_hash = probe_listener.hash; + let (ev_tx, ev_rx) = mpsc::channel::(16); + transport_tx + .send(TransportMessage::RegisterDestination { + hash: listener_hash, + app_name: "probe.client".to_string(), + delivery_tx: Some(ev_tx), + }) + .await + .map_err(|_| ProbeError::TransportClosed)?; + + let waiter = DeliveryProofWaiter { + msg_id: msg_id.clone(), + rx: Mutex::new(ev_rx), + transport_tx: transport_tx.clone(), + probe_dest_hash: listener_hash, + }; + + let path_meta = collect_path_meta(&transport_tx, dest_hash).await; + let send_instant = Instant::now(); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: dest_hash, + })) + .await + .map_err(|_| ProbeError::TransportClosed)?; + + let rtt_from_receipt = waiter + .wait(proof_wait) + .await + .ok_or(ProbeError::PacketTimeout)?; + let rtt = rtt_from_receipt.unwrap_or_else(|| send_instant.elapsed()); + + let _ = use_implicit_proof; + + Ok(ProbeOutcome { + rtt, + hops: path_meta.hops, + via: path_meta.via, + interface: path_meta.interface, + destination_hash: dest_hash, + }) +} + +pub fn parse_dest_hash(hex_str: &str) -> Result<[u8; 16], ProbeError> { + let bytes = hex::decode(hex_str.trim()).map_err(|_| ProbeError::InvalidName)?; + <[u8; 16]>::try_from(bytes.as_slice()).map_err(|_| ProbeError::InvalidName) +} + +pub fn default_probe_app_name() -> &'static str { + "rnstransport.probe" +} + +#[derive(Default)] +struct PathMeta { + hops: u8, + via: Option<[u8; 16]>, + interface: Option, +} + +async fn collect_path_meta(tx: &mpsc::Sender, dest: [u8; 16]) -> PathMeta { + let mut meta = PathMeta::default(); + if let Ok(TransportQueryResponse::PathTable(entries)) = + query(tx, TransportQuery::GetPathTable).await + && let Some(entry) = entries.into_iter().find(|e| e.hash == dest) + { + meta.hops = entry.hops; + meta.via = entry.via; + meta.interface = Some(entry.interface); + } + meta +} + +async fn query( + tx: &mpsc::Sender, + query: TransportQuery, +) -> Result { + let (resp_tx, resp_rx) = oneshot::channel(); + tx.send(TransportMessage::Rpc { + query, + response_tx: resp_tx, + }) + .await + .map_err(|_| ProbeError::TransportClosed)?; + resp_rx.await.map_err(|_| ProbeError::TransportClosed) +} + +fn find_public_key(announces: &[AnnounceRpcEntry], dest_hash: &[u8; 16]) -> Option<[u8; 64]> { + announces + .iter() + .find(|a| &a.dest_hash == dest_hash) + .and_then(|a| a.public_key) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn probe_app_name_matches_python() { + // Python: Transport.APP_NAME = "rnstransport", aspect = "probe". + assert_eq!(default_probe_app_name(), "rnstransport.probe"); + } + + #[test] + fn parse_dest_hash_valid() { + let h = parse_dest_hash("00112233445566778899aabbccddeeff").unwrap(); + assert_eq!( + h, + [ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, + 0xee, 0xff + ] + ); + } + + #[test] + fn parse_dest_hash_too_short_errors() { + assert!(parse_dest_hash("deadbeef").is_err()); + } + + #[test] + fn parse_dest_hash_non_hex_errors() { + assert!(parse_dest_hash("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz").is_err()); + } + + #[test] + fn find_public_key_returns_match() { + let entries = vec![ + AnnounceRpcEntry { + dest_hash: [0xAA; 16], + hops: 0, + app_data: None, + timestamp: 0.0, + public_key: Some([0x11; 64]), + ratchet: None, + retained: false, + }, + AnnounceRpcEntry { + dest_hash: [0xBB; 16], + hops: 1, + app_data: None, + timestamp: 0.0, + public_key: Some([0x22; 64]), + ratchet: None, + retained: false, + }, + ]; + assert_eq!(find_public_key(&entries, &[0xBB; 16]), Some([0x22; 64])); + assert_eq!(find_public_key(&entries, &[0xCC; 16]), None); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn responder_replies_to_data_with_proof() { + let (tx, mut rx) = mpsc::channel::(16); + + let identity = Identity::new(); + let identity_pub = identity.get_public_key(); + let spawn_tx = tx.clone(); + let spawn_handle = tokio::spawn(async move { + spawn_probe_responder(spawn_tx, identity, default_probe_app_name()).await + }); + + let first = rx.recv().await.expect("RegisterDestination"); + let (dest_hash_from_msg, delivery_tx) = match first { + TransportMessage::RegisterDestination { + hash, + delivery_tx: Some(dt), + .. + } => (hash, dt), + other => panic!("expected RegisterDestination, got {other:?}"), + }; + let dest_hash = spawn_handle.await.unwrap().unwrap(); + assert_eq!(dest_hash, dest_hash_from_msg); + + let flags = PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Data, + }; + let header = PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xEE; 32]); + let (expected_full, expected_trunc) = packet_hash_pair(&raw, HeaderType::Header1); + + delivery_tx + .send(DestinationEvent::InboundPacket { + raw: bytes::Bytes::from(raw), + interface_id: 0, + }) + .await + .unwrap(); + + let outbound = tokio::time::timeout(Duration::from_secs(2), rx.recv()) + .await + .expect("timed out waiting for proof") + .expect("channel closed"); + let OutboundRequest { + raw: proof_raw, + destination_hash, + } = match outbound { + TransportMessage::Outbound(r) => r, + other => panic!("expected Outbound, got {other:?}"), + }; + + assert_eq!(destination_hash, expected_trunc); + + let (proof_header, data_offset) = PacketHeader::unpack(&proof_raw).unwrap(); + assert_eq!(proof_header.flags.packet_type, PacketType::Proof); + assert_eq!(proof_header.flags.destination_type, DestinationType::Single); + assert_eq!(proof_header.flags.header_type, HeaderType::Header1); + assert_eq!(proof_header.destination_hash, expected_trunc); + + let payload = &proof_raw[data_offset..]; + assert_eq!(payload.len(), 64, "expected implicit 64-byte proof"); + + let remote = Identity::from_public_key(&identity_pub).unwrap(); + let mut sig = [0u8; 64]; + sig.copy_from_slice(payload); + assert!( + remote.verify(&expected_full, &sig), + "proof signature must verify over full packet hash" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn responder_ignores_non_data_packets() { + let (tx, mut rx) = mpsc::channel::(16); + let identity = Identity::new(); + let spawn_tx = tx.clone(); + let h = tokio::spawn(async move { + spawn_probe_responder(spawn_tx, identity, default_probe_app_name()).await + }); + let reg = rx.recv().await.unwrap(); + let delivery_tx = match reg { + TransportMessage::RegisterDestination { + delivery_tx: Some(dt), + .. + } => dt, + _ => panic!("expected RegisterDestination"), + }; + let dest_hash = h.await.unwrap().unwrap(); + + let flags = PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Announce, + }; + let header = PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xAB; 64]); + + delivery_tx + .send(DestinationEvent::InboundPacket { + raw: bytes::Bytes::from(raw), + interface_id: 0, + }) + .await + .unwrap(); + + match tokio::time::timeout(Duration::from_millis(150), rx.recv()).await { + Err(_) => (), + Ok(other) => panic!("unexpected response to non-DATA packet: {other:?}"), + } + } +} diff --git a/crates/rns-runtime/src/remote_management.rs b/crates/rns-runtime/src/remote_management.rs new file mode 100644 index 0000000..1271e92 --- /dev/null +++ b/crates/rns-runtime/src/remote_management.rs @@ -0,0 +1,634 @@ +//! Authenticated RPC over Reticulum links (`rnstatus -R`, `rnpath -R`). +//! Registers `rnstransport.remote.management` with `/status` + `/path`. +//! +//! Auth: requires prior `LinkIdentify`, then checks identity against +//! `remote_management_allowed`. This mirrors Python `Destination.ALLOW_LIST`: +//! an empty allow-list denies all peers. +//! +//! REQUIRES a multi-threaded Tokio runtime — sync handler calls +//! `block_in_place`. Tests must use `#[tokio::test(flavor = "multi_thread")]`. + +use std::sync::Arc; + +use tokio::sync::{mpsc, oneshot}; + +use rns_crypto::sha::truncated_hash; +use rns_identity::destination::Destination; +use rns_identity::identity::Identity; +use rns_transport::messages::{ + InterfaceStatRpcEntry, PathTableRpcEntry, RateTableRpcEntry, TransportMessage, TransportQuery, + TransportQueryResponse, +}; + +use crate::remote_management_schema as schema; + +const STATUS_PATH: &str = "/status"; +const PATH_PATH: &str = "/path"; + +/// `identity` must be stable across restarts so clients can cache the dest +/// hash. Empty `allowed_identities` denies all peers, matching Python's +/// `Destination.ALLOW_LIST` semantics. +pub async fn start_remote_management( + transport_tx: mpsc::Sender, + identity: &Identity, + allowed_identities: Vec<[u8; 16]>, +) -> Result<[u8; 16], String> { + let signing_key = identity + .get_signing_key() + .ok_or_else(|| "No signing key available for remote management".to_string())?; + + let app_name = "rnstransport.remote.management"; + let dest_hash = Destination::hash_from_name_and_identity(app_name, Some(&identity.hash)); + let event_rx = crate::link_manager::register_destination(&transport_tx, dest_hash, app_name); + let mut lm = crate::link_manager::LinkManager::with_destination( + transport_tx.clone(), + event_rx, + identity, + app_name, + signing_key, + ); + + let status_hash: [u8; 16] = truncated_hash(STATUS_PATH.as_bytes()); + let paths_hash: [u8; 16] = truncated_hash(PATH_PATH.as_bytes()); + + let link_identities = lm.link_identities_handle(); + let allowed = Arc::new(allowed_identities); + let tx = transport_tx.clone(); + + lm.set_request_handler(move |link_id, path_hash, data| { + let peer = match link_identities.lock() { + Ok(guard) => guard.get(&link_id).copied(), + Err(_) => None, + }; + let peer = match peer { + Some(p) => p, + None => { + tracing::debug!( + link_id = %hex::encode(link_id), + "remote management: request before identification — dropping" + ); + return None; + } + }; + + if !peer_allowed(&allowed, &peer) { + tracing::warn!( + link_id = %hex::encode(link_id), + peer = %hex::encode(peer), + "remote management: peer not in allowed list — rejecting" + ); + return None; + } + + if path_hash == status_hash { + handle_status(&tx, &data) + } else if path_hash == paths_hash { + handle_path(&tx, &data) + } else { + tracing::debug!( + link_id = %hex::encode(link_id), + path_hash = %hex::encode(path_hash), + "remote management: unknown request path — dropping" + ); + None + } + }); + + let dest_hash = lm.destination_hash; + + tokio::spawn(async move { + lm.run().await; + }); + + tracing::info!( + dest = %hex::encode(dest_hash), + "remote management destination registered" + ); + + Ok(dest_hash) +} + +fn peer_allowed(allowed: &[[u8; 16]], peer: &[u8; 16]) -> bool { + allowed.iter().any(|a| a == peer) +} + +/// Request: `[include_link_count: bool]`. +/// Response: `[stats_dict]` or `[stats_dict, link_count]`. +fn handle_status(tx: &mpsc::Sender, data: &[u8]) -> Option> { + let include_link_count = parse_status_request(data).unwrap_or(false); + + let iface_stats = match blocking_query(tx, TransportQuery::GetInterfaceStats)? { + TransportQueryResponse::InterfaceStats(v) => v, + _ => return None, + }; + + let link_count = if include_link_count { + match blocking_query(tx, TransportQuery::GetLinkCount)? { + TransportQueryResponse::IntResult(n) => Some(n.max(0) as u64), + _ => None, + } + } else { + None + }; + + let stats = build_transport_stats(iface_stats); + + let bytes = if let Some(lc) = link_count { + rmp_serde::to_vec_named(&(&stats, lc)).ok()? + } else { + rmp_serde::to_vec_named(&(&stats,)).ok()? + }; + Some(bytes) +} + +/// Request: `[command: "table"|"rates", destination?: bytes, max_hops?: int]`. +/// Response: list of path-entry or rate-entry dicts. +fn handle_path(tx: &mpsc::Sender, data: &[u8]) -> Option> { + let (command, destination, max_hops) = parse_path_request(data)?; + + match command.as_str() { + "table" => { + let entries = match blocking_query(tx, TransportQuery::GetPathTable)? { + TransportQueryResponse::PathTable(v) => v, + _ => return None, + }; + let filtered: Vec = entries + .into_iter() + .filter(|e| destination.is_none_or(|d| e.hash == d)) + .filter(|e| max_hops.is_none_or(|m| e.hops <= m)) + .map(path_entry_from_rpc) + .collect(); + rmp_serde::to_vec_named(&filtered).ok() + } + "rates" => { + let entries = match blocking_query(tx, TransportQuery::GetRateTable)? { + TransportQueryResponse::RateTable(v) => v, + _ => return None, + }; + let filtered: Vec = entries + .into_iter() + .filter(|e| destination.is_none_or(|d| e.hash == d)) + .map(rate_entry_from_rpc) + .collect(); + rmp_serde::to_vec_named(&filtered).ok() + } + _ => None, + } +} + +fn parse_status_request(data: &[u8]) -> Option { + let v: rmpv::Value = rmp_serde::from_slice(data).ok()?; + v.as_array()?.first()?.as_bool() +} + +fn parse_path_request(data: &[u8]) -> Option<(String, Option<[u8; 16]>, Option)> { + let v: rmpv::Value = rmp_serde::from_slice(data).ok()?; + let args = v.as_array()?; + let command = args.first()?.as_str()?.to_string(); + let destination = args + .get(1) + .and_then(|v| v.as_slice()) + .and_then(|s| s.try_into().ok()); + let max_hops = args.get(2).and_then(|v| v.as_u64()).map(|n| n as u8); + Some((command, destination, max_hops)) +} + +/// `block_in_place` requires multi-threaded runtime; single-threaded +/// test runtimes panic. +fn blocking_query( + tx: &mpsc::Sender, + query: TransportQuery, +) -> Option { + let (resp_tx, resp_rx) = oneshot::channel(); + if tx + .try_send(TransportMessage::Rpc { + query, + response_tx: resp_tx, + }) + .is_err() + { + return None; + } + tokio::task::block_in_place(|| resp_rx.blocking_recv().ok()) +} + +fn build_transport_stats(entries: Vec) -> schema::TransportStats { + let (total_rxb, total_txb) = entries + .iter() + .fold((0u64, 0u64), |(r, t), e| (r + e.rx_bytes, t + e.tx_bytes)); + let (total_rxs, total_txs) = entries + .iter() + .fold((0u64, 0u64), |(r, t), e| (r + e.rx_rate, t + e.tx_rate)); + + let interfaces = entries.into_iter().map(interface_stats_from_rpc).collect(); + + schema::TransportStats { + interfaces, + rxb: total_rxb, + txb: total_txb, + rxs: total_rxs, + txs: total_txs, + transport_id: None, + network_id: None, + transport_uptime: None, + probe_responder: None, + rss: None, + } +} + +fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats { + let mode = mode_from_debug_string(&e.mode); + let ifac_size = if e.ifac_size > 0 { + Some(e.ifac_size as u64) + } else { + None + }; + schema::InterfaceStats { + name: e.name.clone(), + short_name: e.name, + hash: None, + type_: "Interface".to_string(), + rxb: e.rx_bytes, + txb: e.tx_bytes, + incoming_announce_frequency: e.incoming_announce_frequency, + outgoing_announce_frequency: e.outgoing_announce_frequency, + held_announces: e.held_announces, + status: e.online, + mode, + bitrate: Some(e.bitrate), + rxs: e.rx_rate, + txs: e.tx_rate, + announce_queue: e.announce_queue, + clients: e.clients, + ifac_signature: None, + ifac_size, + ifac_netname: None, + } +} + +fn path_entry_from_rpc(e: PathTableRpcEntry) -> schema::PathEntry { + schema::PathEntry { + hash: e.hash.to_vec(), + timestamp: e.timestamp, + via: e.via.map(|v| v.to_vec()), + hops: e.hops, + expires: e.expires, + interface: e.interface, + } +} + +fn rate_entry_from_rpc(e: RateTableRpcEntry) -> schema::RateEntry { + schema::RateEntry { + hash: e.hash.to_vec(), + rate: e.rate, + } +} + +/// Maps Debug-formatted InterfaceMode to Python `Interface.MODE_*` integers. +fn mode_from_debug_string(s: &str) -> u8 { + match s { + "Full" => 0x01, + "PointToPoint" => 0x02, + "Access" | "AccessPoint" => 0x03, + "Roaming" => 0x04, + "Boundary" => 0x05, + "Gateway" => 0x06, + _ => 0x01, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn remote_management_allow_list_denies_empty() { + let peer = [0x42; 16]; + assert!( + !peer_allowed(&[], &peer), + "empty ACL must match Python Destination.ALLOW_LIST and deny all" + ); + } + + #[test] + fn remote_management_allow_list_accepts_explicit_peer() { + let peer = [0x42; 16]; + let other = [0x24; 16]; + assert!(peer_allowed(&[peer], &peer)); + assert!(!peer_allowed(&[peer], &other)); + } + + #[test] + fn status_response_is_python_compatible_list() { + let stats = schema::TransportStats { + interfaces: vec![schema::InterfaceStats { + name: "TestIf".to_string(), + short_name: "TestIf".to_string(), + hash: None, + type_: "Interface".to_string(), + rxb: 42, + txb: 7, + incoming_announce_frequency: 0.0, + outgoing_announce_frequency: 0.0, + held_announces: 0, + status: true, + mode: 0x01, + bitrate: Some(1_000_000), + rxs: 0, + txs: 0, + announce_queue: None, + clients: None, + ifac_signature: None, + ifac_size: None, + ifac_netname: None, + }], + rxb: 42, + txb: 7, + rxs: 0, + txs: 0, + transport_id: None, + network_id: None, + transport_uptime: None, + probe_responder: None, + rss: None, + }; + + let encoded = rmp_serde::to_vec_named(&(&stats, 5u64)).unwrap(); + let decoded: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap(); + let arr = decoded.as_array().expect("top level is an array"); + assert_eq!(arr.len(), 2, "response is [stats_dict, link_count]"); + + let stats_map = arr[0].as_map().expect("first element is map"); + let has_interfaces = stats_map + .iter() + .any(|(k, _)| k.as_str() == Some("interfaces")); + assert!(has_interfaces, "stats dict has 'interfaces' key"); + + assert_eq!(arr[1].as_u64(), Some(5)); + } + + #[test] + fn path_response_is_list_of_dicts() { + let entry = schema::PathEntry { + hash: vec![0xAA; 16], + timestamp: 1_700_000_000.0, + via: Some(vec![0xBB; 16]), + hops: 2, + expires: 1_700_001_000.0, + interface: "TestIf".to_string(), + }; + let encoded = rmp_serde::to_vec_named(&vec![entry]).unwrap(); + let decoded: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap(); + let arr = decoded.as_array().expect("top-level array"); + assert_eq!(arr.len(), 1); + + let m = arr[0].as_map().expect("each entry is a map"); + let keys: Vec<&str> = m.iter().filter_map(|(k, _)| k.as_str()).collect(); + for expected in ["hash", "timestamp", "via", "hops", "expires", "interface"] { + assert!( + keys.contains(&expected), + "missing key {expected} in {keys:?}" + ); + } + + // hash/via are msgpack bin, not arrays-of-ints + let hash_val = m + .iter() + .find(|(k, _)| k.as_str() == Some("hash")) + .map(|(_, v)| v) + .unwrap(); + assert_eq!( + hash_val.as_slice(), + Some(&[0xAA; 16][..]), + "hash is msgpack bin" + ); + } + + #[test] + fn parse_status_request_decodes_bool_array() { + let data_true = rmp_serde::to_vec(&(true,)).unwrap(); + assert_eq!(parse_status_request(&data_true), Some(true)); + + let data_false = rmp_serde::to_vec(&(false,)).unwrap(); + assert_eq!(parse_status_request(&data_false), Some(false)); + + let data_empty = rmp_serde::to_vec::>(&vec![]).unwrap(); + assert_eq!(parse_status_request(&data_empty), None); + } + + #[test] + fn parse_path_request_table_no_filters() { + let data = rmp_serde::to_vec(&("table",)).unwrap(); + let (cmd, dest, max_hops) = parse_path_request(&data).unwrap(); + assert_eq!(cmd, "table"); + assert_eq!(dest, None); + assert_eq!(max_hops, None); + } + + #[test] + fn parse_path_request_rates_with_destination_and_max_hops() { + // Python wire: `["rates", msgpack_bin(dest), max_hops]`. + let dest_bytes = [0xCC; 16]; + let value = rmpv::Value::Array(vec![ + rmpv::Value::from("rates"), + rmpv::Value::Binary(dest_bytes.to_vec()), + rmpv::Value::from(3u64), + ]); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &value).unwrap(); + let (cmd, dest, max_hops) = parse_path_request(&buf).unwrap(); + assert_eq!(cmd, "rates"); + assert_eq!(dest, Some(dest_bytes)); + assert_eq!(max_hops, Some(3)); + } + + fn spawn_mock_transport() -> mpsc::Sender { + let (tx, mut rx) = mpsc::channel::(16); + tokio::spawn(async move { + while let Some(msg) = rx.recv().await { + if let TransportMessage::Rpc { query, response_tx } = msg { + let resp = match query { + TransportQuery::GetInterfaceStats => { + let stats = vec![InterfaceStatRpcEntry { + id: 1, + name: "MockIf".to_string(), + rx_bytes: 100, + tx_bytes: 200, + rx_rate: 10, + tx_rate: 20, + online: true, + bitrate: 12_000, + mtu: 512, + mode: "Gateway".to_string(), + role: "normal".to_string(), + announce_queue: Some(2), + held_announces: 1, + incoming_announce_frequency: 0.5, + outgoing_announce_frequency: 0.25, + clients: None, + announce_rate_target: None, + announce_rate_grace: None, + announce_rate_penalty: None, + announce_cap: 2.0, + ifac_size: 0, + tx_drops: 0, + }]; + TransportQueryResponse::InterfaceStats(stats) + } + TransportQuery::GetLinkCount => TransportQueryResponse::IntResult(3), + TransportQuery::GetPathTable => { + let entries = vec![PathTableRpcEntry { + hash: [0x11; 16], + timestamp: 1_700_000_000.0, + via: Some([0x22; 16]), + hops: 2, + expires: 1_700_100_000.0, + interface: "MockIf".to_string(), + }]; + TransportQueryResponse::PathTable(entries) + } + TransportQuery::GetRateTable => { + let entries = vec![RateTableRpcEntry { + hash: [0x33; 16], + rate: 1.25, + last: 1_700_000_000.0, + rate_violations: 2, + blocked_until: 0.0, + timestamps: vec![1_700_000_000.0], + }]; + TransportQueryResponse::RateTable(entries) + } + _ => TransportQueryResponse::Ok, + }; + let _ = response_tx.send(resp); + } + } + }); + tx + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn handle_status_end_to_end() { + let tx = spawn_mock_transport(); + + let req = rmp_serde::to_vec(&(true,)).unwrap(); + let resp = handle_status(&tx, &req).expect("handler produced a response"); + + let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap(); + let arr = decoded.as_array().expect("response is an array"); + assert_eq!(arr.len(), 2, "response is [stats_dict, link_count]"); + assert_eq!(arr[1].as_u64(), Some(3), "link count is 3"); + + let stats_map = arr[0].as_map().expect("stats is a map"); + let rxb = stats_map + .iter() + .find(|(k, _)| k.as_str() == Some("rxb")) + .unwrap() + .1 + .as_u64(); + assert_eq!(rxb, Some(100)); + let txb = stats_map + .iter() + .find(|(k, _)| k.as_str() == Some("txb")) + .unwrap() + .1 + .as_u64(); + assert_eq!(txb, Some(200)); + + let ifaces = stats_map + .iter() + .find(|(k, _)| k.as_str() == Some("interfaces")) + .unwrap() + .1 + .as_array() + .unwrap(); + assert_eq!(ifaces.len(), 1); + let iface_map = ifaces[0].as_map().unwrap(); + let name = iface_map + .iter() + .find(|(k, _)| k.as_str() == Some("name")) + .unwrap() + .1 + .as_str(); + assert_eq!(name, Some("MockIf")); + let mode = iface_map + .iter() + .find(|(k, _)| k.as_str() == Some("mode")) + .unwrap() + .1 + .as_u64(); + assert_eq!( + mode, + Some(0x06), + "Gateway mode maps to Python MODE_GATEWAY=0x06" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn handle_status_without_link_count() { + let tx = spawn_mock_transport(); + + let req = rmp_serde::to_vec(&(false,)).unwrap(); + let resp = handle_status(&tx, &req).unwrap(); + let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap(); + let arr = decoded.as_array().unwrap(); + assert_eq!(arr.len(), 1, "response is [stats_dict] with no link count"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn handle_path_table_end_to_end() { + let tx = spawn_mock_transport(); + + let req = rmp_serde::to_vec(&("table",)).unwrap(); + let resp = handle_path(&tx, &req).expect("handler produced a response"); + let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap(); + let arr = decoded.as_array().expect("response is an array"); + assert_eq!(arr.len(), 1); + + let entry = arr[0].as_map().unwrap(); + let hops = entry + .iter() + .find(|(k, _)| k.as_str() == Some("hops")) + .unwrap() + .1 + .as_u64(); + assert_eq!(hops, Some(2)); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn handle_path_rates_end_to_end() { + let tx = spawn_mock_transport(); + + let req = rmp_serde::to_vec(&("rates",)).unwrap(); + let resp = handle_path(&tx, &req).expect("handler produced a response"); + let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap(); + let arr = decoded.as_array().unwrap(); + assert_eq!(arr.len(), 1); + let entry = arr[0].as_map().unwrap(); + let rate = entry + .iter() + .find(|(k, _)| k.as_str() == Some("rate")) + .unwrap() + .1 + .as_f64(); + assert_eq!(rate, Some(1.25)); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn handle_path_unknown_command_returns_none() { + let tx = spawn_mock_transport(); + let req = rmp_serde::to_vec(&("wat",)).unwrap(); + assert!(handle_path(&tx, &req).is_none()); + } + + #[test] + fn mode_mapping_matches_python_constants() { + assert_eq!(mode_from_debug_string("Full"), 0x01); + assert_eq!(mode_from_debug_string("PointToPoint"), 0x02); + assert_eq!(mode_from_debug_string("Access"), 0x03); + assert_eq!(mode_from_debug_string("Roaming"), 0x04); + assert_eq!(mode_from_debug_string("Boundary"), 0x05); + assert_eq!(mode_from_debug_string("Gateway"), 0x06); + assert_eq!(mode_from_debug_string("Unknown"), 0x01); + } +} diff --git a/crates/rns-runtime/src/remote_management_schema.rs b/crates/rns-runtime/src/remote_management_schema.rs new file mode 100644 index 0000000..57c9525 --- /dev/null +++ b/crates/rns-runtime/src/remote_management_schema.rs @@ -0,0 +1,94 @@ +//! Msgpack wire schema for remote management; field names mirror Python +//! dict keys for `rnstatus -R` / `rnpath -R` interop. +//! See Transport.py:2591-2643, Reticulum.py:1090-1269. + +use serde::{Serialize, Serializer}; + +// rmp_serde's default encodes `Vec` as array-of-ints; Python expects msgpack bin. +pub(crate) mod bytes_vec { + use super::*; + pub fn serialize(bytes: &[u8], s: S) -> Result { + s.serialize_bytes(bytes) + } +} + +pub(crate) mod bytes_opt { + use super::*; + pub fn serialize(bytes: &Option>, s: S) -> Result { + match bytes { + Some(b) => s.serialize_bytes(b), + None => s.serialize_none(), + } + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct InterfaceStats { + pub name: String, + pub short_name: String, + #[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")] + pub hash: Option>, + #[serde(rename = "type")] + pub type_: String, + pub rxb: u64, + pub txb: u64, + pub incoming_announce_frequency: f64, + pub outgoing_announce_frequency: f64, + pub held_announces: u64, + /// Python field name (not `online`). + pub status: bool, + /// Matches Python `Interface.MODE_*` integers. + pub mode: u8, + #[serde(skip_serializing_if = "Option::is_none")] + pub bitrate: Option, + pub rxs: u64, + pub txs: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub announce_queue: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub clients: Option, + #[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")] + pub ifac_signature: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub ifac_size: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub ifac_netname: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct TransportStats { + pub interfaces: Vec, + pub rxb: u64, + pub txb: u64, + pub rxs: u64, + pub txs: u64, + #[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")] + pub transport_id: Option>, + #[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")] + pub network_id: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub transport_uptime: Option, + #[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")] + pub probe_responder: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub rss: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PathEntry { + #[serde(with = "bytes_vec")] + pub hash: Vec, + pub timestamp: f64, + #[serde(with = "bytes_opt")] + pub via: Option>, + pub hops: u8, + pub expires: f64, + pub interface: String, +} + +#[derive(Debug, Clone, Serialize)] +pub struct RateEntry { + #[serde(with = "bytes_vec")] + pub hash: Vec, + pub rate: f64, +} diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs new file mode 100644 index 0000000..58c2006 --- /dev/null +++ b/crates/rns-runtime/src/reticulum.rs @@ -0,0 +1,3795 @@ +//! Reticulum runtime singleton, init and lifecycle. Three operating modes: +//! **Shared** owns hardware and serves RPC to siblings; **Client** connects +//! to a Shared instance over a local socket; **Standalone** owns its +//! interfaces and exposes no IPC. Python: `RNS/Reticulum.py`. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64}; +use std::sync::{Arc, OnceLock}; + +use std::time::Duration; + +use bytes::Bytes; +use tokio::sync::{Mutex, mpsc}; +use tokio::task::JoinHandle; + +use crate::config::{Config, ConfigError, ConfigSection}; +use crate::constants::*; +use crate::interface_factory; +use crate::jobs::{Job, JobScheduler}; +use crate::lifecycle::ShutdownSignal; +use crate::link_client::LinkClient; +use crate::link_manager::LinkManager; +use crate::platform::{StoragePaths, resolve_config_dir}; +use rns_identity::identity::Identity; +use rns_transport::await_path::{AwaitPathError, await_path}; +use rns_transport::discovery::{ + Announcer, BLACKHOLE_INITIAL_WAIT, BLACKHOLE_JOB_INTERVAL, BLACKHOLE_SOURCE_TIMEOUT, + BLACKHOLE_UPDATE_INTERVAL, BlackholeSubscriberState, DiscoveredInterface, DiscoveryDecryptor, + DiscoveryInterfaceConfig, DiscoveryStamper, DiscoveryStore, ReceiverConfig, discovery_hash, +}; +use rns_transport::messages::{ + OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse, +}; + +static INSTANCE: OnceLock = OnceLock::new(); + +/// Spawned interface driver tasks, keyed by `interface_id`. Stash is required: +/// dropping the JoinHandle only detaches the task, so `teardown_interface` +/// must abort it explicitly to stop reconnect/read/write loops. +static INTERFACE_TASKS: OnceLock>>> = OnceLock::new(); + +fn interface_tasks() -> &'static std::sync::Mutex>> { + INTERFACE_TASKS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) +} + +#[derive(Clone)] +pub struct ReticulumHandle { + pub transport_tx: mpsc::Sender, + pub config_dir: PathBuf, + pub instance_mode: InstanceMode, + pub interface_configs: Vec, + /// ID allocator for interfaces spawned dynamically after init. + pub id_gen: Arc, + /// Used by server-style interfaces to register per-client sub-handles. + pub handle_tx: mpsc::Sender, + pub socket_base: PathBuf, + pub config: ReticulumConfig, + /// Mobile builds throttle tick rates when the app is backgrounded. + pub is_foreground: Arc, + pub shutdown: ShutdownSignal, + pub transport_identity: Arc, + pub network_identity: Option>, + /// Present even when `discover_interfaces = No` so a downstream can + /// still install a stamper and start publishing. + pub discovery: Arc, +} + +/// Shared discovery state behind one `Arc` so cloning [`ReticulumHandle`] +/// doesn't proliferate state. Holds inputs for the eventual announce tick / +/// subscriber loop. +pub struct DiscoveryRuntime { + stamper: Mutex>>, + store: Mutex>>, + receiver_started: Mutex, + announcer_started: Mutex, + subscriber_started: Mutex, + local_interfaces: Mutex>, + autoconnected: Mutex>, + bootstrap_interfaces: Mutex>, +} + +impl Default for DiscoveryRuntime { + fn default() -> Self { + Self { + stamper: Mutex::new(None), + store: Mutex::new(None), + receiver_started: Mutex::new(false), + announcer_started: Mutex::new(false), + subscriber_started: Mutex::new(false), + local_interfaces: Mutex::new(Vec::new()), + autoconnected: Mutex::new(HashMap::new()), + bootstrap_interfaces: Mutex::new(Vec::new()), + } + } +} + +#[derive(Debug, Clone)] +struct LocalDiscoveryInterface { + id: u64, + config: DiscoveryInterfaceConfig, +} + +impl ReticulumHandle { + pub fn transport_enabled(&self) -> bool { + self.config.enable_transport + } + + pub fn should_use_implicit_proof(&self) -> bool { + self.config.use_implicit_proof + } + + pub fn remote_management_enabled(&self) -> bool { + self.config.enable_remote_management + } + + pub fn link_mtu_discovery(&self) -> bool { + self.config.link_mtu_discovery + } + + /// Wait up to `timeout` for the transport actor to resolve a path. + /// Python: `Transport.await_path` (RNS/Transport.py:2524). + pub async fn await_path( + &self, + destination_hash: [u8; 16], + timeout: Duration, + ) -> Result<(), AwaitPathError> { + await_path(&self.transport_tx, destination_hash, timeout).await + } + + /// Query this process' transport actor directly. + pub async fn query_transport(&self, query: TransportQuery) -> Option { + let (tx, rx) = tokio::sync::oneshot::channel(); + if self + .transport_tx + .send(TransportMessage::Rpc { + query, + response_tx: tx, + }) + .await + .is_err() + { + return None; + } + tokio::time::timeout(Duration::from_secs(5), rx) + .await + .ok() + .and_then(|r| r.ok()) + } + + /// Query the authoritative control plane. + /// + /// In client mode, Python proxies Reticulum control methods to the local + /// shared instance over the RPC listener. Mirror that for the operations + /// Python exposes, then fall back to the local actor for Rust-only/local + /// diagnostics such as recent announce snapshots. + pub async fn query_control(&self, query: TransportQuery) -> Option { + if self.instance_mode == InstanceMode::Client + && let Some(request) = transport_query_to_rpc_request(&query) + && let Some(rpc_key) = self.config.rpc_key.as_deref() + { + let rpc_result = match self.config.shared_rpc_endpoint(&self.socket_base) { + SharedInstanceRpcEndpoint::Tcp(port) => { + crate::rpc::connect_and_request(port, rpc_key, &request, Duration::from_secs(5)) + .await + } + SharedInstanceRpcEndpoint::Unix(socket_path) => { + crate::rpc::connect_unix_and_request( + &socket_path, + rpc_key, + &request, + Duration::from_secs(5), + ) + .await + } + }; + match rpc_result { + Ok(response) => { + if let Some(mapped) = rpc_response_to_transport_response(response) { + return Some(mapped); + } + } + Err(e) => { + tracing::debug!(error = %e, "shared instance control RPC failed; falling back to local actor"); + } + } + } + + self.query_transport(query).await + } + + /// Install a [`DiscoveryStamper`] so this node can emit PoW-stamped + /// discovery announces. Inverts Python's hard `LXMF.LXStamper` import + /// (RNS/Discovery.py:41) — downstream apps install at startup. Idempotent; + /// without a stamper, discovery stays silently inert. + pub async fn enable_on_network_discovery( + &self, + stamper: Arc, + ) { + *self.discovery.stamper.lock().await = Some(stamper); + start_on_network_discovery(self.clone()).await; + } + + pub async fn discovery_enabled(&self) -> bool { + self.discovery.stamper.lock().await.is_some() + } + + /// Snapshot of currently-known interfaces. Stale + disallowed entries + /// are purged on read. Python: `discovered_interfaces()`. + pub async fn discovered_interfaces(&self) -> Vec { + let store = self.discovery.store.lock().await.clone(); + let Some(store) = store else { + return Vec::new(); + }; + let sources = if self.config.interface_discovery_sources.is_empty() { + None + } else { + Some(self.config.interface_discovery_sources.as_slice()) + }; + store.list(sources).unwrap_or_default() + } + + /// Identity hashes whose blackhole manifest this node subscribes to. + /// Python: `Reticulum.blackhole_sources()`. + pub fn blackhole_sources(&self) -> &[[u8; 16]] { + &self.config.blackhole_sources + } + + pub fn publish_blackhole_enabled(&self) -> bool { + self.config.publish_blackhole + } + + #[cfg(test)] + pub(crate) async fn install_discovery_store_for_tests(&self, store: Arc) { + *self.discovery.store.lock().await = Some(store); + } +} + +fn transport_query_to_rpc_request(query: &TransportQuery) -> Option { + use crate::rpc::RpcRequest; + Some(match query { + TransportQuery::GetPathTable => RpcRequest::GetPathTable { max_hops: None }, + TransportQuery::GetInterfaceStats => RpcRequest::GetInterfaceStats, + TransportQuery::GetRateTable => RpcRequest::GetRateTable, + TransportQuery::GetLinkCount => RpcRequest::GetLinkCount, + TransportQuery::GetNextHopIfName { dest } => RpcRequest::GetNextHopIfName { + destination_hash: dest.to_vec(), + }, + TransportQuery::GetNextHop { dest } => RpcRequest::GetNextHop { + destination_hash: dest.to_vec(), + }, + TransportQuery::FirstHopTimeout { dest } => RpcRequest::GetFirstHopTimeout { + destination_hash: dest.to_vec(), + }, + TransportQuery::GetPacketRssi { packet_hash } => RpcRequest::GetPacketRssi { + packet_hash: packet_hash.to_vec(), + }, + TransportQuery::GetPacketSnr { packet_hash } => RpcRequest::GetPacketSnr { + packet_hash: packet_hash.to_vec(), + }, + TransportQuery::GetPacketQ { packet_hash } => RpcRequest::GetPacketQ { + packet_hash: packet_hash.to_vec(), + }, + TransportQuery::GetBlackholedIdentities => RpcRequest::GetBlackholedIdentities, + TransportQuery::DropPath { dest } => RpcRequest::DropPath { + destination_hash: dest.to_vec(), + }, + TransportQuery::DropAllVia { next_hop } => RpcRequest::DropAllVia { + transport_hash: next_hop.to_vec(), + }, + TransportQuery::DropAnnounceQueues => RpcRequest::DropAnnounceQueues, + TransportQuery::BlackholeIdentity { + hash, + ttl, + reason, + reason_label, + } => RpcRequest::BlackholeIdentity { + identity_hash: hash.to_vec(), + until: ttl.map(|ttl| unix_now() + ttl), + reason: Some( + reason_label + .clone() + .unwrap_or_else(|| reason.as_str().to_string()), + ), + }, + TransportQuery::UnblackholeIdentity { hash } => RpcRequest::UnblackholeIdentity { + identity_hash: hash.to_vec(), + }, + TransportQuery::RetainDestination { dest } => RpcRequest::RetainDestination { + destination_hash: dest.to_vec(), + }, + TransportQuery::UseDestination { dest } => RpcRequest::UseDestination { + destination_hash: dest.to_vec(), + }, + TransportQuery::UnretainDestination { dest } => RpcRequest::UnretainDestination { + destination_hash: dest.to_vec(), + }, + _ => return None, + }) +} + +fn rpc_response_to_transport_response( + response: crate::rpc::RpcResponse, +) -> Option { + use crate::rpc::RpcResponse; + use rns_transport::messages::{ + BlackholeRpcEntry, InterfaceStatRpcEntry, PathTableRpcEntry, RateTableRpcEntry, + }; + + Some(match response { + RpcResponse::PathTable(entries) => { + let entries = entries + .into_iter() + .filter_map(|entry| { + Some(PathTableRpcEntry { + hash: vec_to_16(&entry.hash)?, + timestamp: entry.timestamp, + via: entry.via.as_deref().and_then(vec_to_16), + hops: entry.hops, + expires: entry.expires, + interface: entry.interface, + }) + }) + .collect(); + TransportQueryResponse::PathTable(entries) + } + RpcResponse::InterfaceStats(entries) => { + let entries = entries + .into_iter() + .map(|entry| InterfaceStatRpcEntry { + id: entry.id, + name: entry.name, + rx_bytes: entry.rx_bytes, + tx_bytes: entry.tx_bytes, + rx_rate: entry.rx_rate, + tx_rate: entry.tx_rate, + online: entry.online, + bitrate: entry.bitrate, + mtu: entry.mtu, + mode: entry.mode, + role: entry.role, + announce_queue: entry.announce_queue, + held_announces: entry.held_announces, + incoming_announce_frequency: entry.incoming_announce_frequency, + outgoing_announce_frequency: entry.outgoing_announce_frequency, + clients: entry.clients, + announce_rate_target: entry.announce_rate_target, + announce_rate_grace: entry.announce_rate_grace, + announce_rate_penalty: entry.announce_rate_penalty, + announce_cap: entry.announce_cap, + ifac_size: entry.ifac_size, + tx_drops: entry.tx_drops, + }) + .collect(); + TransportQueryResponse::InterfaceStats(entries) + } + RpcResponse::RateTable(entries) => { + let entries = entries + .into_iter() + .filter_map(|entry| { + Some(RateTableRpcEntry { + hash: vec_to_16(&entry.hash)?, + rate: entry.rate, + last: entry.last, + rate_violations: entry.rate_violations, + blocked_until: entry.blocked_until, + timestamps: entry.timestamps, + }) + }) + .collect(); + TransportQueryResponse::RateTable(entries) + } + RpcResponse::StringResult(v) => TransportQueryResponse::StringResult(v), + RpcResponse::HashResult(v) => { + TransportQueryResponse::HashResult(v.as_deref().and_then(vec_to_16)) + } + RpcResponse::FloatResult(v) => TransportQueryResponse::FloatResult(v), + RpcResponse::IntResult(v) => TransportQueryResponse::IntResult(v), + RpcResponse::BoolResult(v) => TransportQueryResponse::BoolResult(v), + RpcResponse::BlackholeList(entries) => { + let now = unix_now(); + let entries = entries + .into_iter() + .filter_map(|entry| { + Some(BlackholeRpcEntry { + identity_hash: vec_to_16(&entry.identity_hash)?, + source: entry.source.as_deref().and_then(vec_to_16), + created: now, + ttl: entry.until.map(|until| (until - now).max(0.0)), + reason: entry + .reason + .as_deref() + .map(rns_transport::blackhole::BlackholeReason::parse) + .unwrap_or_default(), + reason_label: entry.reason, + }) + }) + .collect(); + TransportQueryResponse::BlackholeList(entries) + } + RpcResponse::Ok => TransportQueryResponse::Ok, + RpcResponse::Error(e) => TransportQueryResponse::Error(e), + }) +} + +fn vec_to_16(bytes: &[u8]) -> Option<[u8; 16]> { + if bytes.len() < 16 { + return None; + } + let mut out = [0u8; 16]; + out.copy_from_slice(&bytes[..16]); + Some(out) +} + +fn unix_now() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InstanceMode { + Shared, + Client, + Standalone, +} + +/// Shared-instance transport: TCP loopback or AF_UNIX socket. Python uses +/// AF_UNIX only on Linux/Android and TCP elsewhere. Python config key: +/// `shared_instance_type`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SharedInstanceType { + /// TCP loopback on [`ReticulumConfig::shared_instance_port`]. + Tcp, + /// AF_UNIX socket; Linux/Android use Python-compatible abstract names. + Unix, +} + +impl SharedInstanceType { + fn platform_default() -> Self { + if cfg!(any(target_os = "linux", target_os = "android")) { + Self::Unix + } else { + Self::Tcp + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SharedInstanceRpcEndpoint { + Tcp(u16), + Unix(String), +} + +impl SharedInstanceRpcEndpoint { + pub fn display(&self) -> String { + match self { + Self::Tcp(port) => format!("127.0.0.1:{port}"), + Self::Unix(path) => socket_path_display(path), + } + } +} + +fn shared_unix_socket_path(instance_name: &str, socket_base: &Path) -> String { + if cfg!(any(target_os = "linux", target_os = "android")) { + rns_interface::local::python_shared_socket_name(instance_name) + } else { + socket_base + .join(format!("reticulum_rs_{instance_name}.sock")) + .to_string_lossy() + .to_string() + } +} + +fn shared_unix_rpc_socket_path(instance_name: &str, socket_base: &Path) -> String { + if cfg!(any(target_os = "linux", target_os = "android")) { + format!("\0rns/{instance_name}/rpc") + } else { + socket_base + .join(format!("reticulum_rs_{instance_name}.rpc.sock")) + .to_string_lossy() + .to_string() + } +} + +pub fn shared_instance_rpc_socket_path(instance_name: &str, socket_base: &Path) -> String { + shared_unix_rpc_socket_path(instance_name, socket_base) +} + +fn shared_tcp_client_config(port: u16) -> rns_interface::tcp::TcpClientConfig { + rns_interface::tcp::TcpClientConfig::new("SharedInstanceClient", "127.0.0.1", port) +} + +async fn detect_shared_tcp_server(port: u16) -> bool { + let addr = format!("127.0.0.1:{port}"); + tokio::time::timeout( + Duration::from_millis(250), + tokio::net::TcpStream::connect(&addr), + ) + .await + .is_ok_and(|r| r.is_ok()) +} + +fn socket_path_display(path: &str) -> String { + if path.as_bytes().first() == Some(&0) { + format!("\\0{}", &path[1..]) + } else { + path.to_string() + } +} + +#[derive(Debug, Clone)] +pub struct ReticulumConfig { + pub share_instance: bool, + pub instance_name: String, + pub shared_instance_type: SharedInstanceType, + pub shared_instance_port: u16, + pub control_port: u16, + pub enable_transport: bool, + pub respond_to_probes: bool, + pub use_implicit_proof: bool, + pub panic_on_interface_error: bool, + pub link_mtu_discovery: bool, + pub enable_remote_management: bool, + pub remote_management_allowed: Vec>, + pub rpc_key: Option>, + /// Python `force_shared_instance_bitrate` (bps). Caps announce rate / + /// token bucket regardless of real link bitrate. + pub force_shared_instance_bitrate: Option, + pub loglevel: i32, + + /// Optional "network identity" file: discovery announce app_data is + /// encrypted to this identity's pubkey. Python `network_identity`. + pub network_identity_path: Option, + /// Publish periodic discovery announces. Python `discover_interfaces`. + pub discover_interfaces: bool, + /// Maximum number of discovered interfaces to auto-connect to. Python + /// `autoconnect_discovered_interfaces`. + pub autoconnect_discovered_interfaces: usize, + /// Minimum stamp value (leading-zero bits). Default 14 (LXStamper + /// `DEFAULT_STAMP_VALUE`). Python `required_discovery_value`. + pub discover_interfaces_required_value: u8, + /// Accepted discovery publisher identities. Python + /// `interface_discovery_sources`. + pub interface_discovery_sources: Vec<[u8; 16]>, + + /// Identity hashes whose `rnstransport.info.blackhole` manifests this + /// node subscribes to. Python `blackhole_sources`. + pub blackhole_sources: Vec<[u8; 16]>, + /// Publish this node's local blackhole table on + /// `rnstransport.info.blackhole`. Python `publish_blackhole`. + pub publish_blackhole: bool, + + /// Bootstrap config files loaded on startup. Python `bootstrap_configs`. + pub bootstrap_configs: Vec, +} + +impl Default for ReticulumConfig { + fn default() -> Self { + Self { + share_instance: true, + instance_name: DEFAULT_INSTANCE_NAME.to_string(), + shared_instance_type: SharedInstanceType::platform_default(), + shared_instance_port: LOCAL_INTERFACE_PORT, + control_port: LOCAL_CONTROL_PORT, + enable_transport: false, + respond_to_probes: false, + use_implicit_proof: true, + panic_on_interface_error: false, + link_mtu_discovery: true, + enable_remote_management: false, + remote_management_allowed: Vec::new(), + rpc_key: None, + force_shared_instance_bitrate: None, + loglevel: 4, + network_identity_path: None, + discover_interfaces: false, + autoconnect_discovered_interfaces: 0, + discover_interfaces_required_value: 14, + interface_discovery_sources: Vec::new(), + blackhole_sources: Vec::new(), + publish_blackhole: false, + bootstrap_configs: Vec::new(), + } + } +} + +impl ReticulumConfig { + pub fn shared_rpc_endpoint(&self, socket_base: &Path) -> SharedInstanceRpcEndpoint { + match self.shared_instance_type { + SharedInstanceType::Tcp => SharedInstanceRpcEndpoint::Tcp(self.control_port), + SharedInstanceType::Unix => SharedInstanceRpcEndpoint::Unix( + shared_instance_rpc_socket_path(&self.instance_name, socket_base), + ), + } + } +} + +fn invalid_config_value(section: &str, key: &str, message: impl Into) -> ConfigError { + ConfigError::InvalidValue { + section: section.to_string(), + key: key.to_string(), + message: message.into(), + } +} + +fn config_bool( + section_name: &str, + section: &ConfigSection, + key: &str, +) -> Result, ConfigError> { + if !section.has(key) { + return Ok(None); + } + section + .get_bool(key) + .map(Some) + .ok_or_else(|| invalid_config_value(section_name, key, "value is neither True nor False")) +} + +fn config_int( + section_name: &str, + section: &ConfigSection, + key: &str, +) -> Result, ConfigError> { + if !section.has(key) { + return Ok(None); + } + section + .get_int(key) + .map(Some) + .ok_or_else(|| invalid_config_value(section_name, key, "value is not an integer")) +} + +fn config_uint( + section_name: &str, + section: &ConfigSection, + key: &str, +) -> Result, ConfigError> { + if !section.has(key) { + return Ok(None); + } + section + .get_uint(key) + .map(Some) + .ok_or_else(|| invalid_config_value(section_name, key, "value is not an unsigned integer")) +} + +fn config_u16( + section_name: &str, + section: &ConfigSection, + key: &str, +) -> Result, ConfigError> { + let Some(value) = config_uint(section_name, section, key)? else { + return Ok(None); + }; + let value = u16::try_from(value) + .map_err(|_| invalid_config_value(section_name, key, "value is outside u16 range"))?; + Ok(Some(value)) +} + +fn parse_autoconnect_limit(sec: &ConfigSection) -> Result, ConfigError> { + if let Some(v) = config_uint("reticulum", sec, "autoconnect_discovered_interfaces")? { + return Ok(Some(v as usize)); + } + + // Rust retained this pre-1.2.1 alias while adding the upstream integer + // key above. Keep bool support only for the alias so the Python key still + // rejects `Yes`/`No` like ConfigObj `as_int()`. + let key = "discover_interfaces_autoconnect"; + if sec.has(key) { + if let Some(v) = sec.get_uint(key) { + return Ok(Some(v as usize)); + } + if let Some(v) = sec.get_bool(key) { + return Ok(Some(usize::from(v))); + } + return Err(invalid_config_value( + "reticulum", + key, + "value is not an integer or boolean", + )); + } + + Ok(None) +} + +fn parse_hash16_list(key: &str, list: Option>) -> Result, ConfigError> { + let mut parsed = Vec::new(); + for value in list.unwrap_or_default() { + let hexhash = value.trim(); + let bytes = hex_decode(hexhash) + .ok_or_else(|| invalid_config_value("reticulum", key, "invalid identity hash"))?; + if bytes.len() != 16 { + return Err(invalid_config_value( + "reticulum", + key, + "identity hash must be 32 hexadecimal characters (16 bytes)", + )); + } + let mut hash = [0u8; 16]; + hash.copy_from_slice(&bytes); + parsed.push(hash); + } + Ok(parsed) +} + +fn expand_home_path(path: &str) -> PathBuf { + if (path == "~" || path.starts_with("~/")) + && let Ok(home) = std::env::var("HOME") + { + return PathBuf::from(format!("{home}{}", &path[1..])); + } + PathBuf::from(path) +} + +impl ReticulumConfig { + pub fn try_from_config(config: &Config) -> Result { + let mut rc = ReticulumConfig::default(); + + if let Some(sec) = config.section("reticulum") { + if let Some(value) = config_bool("reticulum", sec, "share_instance")? { + rc.share_instance = value; + } + if let Some(name) = sec.get("instance_name") { + rc.instance_name = name.to_string(); + } + if let Some(kind) = sec.get("shared_instance_type") { + match kind.trim().to_lowercase().as_str() { + "tcp" => rc.shared_instance_type = SharedInstanceType::Tcp, + "unix" => rc.shared_instance_type = SharedInstanceType::Unix, + _ => {} + } + } + if let Some(port) = config_u16("reticulum", sec, "shared_instance_port")? { + rc.shared_instance_port = port; + } + if let Some(port) = config_u16("reticulum", sec, "instance_control_port")? { + rc.control_port = port; + } + if let Some(value) = config_bool("reticulum", sec, "enable_transport")? { + rc.enable_transport = value; + } + if let Some(value) = config_bool("reticulum", sec, "respond_to_probes")? { + rc.respond_to_probes = value; + } + if let Some(value) = config_bool("reticulum", sec, "use_implicit_proof")? { + rc.use_implicit_proof = value; + } + if let Some(value) = config_bool("reticulum", sec, "panic_on_interface_error")? { + rc.panic_on_interface_error = value; + } + if let Some(value) = config_bool("reticulum", sec, "link_mtu_discovery")? { + rc.link_mtu_discovery = value; + } + if let Some(value) = config_bool("reticulum", sec, "enable_remote_management")? { + rc.enable_remote_management = value; + } + rc.force_shared_instance_bitrate = + config_uint("reticulum", sec, "force_shared_instance_bitrate")?; + + if let Some(list) = sec.get_list("remote_management_allowed") { + rc.remote_management_allowed = + parse_hash16_list("remote_management_allowed", Some(list))? + .into_iter() + .map(|hash| hash.to_vec()) + .collect(); + } + if let Some(key) = sec.get_hex("rpc_key") { + rc.rpc_key = Some(key); + } + + if let Some(path) = sec.get("network_identity") { + let trimmed = path.trim(); + if !trimmed.is_empty() { + rc.network_identity_path = Some(expand_home_path(trimmed)); + } + } + if let Some(value) = config_bool("reticulum", sec, "discover_interfaces")? { + rc.discover_interfaces = value; + } + rc.autoconnect_discovered_interfaces = + parse_autoconnect_limit(sec)?.unwrap_or(rc.autoconnect_discovered_interfaces); + if let Some(v) = config_uint("reticulum", sec, "required_discovery_value")?.or( + config_uint("reticulum", sec, "discover_interfaces_required_value")?, + ) { + rc.discover_interfaces_required_value = v.min(u8::MAX as u64) as u8; + } + rc.interface_discovery_sources = parse_hash16_list( + "interface_discovery_sources", + sec.get_list("interface_discovery_sources"), + )?; + if let Some(value) = config_bool("reticulum", sec, "publish_blackhole")? { + rc.publish_blackhole = value; + } + + if let Some(list) = sec.get_list("blackhole_sources") { + rc.blackhole_sources = parse_hash16_list("blackhole_sources", Some(list))?; + } + if let Some(list) = sec.get_list("bootstrap_configs") { + rc.bootstrap_configs = list.iter().map(|s| PathBuf::from(s.trim())).collect(); + } + } + + if let Some(sec) = config.section("logging") + && let Some(level) = config_int("logging", sec, "loglevel")? + { + rc.loglevel = (level as i32).clamp(0, 7); + } + + Ok(rc) + } + + pub fn from_config(config: &Config) -> Self { + Self::try_from_config(config).expect("valid Reticulum configuration") + } +} + +/// Bring up the Reticulum runtime: config dir, transport actor, interfaces, +/// instance mode, jobs runner, and optional RPC / remote-management / probe. +pub async fn init( + configdir: Option<&str>, + socket_dir: Option, + shutdown: ShutdownSignal, + is_foreground: Arc, +) -> Result { + let config_dir = resolve_config_dir(configdir); + let paths = StoragePaths::from_config_dir(&config_dir); + paths.ensure_dirs().map_err(ReticulumError::Io)?; + + let config_path = config_dir.join("config"); + let (config, config_created) = load_or_create_config(&config_path)?; + if config_created { + tracing::info!( + path = %config_path.display(), + "created default Reticulum config; continuing after first-run grace period" + ); + tokio::time::sleep(Duration::from_millis(1500)).await; + } + let mut rc = ReticulumConfig::try_from_config(&config).map_err(ReticulumError::Config)?; + + let (mut actor, transport_tx) = rns_transport::actor::TransportActor::new(); + actor.is_foreground = is_foreground.clone(); + + let shutdown_tx = transport_tx.clone(); + let shutdown_clone = shutdown.clone(); + tokio::spawn(async move { + actor.run().await; + }); + + let _ = transport_tx.try_send(TransportMessage::SetStoragePaths { + storage_dir: paths.storage_dir.clone(), + }); + + // Python Reticulum has a persistent transport identity. The actor needs + // its hash for transport-node path requests and Header2 path responses. + let transport_identity_path = paths.storage_dir.join("transport_identity"); + let transport_identity = match rns_identity::identity::Identity::from_file( + &transport_identity_path, + ) { + Ok(id) => id, + Err(_) => { + let id = rns_identity::identity::Identity::new(); + if let Err(e) = id.to_file(&transport_identity_path) { + tracing::warn!(path = %transport_identity_path.display(), error = %e, + "failed to persist transport identity — path request identity will change on restart"); + } + id + } + }; + let _ = transport_tx.try_send(TransportMessage::SetTransportIdentity { + identity_hash: transport_identity.hash, + }); + let _ = transport_tx.try_send(TransportMessage::SetBlackholeSources { + sources: rc.blackhole_sources.clone(), + }); + + // Python defaults the local shared-instance RPC key to a hash of the + // persistent transport identity, so CLI/control clients work without an + // explicit config key as long as they share the same config directory. + if rc.rpc_key.is_none() + && let Some(private_key) = transport_identity.get_private_key() + { + rc.rpc_key = Some(crate::rpc::derive_rpc_key(&*private_key).to_vec()); + } + let transport_identity = Arc::new(transport_identity); + + let network_identity = rc + .network_identity_path + .as_ref() + .map(|path| load_or_create_network_identity(path)) + .transpose()?; + + let id_gen = Arc::new(AtomicU64::new(1)); + + // Sub-interface sink (e.g. TCP per-client). + let (handle_tx, mut handle_rx) = mpsc::channel::(64); + + let socket_base = socket_dir.clone().unwrap_or_else(std::env::temp_dir); + let instance_mode = if rc.share_instance { + if rc.shared_instance_type == SharedInstanceType::Tcp { + let live_server_detected = detect_shared_tcp_server(rc.shared_instance_port).await; + + if live_server_detected { + let client_config = shared_tcp_client_config(rc.shared_instance_port); + let client_id = next_id(&id_gen); + match rns_interface::tcp::spawn_tcp_client( + client_config, + client_id, + transport_tx.clone(), + None, + ) + .await + { + Ok(client_handle) => { + let client_iface_id = client_handle.id; + register_interface_handle_with_role( + &transport_tx, + client_handle, + rns_transport::messages::InterfaceRole::SharedInstancePeer, + ) + .await; + let _ = transport_tx + .send(TransportMessage::SharedConnectionRestored { + interface_id: client_iface_id, + }) + .await; + InstanceMode::Client + } + Err(_) => InstanceMode::Standalone, + } + } else { + let server_config = rns_interface::tcp::TcpServerConfig::new( + "SharedInstanceServer", + "127.0.0.1", + rc.shared_instance_port, + ); + let server_id = next_id(&id_gen); + match rns_interface::tcp::spawn_tcp_server( + server_config, + server_id, + id_gen.clone(), + transport_tx.clone(), + handle_tx.clone(), + ) + .await + { + Ok(server_handle) => { + register_interface_handle_with_role( + &transport_tx, + server_handle, + rns_transport::messages::InterfaceRole::SharedServer, + ) + .await; + InstanceMode::Shared + } + Err(_) => { + if detect_shared_tcp_server(rc.shared_instance_port).await { + let client_config = shared_tcp_client_config(rc.shared_instance_port); + let client_id = next_id(&id_gen); + match rns_interface::tcp::spawn_tcp_client( + client_config, + client_id, + transport_tx.clone(), + None, + ) + .await + { + Ok(client_handle) => { + let client_iface_id = client_handle.id; + register_interface_handle_with_role( + &transport_tx, + client_handle, + rns_transport::messages::InterfaceRole::SharedInstancePeer, + ) + .await; + let _ = transport_tx + .send(TransportMessage::SharedConnectionRestored { + interface_id: client_iface_id, + }) + .await; + InstanceMode::Client + } + Err(_) => InstanceMode::Standalone, + } + } else { + InstanceMode::Standalone + } + } + } + } + } else { + let socket_path = shared_unix_socket_path(&rc.instance_name, &socket_base); + // Probe before binding: spawn_local_server unconditionally removes + // the socket, which would otherwise hijack a live sibling's listener. + let mut live_server_detected = false; + #[cfg(unix)] + { + let is_abstract = socket_path.as_bytes().first() == Some(&0); + if is_abstract || std::path::Path::new(&socket_path).exists() { + match tokio::net::UnixStream::connect(&socket_path).await { + Ok(_) => { + tracing::info!( + "existing shared instance detected on {}", + socket_path_display(&socket_path) + ); + live_server_detected = true; + } + Err(_) => { + if !is_abstract { + tracing::info!( + "removing stale shared instance socket: {}", + socket_path_display(&socket_path) + ); + std::fs::remove_file(&socket_path).ok(); + } + } + } + } + } + + if live_server_detected { + let client_config = rns_interface::local::LocalClientConfig { + socket_path, + name: "SharedInstanceClient".to_string(), + }; + let client_id = next_id(&id_gen); + match rns_interface::local::spawn_local_client( + client_config, + client_id, + transport_tx.clone(), + ) + .await + { + Ok(client_handle) => { + let client_iface_id = client_handle.id; + register_interface_handle_with_role( + &transport_tx, + client_handle, + rns_transport::messages::InterfaceRole::SharedInstancePeer, + ) + .await; + let _ = transport_tx + .send(TransportMessage::SharedConnectionRestored { + interface_id: client_iface_id, + }) + .await; + InstanceMode::Client + } + Err(_) => InstanceMode::Standalone, + } + } else { + let server_config = rns_interface::local::LocalServerConfig { + socket_path: socket_path.clone(), + name: "SharedInstanceServer".to_string(), + }; + match rns_interface::local::spawn_local_server( + server_config, + id_gen.clone(), + transport_tx.clone(), + handle_tx.clone(), + ) + .await + { + Ok(server_handle) => { + register_interface_handle_with_role( + &transport_tx, + server_handle, + rns_transport::messages::InterfaceRole::SharedServer, + ) + .await; + InstanceMode::Shared + } + Err(_) => { + let client_config = rns_interface::local::LocalClientConfig { + socket_path, + name: "SharedInstanceClient".to_string(), + }; + let client_id = next_id(&id_gen); + match rns_interface::local::spawn_local_client( + client_config, + client_id, + transport_tx.clone(), + ) + .await + { + Ok(client_handle) => { + let client_iface_id = client_handle.id; + register_interface_handle_with_role( + &transport_tx, + client_handle, + rns_transport::messages::InterfaceRole::SharedInstancePeer, + ) + .await; + let _ = transport_tx + .send(TransportMessage::SharedConnectionRestored { + interface_id: client_iface_id, + }) + .await; + InstanceMode::Client + } + Err(_) => InstanceMode::Standalone, + } + } + } + } + } + } else { + InstanceMode::Standalone + }; + + if instance_mode == InstanceMode::Client { + if rc.enable_transport + || rc.enable_remote_management + || rc.respond_to_probes + || rc.discover_interfaces + || rc.autoconnect_discovered_interfaces > 0 + || rc.publish_blackhole + || !rc.blackhole_sources.is_empty() + { + tracing::info!( + "shared-instance client mode suppresses local transport, management and discovery features" + ); + } + rc.enable_transport = false; + rc.enable_remote_management = false; + rc.respond_to_probes = false; + rc.discover_interfaces = false; + rc.autoconnect_discovered_interfaces = 0; + rc.publish_blackhole = false; + rc.blackhole_sources.clear(); + } + + // Rebroadcast / path forwarding / reverse-path proof routing requires + // explicit opt-in; otherwise rnsd behaves as a leaf. Shared-instance + // clients leave transport duties to their shared sibling. + if rc.enable_transport { + let _ = transport_tx.try_send(TransportMessage::SetTransportEnabled { enabled: true }); + tracing::info!("transport node mode enabled"); + } + + let interfaces = match synthesize_interfaces(&config, rc.panic_on_interface_error) { + Ok(interfaces) => interfaces, + Err(e) => { + let _ = transport_tx.send(TransportMessage::Shutdown).await; + return Err(e); + } + }; + if !interfaces.is_empty() { + tracing::info!("synthesized {} interfaces from config", interfaces.len()); + } + + let discovery_runtime = Arc::new(DiscoveryRuntime::default()); + if let Ok(store) = DiscoveryStore::open(&paths.storage_dir) { + *discovery_runtime.store.lock().await = Some(Arc::new(store)); + } + + // Client mode leaves hardware to the Shared sibling. + if instance_mode != InstanceMode::Client { + for iface_config in &interfaces { + let iface_id = next_id(&id_gen); + let post_init = get_post_init_for_config(&config, iface_config); + let discovery_config = discovery_config_for_interface( + &config, + iface_config, + &post_init, + rc.enable_transport, + ); + let bootstrap_only = interface_bootstrap_only(&config, iface_config); + let ifac_key = derive_ifac_key_from_post_init(&post_init); + + match spawn_interface( + iface_config, + iface_id, + transport_tx.clone(), + id_gen.clone(), + handle_tx.clone(), + &socket_base, + is_foreground.clone(), + ) + .await + { + Ok(iface_handles) => { + for iface_handle in iface_handles { + let registered_id = iface_handle.id; + register_interface_with_post_init( + &transport_tx, + iface_handle, + &post_init, + ifac_key, + ) + .await; + if let Some(ref cfg) = discovery_config { + discovery_runtime.local_interfaces.lock().await.push( + LocalDiscoveryInterface { + id: registered_id, + config: cfg.clone(), + }, + ); + } + if bootstrap_only { + discovery_runtime + .bootstrap_interfaces + .lock() + .await + .push(registered_id); + } + } + } + Err(e) => { + if rc.panic_on_interface_error { + let _ = transport_tx.send(TransportMessage::Shutdown).await; + return Err(ReticulumError::Interface(e)); + } else { + tracing::warn!("failed to spawn interface: {}", e); + } + } + } + } + } + + { + let reg_tx = transport_tx.clone(); + tokio::spawn(async move { + while let Some(sub_handle) = handle_rx.recv().await { + let role = if sub_handle.name.starts_with("SharedInstanceServer/") { + rns_transport::messages::InterfaceRole::LocalClient + } else { + rns_transport::messages::InterfaceRole::Normal + }; + register_interface_handle_with_role(®_tx, sub_handle, role).await; + } + }); + } + + let handle = ReticulumHandle { + transport_tx: transport_tx.clone(), + config_dir: config_dir.clone(), + instance_mode, + interface_configs: interfaces, + id_gen: id_gen.clone(), + handle_tx: handle_tx.clone(), + socket_base: socket_base.clone(), + config: rc.clone(), + is_foreground, + shutdown: shutdown.clone(), + transport_identity: transport_identity.clone(), + network_identity: network_identity.clone(), + discovery: discovery_runtime, + }; + + if instance_mode != InstanceMode::Client && rc.publish_blackhole { + match start_blackhole_publisher(&handle).await { + Ok(dest) => tracing::info!(dest = %hex::encode(dest), "blackhole publisher started"), + Err(e) => tracing::warn!("failed to start blackhole publisher: {}", e), + } + } + if instance_mode != InstanceMode::Client && !rc.blackhole_sources.is_empty() { + start_blackhole_subscriber(handle.clone()).await; + } + + tokio::spawn(async move { + shutdown_clone.wait().await; + let _ = shutdown_tx.send(TransportMessage::Shutdown).await; + }); + + if instance_mode != InstanceMode::Client { + let job_tx = transport_tx.clone(); + let cache_dir = paths.cache_dir.clone(); + let job_shutdown = shutdown.clone(); + tokio::spawn(async move { + run_jobs(job_tx, cache_dir, job_shutdown).await; + }); + } + + // RPC server runs only on Shared; CLI clients authenticate against `rpc_key`. + if instance_mode == InstanceMode::Shared + && let Some(rpc_key) = rc.rpc_key.clone() + { + let rpc_tx = transport_tx.clone(); + let rpc_shutdown = shutdown.clone(); + if rc.shared_instance_type == SharedInstanceType::Unix { + let rpc_socket = shared_unix_rpc_socket_path(&rc.instance_name, &socket_base); + tokio::spawn(async move { + if let Err(e) = crate::rpc_server::run_unix_rpc_server( + &rpc_socket, + rpc_key, + rpc_tx, + rpc_shutdown, + ) + .await + { + tracing::warn!("Unix RPC server error: {}", e); + } + }); + } else { + let rpc_port = rc.control_port; + tokio::spawn(async move { + if let Err(e) = + crate::rpc_server::run_rpc_server(rpc_port, rpc_key, rpc_tx, rpc_shutdown).await + { + tracing::warn!("RPC server error: {}", e); + } + }); + } + } + + if instance_mode != InstanceMode::Client && rc.enable_remote_management { + // Persist so the destination hash stays stable across restarts. + let mgmt_path = paths.storage_dir.join("remote_management_identity"); + let mgmt_identity = match rns_identity::identity::Identity::from_file(&mgmt_path) { + Ok(id) => id, + Err(_) => { + let id = rns_identity::identity::Identity::new(); + if let Err(e) = id.to_file(&mgmt_path) { + tracing::warn!(path = %mgmt_path.display(), error = %e, + "failed to persist remote management identity — destination hash will change on restart"); + } + id + } + }; + + // Drop wrong-length entries with a warning so a single typo doesn't disable management. + let allowed: Vec<[u8; 16]> = rc + .remote_management_allowed + .iter() + .filter_map(|v| <[u8; 16]>::try_from(v.as_slice()).ok()) + .collect(); + if allowed.len() < rc.remote_management_allowed.len() { + tracing::warn!( + ignored = rc.remote_management_allowed.len() - allowed.len(), + "remote_management_allowed: ignored entries with wrong hash length" + ); + } + if allowed.is_empty() { + tracing::warn!( + "remote management enabled with an empty allow-list; all remote management requests will be denied" + ); + } + + match crate::remote_management::start_remote_management( + transport_tx.clone(), + &mgmt_identity, + allowed, + ) + .await + { + Ok(dest) => { + tracing::info!(dest = %hex::encode(dest), "remote management started"); + } + Err(e) => { + tracing::warn!("failed to start remote management: {}", e); + } + } + } + + // `respond_to_probes = Yes` registers `rnstransport.probe` (PROVE_ALL). + if instance_mode != InstanceMode::Client && rc.respond_to_probes { + let probe_path = paths.storage_dir.join("probe_identity"); + let probe_identity = match rns_identity::identity::Identity::from_file(&probe_path) { + Ok(id) => id, + Err(_) => { + let id = rns_identity::identity::Identity::new(); + if let Err(e) = id.to_file(&probe_path) { + tracing::warn!(path = %probe_path.display(), error = %e, + "failed to persist probe identity — destination hash will change on restart"); + } + id + } + }; + match crate::probe::spawn_probe_responder( + transport_tx.clone(), + probe_identity, + crate::probe::default_probe_app_name(), + ) + .await + { + Ok(dest) => { + tracing::info!(dest = %hex::encode(dest), "probe responder started"); + } + Err(e) => { + tracing::warn!("failed to start probe responder: {}", e); + } + } + } + + let _ = INSTANCE.set(handle.clone()); + + Ok(handle) +} + +fn next_id(id_gen: &Arc) -> u64 { + id_gen.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +/// Preserve Python Reticulum's six interface modes in the transport actor. +/// Full and point-to-point currently share gateway's forwarding policy, but +/// retaining the variants keeps stats/RPC and future policy changes honest. +fn convert_mode( + mode: rns_interface::traits::InterfaceMode, +) -> rns_transport::constants::InterfaceMode { + match mode { + rns_interface::traits::InterfaceMode::AccessPoint => { + rns_transport::constants::InterfaceMode::AccessPoint + } + rns_interface::traits::InterfaceMode::Roaming => { + rns_transport::constants::InterfaceMode::Roaming + } + rns_interface::traits::InterfaceMode::Boundary => { + rns_transport::constants::InterfaceMode::Boundary + } + rns_interface::traits::InterfaceMode::Gateway => { + rns_transport::constants::InterfaceMode::Gateway + } + rns_interface::traits::InterfaceMode::Full => rns_transport::constants::InterfaceMode::Full, + rns_interface::traits::InterfaceMode::PointToPoint => { + rns_transport::constants::InterfaceMode::PointToPoint + } + } +} + +/// Must use `send().await`, not `try_send`: dropping the registration on a +/// full channel leaves a spawned interface that never receives traffic. +async fn register_interface_handle( + transport_tx: &mpsc::Sender, + handle: rns_interface::traits::InterfaceHandle, +) { + register_interface_handle_with_role( + transport_tx, + handle, + rns_transport::messages::InterfaceRole::Normal, + ) + .await; +} + +/// Must use `send().await`, not `try_send`: dropping the registration on a +/// full channel leaves a spawned interface that never receives traffic. +async fn register_interface_handle_with_role( + transport_tx: &mpsc::Sender, + handle: rns_interface::traits::InterfaceHandle, + role: rns_transport::messages::InterfaceRole, +) { + let name = handle.name.clone(); + let id = handle.id; + // Stash the driver task so `teardown_interface` can abort it; drop alone only detaches. + interface_tasks() + .lock() + .expect("interface_tasks mutex poisoned") + .insert(id, handle.read_task); + let entry = rns_transport::messages::InterfaceEntry { + name: handle.name.clone(), + mode: convert_mode(handle.mode), + role, + direction: rns_transport::constants::InterfaceDirection { + inbound: handle.direction.inbound, + outbound: handle.direction.outbound, + }, + bitrate: handle.bitrate, + mtu: handle.mtu, + tx: handle.tx, + ifac_key: None, + ifac_size: 0, + announce_cap: ANNOUNCE_CAP, + announce_allowed_at: 0.0, + announce_rate_target: None, + announce_rate_grace: None, + announce_rate_penalty: None, + online: Some(handle.online), + rxb: handle.rxb, + txb: handle.txb, + tx_drops: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), + ingress: rns_transport::ingress::IngressController::new(), + announce_queue: Vec::new(), + }; + if let Err(e) = transport_tx + .send(TransportMessage::RegisterInterface { id, entry }) + .await + { + tracing::error!(name = %name, id, error = %e, "RegisterInterface failed — transport actor gone"); + } +} + +/// See [`register_interface_handle`] for `send().await` rationale. +async fn register_interface_with_post_init( + transport_tx: &mpsc::Sender, + handle: rns_interface::traits::InterfaceHandle, + post_init: &interface_factory::InterfacePostInit, + ifac_key: Option<[u8; 64]>, +) { + // Outbound = physical capability AND `outgoing` config flag. + let direction = rns_transport::constants::InterfaceDirection { + inbound: handle.direction.inbound, + outbound: handle.direction.outbound && post_init.outgoing, + }; + let ingress = if !post_init.ingress_control { + rns_transport::ingress::IngressController::disabled() + } else if post_init.ingress_overrides.is_empty() { + rns_transport::ingress::IngressController::new() + } else { + rns_transport::ingress::IngressController::with_overrides(&post_init.ingress_overrides) + }; + let name = handle.name.clone(); + let id = handle.id; + interface_tasks() + .lock() + .expect("interface_tasks mutex poisoned") + .insert(id, handle.read_task); + let entry = rns_transport::messages::InterfaceEntry { + name: handle.name.clone(), + mode: convert_mode(handle.mode), + role: rns_transport::messages::InterfaceRole::Normal, + direction, + bitrate: post_init.bitrate.unwrap_or(handle.bitrate), + mtu: handle.mtu, + tx: handle.tx, + ifac_key, + ifac_size: post_init.ifac_size.unwrap_or(post_init.default_ifac_size), + announce_cap: post_init.announce_cap.unwrap_or(ANNOUNCE_CAP), + announce_allowed_at: 0.0, + announce_rate_target: post_init.announce_rate_target.map(|v| v as f64), + announce_rate_grace: post_init.announce_rate_grace, + announce_rate_penalty: post_init.announce_rate_penalty.map(|v| v as f64), + online: Some(handle.online), + rxb: handle.rxb, + txb: handle.txb, + tx_drops: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), + ingress, + announce_queue: Vec::new(), + }; + if let Err(e) = transport_tx + .send(TransportMessage::RegisterInterface { id, entry }) + .await + { + tracing::error!(name = %name, id, error = %e, "RegisterInterface failed — transport actor gone"); + } +} + +fn derive_ifac_key_from_post_init( + post_init: &interface_factory::InterfacePostInit, +) -> Option<[u8; 64]> { + if post_init.ifac_network_name.is_some() || post_init.ifac_passphrase.is_some() { + rns_identity::ifac::derive_ifac_key( + post_init.ifac_network_name.as_deref(), + post_init.ifac_passphrase.as_deref(), + ) + .ok() + } else { + None + } +} + +fn get_post_init_for_config( + config: &Config, + iface_config: &interface_factory::InterfaceConfig, +) -> interface_factory::InterfacePostInit { + let name = interface_config_name(iface_config); + let default_ifac_size = interface_factory::default_ifac_size_for(iface_config); + if let Some(section) = config.subsection("interfaces", name) { + return interface_factory::InterfacePostInit::from_section(section) + .with_default_ifac_size(default_ifac_size); + } + interface_factory::InterfacePostInit::from_section(&crate::config::ConfigSection::new()) + .with_default_ifac_size(default_ifac_size) +} + +fn interface_config_name(iface_config: &interface_factory::InterfaceConfig) -> &str { + match iface_config { + interface_factory::InterfaceConfig::TcpClient(c) => &c.name, + interface_factory::InterfaceConfig::TcpServer(c) => &c.name, + interface_factory::InterfaceConfig::Udp(c) => &c.name, + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::Serial(c) => &c.name, + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::KissSerial(c) => &c.name, + interface_factory::InterfaceConfig::Auto(c) => &c.name, + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::RNode(c) => &c.name, + interface_factory::InterfaceConfig::Local(c) => &c.name, + interface_factory::InterfaceConfig::I2P(c) => &c.name, + interface_factory::InterfaceConfig::Pipe(c) => &c.name, + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::RNodeMulti(c) => &c.name, + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::AX25KISS(c) => &c.name, + interface_factory::InterfaceConfig::Backbone(c) => &c.name, + #[cfg(feature = "ble")] + interface_factory::InterfaceConfig::BleRNode(c) => &c.name, + } +} + +fn interface_section<'a>( + config: &'a Config, + iface_config: &interface_factory::InterfaceConfig, +) -> Option<&'a ConfigSection> { + let name = interface_config_name(iface_config); + config.subsection("interfaces", name) +} + +fn interface_bootstrap_only( + config: &Config, + iface_config: &interface_factory::InterfaceConfig, +) -> bool { + interface_section(config, iface_config) + .and_then(|s| s.get_bool("bootstrap_only")) + .unwrap_or(false) +} + +fn discovery_config_for_interface( + config: &Config, + iface_config: &interface_factory::InterfaceConfig, + post_init: &interface_factory::InterfacePostInit, + transport_enabled: bool, +) -> Option { + let section = interface_section(config, iface_config)?; + if !section.get_bool("discoverable").unwrap_or(false) { + return None; + } + + let name = section + .get("discovery_name") + .unwrap_or_else(|| interface_config_name(iface_config)) + .to_string(); + + let (interface_type, reachable_on, port, frequency, bandwidth, spreading_factor, coding_rate) = + match iface_config { + interface_factory::InterfaceConfig::TcpServer(c) => ( + "TCPServerInterface", + configured_reachable_on(section).or_else(|| usable_listen_addr(&c.listen_ip)), + Some(c.listen_port), + None, + None, + None, + None, + ), + interface_factory::InterfaceConfig::TcpClient(c) if c.kiss_framing => ( + "TCPClientInterface", + configured_reachable_on(section).or_else(|| Some(c.target_host.clone())), + Some(c.target_port), + None, + None, + None, + None, + ), + interface_factory::InterfaceConfig::Backbone(c) => ( + "BackboneInterface", + configured_reachable_on(section).or_else(|| { + c.listen_on + .as_ref() + .and_then(|addr| usable_listen_addr(addr)) + .or_else(|| c.target_host.clone()) + }), + Some(c.port), + None, + None, + None, + None, + ), + interface_factory::InterfaceConfig::I2P(c) => ( + "I2PInterface", + configured_reachable_on(section).or_else(|| { + if c.connectable { + c.peers.first().cloned() + } else { + None + } + }), + None, + None, + None, + None, + None, + ), + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::RNode(c) => ( + "RNodeInterface", + configured_reachable_on(section), + None, + Some(c.frequency as u64), + Some(c.bandwidth as u64), + Some(c.spreading_factor), + Some(c.coding_rate), + ), + #[cfg(feature = "ble")] + interface_factory::InterfaceConfig::BleRNode(c) => ( + "RNodeInterface", + configured_reachable_on(section), + None, + Some(c.frequency as u64), + Some(c.bandwidth as u64), + Some(c.spreading_factor), + Some(c.coding_rate), + ), + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::KissSerial(_c) => ( + "KISSInterface", + configured_reachable_on(section), + None, + section.get_uint("discovery_frequency"), + section.get_uint("discovery_bandwidth"), + section + .get_uint("discovery_spreading_factor") + .map(|v| v.min(u8::MAX as u64) as u8), + section + .get_uint("discovery_coding_rate") + .map(|v| v.min(u8::MAX as u64) as u8), + ), + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::AX25KISS(_c) => ( + "KISSInterface", + configured_reachable_on(section), + None, + section.get_uint("discovery_frequency"), + section.get_uint("discovery_bandwidth"), + section + .get_uint("discovery_spreading_factor") + .map(|v| v.min(u8::MAX as u64) as u8), + section + .get_uint("discovery_coding_rate") + .map(|v| v.min(u8::MAX as u64) as u8), + ), + _ => return None, + }; + + let publish_ifac = section + .get_bool("discovery_publish_ifac") + .or_else(|| section.get_bool("publish_ifac")) + .unwrap_or(false); + + Some(DiscoveryInterfaceConfig { + interface_type: interface_type.to_string(), + discoverable: true, + name, + transport_enabled, + announce_interval_secs: discovery_announce_interval_secs(section), + stamp_value: section + .get_uint("discovery_stamp_value") + .or_else(|| section.get_uint("stamp_value")) + .map(|v| v.min(u8::MAX as u64) as u8) + .unwrap_or(rns_transport::discovery::DEFAULT_STAMP_VALUE), + reachable_on, + port, + ifac_netname: publish_ifac + .then(|| post_init.ifac_network_name.clone()) + .flatten(), + ifac_netkey: publish_ifac + .then(|| post_init.ifac_passphrase.clone()) + .flatten(), + frequency: section.get_uint("discovery_frequency").or(frequency), + bandwidth: section.get_uint("discovery_bandwidth").or(bandwidth), + spreading_factor: section + .get_uint("discovery_spreading_factor") + .map(|v| v.min(u8::MAX as u64) as u8) + .or(spreading_factor), + coding_rate: section + .get_uint("discovery_coding_rate") + .map(|v| v.min(u8::MAX as u64) as u8) + .or(coding_rate), + modulation: section.get("discovery_modulation").map(ToString::to_string), + channel: section + .get_uint("discovery_channel") + .map(|v| v.min(u16::MAX as u64) as u16), + latitude: section + .get_float("discovery_latitude") + .or_else(|| section.get_float("latitude")) + .unwrap_or(0.0), + longitude: section + .get_float("discovery_longitude") + .or_else(|| section.get_float("longitude")) + .unwrap_or(0.0), + height: section + .get_float("discovery_height") + .or_else(|| section.get_float("height")) + .unwrap_or(0.0), + encrypt: section.get_bool("discovery_encrypt").unwrap_or(false), + signed: false, + }) +} + +fn configured_reachable_on(section: &ConfigSection) -> Option { + section + .get("discovery_reachable_on") + .or_else(|| section.get("reachable_on")) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +fn usable_listen_addr(addr: &str) -> Option { + let trimmed = addr.trim(); + if trimmed.is_empty() || trimmed == "0.0.0.0" || trimmed == "::" { + None + } else { + Some(trimmed.to_string()) + } +} + +fn discovery_announce_interval_secs(section: &ConfigSection) -> u64 { + if let Some(seconds) = section.get_uint("discovery_announce_interval_secs") { + return seconds.max(1); + } + section + .get_float("discovery_announce_interval") + .or_else(|| section.get_float("announce_interval")) + .map(|minutes| (minutes.max(0.0) * 60.0).round().max(1.0) as u64) + .unwrap_or(6 * 60 * 60) +} + +struct IdentityDiscoveryDecryptor { + identity: Arc, +} + +impl DiscoveryDecryptor for IdentityDiscoveryDecryptor { + fn decrypt(&self, ciphertext: &[u8]) -> Option> { + self.identity.decrypt(ciphertext, None, false).ok() + } +} + +async fn start_on_network_discovery(handle: ReticulumHandle) { + let stamper = handle.discovery.stamper.lock().await.clone(); + let Some(stamper) = stamper else { + return; + }; + let store = handle.discovery.store.lock().await.clone(); + let Some(store) = store else { + return; + }; + + if handle.config.discover_interfaces { + let mut started = handle.discovery.receiver_started.lock().await; + if !*started { + *started = true; + drop(started); + + let (observer_tx, observer_rx) = if handle.config.autoconnect_discovered_interfaces > 0 + { + let (tx, rx) = mpsc::channel(128); + (Some(tx), Some(rx)) + } else { + (None, None) + }; + let decryptor = handle.network_identity.as_ref().map(|identity| { + Arc::new(IdentityDiscoveryDecryptor { + identity: identity.clone(), + }) as Arc + }); + let receiver_config = ReceiverConfig { + stamper: stamper.clone(), + store: store.clone(), + required_value: handle.config.discover_interfaces_required_value, + discovery_sources: (!handle.config.interface_discovery_sources.is_empty()) + .then(|| handle.config.interface_discovery_sources.clone()), + decryptor, + observer: observer_tx, + }; + let (_join, callback_tx) = rns_transport::discovery::receiver::spawn(receiver_config); + let _ = handle + .transport_tx + .send(TransportMessage::RegisterAnnounceHandler { + aspect_filter: Some( + rns_transport::discovery::DISCOVERY_ASPECT_FILTER.to_string(), + ), + receive_path_responses: false, + callback_tx, + }) + .await; + + if let Some(rx) = observer_rx { + let observer_handle = handle.clone(); + tokio::spawn(async move { + run_discovery_autoconnect(observer_handle, rx).await; + }); + } + } + } + + let locals = handle.discovery.local_interfaces.lock().await.clone(); + if !locals.is_empty() { + let mut started = handle.discovery.announcer_started.lock().await; + if !*started { + *started = true; + drop(started); + tokio::spawn(async move { + run_discovery_announcer(handle, stamper, locals).await; + }); + } + } +} + +async fn run_discovery_announcer( + handle: ReticulumHandle, + stamper: Arc, + locals: Vec, +) { + let mut announcer = Announcer::new(stamper); + for local in locals { + announcer.register(local.id, handle.transport_identity.hash, local.config); + } + + let announce_identity = handle + .network_identity + .clone() + .unwrap_or_else(|| handle.transport_identity.clone()); + let encrypt_identity = handle.network_identity.clone(); + let tick_interval = Duration::from_secs(rns_transport::discovery::ANNOUNCE_JOB_INTERVAL_SECS); + + loop { + let encrypt = |plaintext: &[u8]| { + encrypt_identity + .as_ref() + .and_then(|identity| identity.encrypt(plaintext, None).ok()) + }; + let (requests, _skips) = announcer.tick(unix_now(), Some(&encrypt)); + for request in requests { + match build_announce_packet( + &announce_identity, + rns_transport::discovery::DISCOVERY_ASPECT_FILTER, + Some(&request.app_data), + ) { + Ok(raw) => { + let _ = handle + .transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: + rns_identity::destination::Destination::hash_from_name_and_identity( + rns_transport::discovery::DISCOVERY_ASPECT_FILTER, + Some(&announce_identity.hash), + ), + })) + .await; + } + Err(e) => { + tracing::warn!(error = %e, "failed to build discovery announce"); + } + } + } + + tokio::select! { + _ = handle.shutdown.wait() => break, + _ = tokio::time::sleep(tick_interval) => {} + } + } +} + +async fn run_discovery_autoconnect( + handle: ReticulumHandle, + mut rx: mpsc::Receiver, +) { + if let Some(store) = handle.discovery.store.lock().await.clone() { + let sources = if handle.config.interface_discovery_sources.is_empty() { + None + } else { + Some(handle.config.interface_discovery_sources.as_slice()) + }; + for record in store.list(sources).unwrap_or_default() { + maybe_autoconnect_discovered(&handle, record).await; + } + } + + loop { + tokio::select! { + Some(record) = rx.recv() => { + maybe_autoconnect_discovered(&handle, record).await; + } + _ = handle.shutdown.wait() => break, + } + } +} + +async fn maybe_autoconnect_discovered(handle: &ReticulumHandle, record: DiscoveredInterface) { + let limit = handle.config.autoconnect_discovered_interfaces; + if limit == 0 { + return; + } + if !matches!( + record.info.interface_type.as_str(), + "BackboneInterface" | "TCPServerInterface" + ) { + return; + } + let Some(host) = record.info.reachable_on.clone() else { + return; + }; + let Some(port) = record.info.port else { + return; + }; + + let key = discovery_hash(&record.info.transport_id, &record.info.name); + { + let mut connected = handle.discovery.autoconnected.lock().await; + if connected.contains_key(&key) || connected.len() >= limit { + return; + } + connected.insert(key, u64::MAX); + } + + match spawn_discovered_backbone_client(handle, &record, &host, port).await { + Ok(id) => { + handle.discovery.autoconnected.lock().await.insert(key, id); + maybe_teardown_bootstrap_interfaces(handle).await; + } + Err(e) => { + handle.discovery.autoconnected.lock().await.remove(&key); + tracing::warn!( + name = %record.info.name, + endpoint = %format!("{host}:{port}"), + error = %e, + "failed to auto-connect discovered interface" + ); + } + } +} + +async fn spawn_discovered_backbone_client( + handle: &ReticulumHandle, + record: &DiscoveredInterface, + host: &str, + port: u16, +) -> Result { + let id = next_id(&handle.id_gen); + let name = format!( + "Discovered/{}", + record + .info + .name + .chars() + .map(|c| if c == '/' { '_' } else { c }) + .collect::() + ); + let config = rns_interface::backbone::BackboneClientConfig::new(&name, host, port); + let iface_handle = + rns_interface::backbone::spawn_backbone_client(config, id, handle.transport_tx.clone()) + .await + .map_err(|e| format!("Backbone client spawn failed: {e}"))?; + + let mut post_init = interface_factory::InterfacePostInit::from_section(&ConfigSection::new()) + .with_default_ifac_size(16); + post_init.ifac_network_name = record.info.ifac_netname.clone(); + post_init.ifac_passphrase = record.info.ifac_netkey.clone(); + let ifac_key = derive_ifac_key_from_post_init(&post_init); + register_interface_with_post_init(&handle.transport_tx, iface_handle, &post_init, ifac_key) + .await; + tracing::info!(name = %name, id, endpoint = %format!("{host}:{port}"), "auto-connected discovered interface"); + Ok(id) +} + +async fn maybe_teardown_bootstrap_interfaces(handle: &ReticulumHandle) { + let limit = handle.config.autoconnect_discovered_interfaces; + let connected = handle.discovery.autoconnected.lock().await.len(); + if limit == 0 || connected < limit { + return; + } + let ids = { + let mut bootstrap = handle.discovery.bootstrap_interfaces.lock().await; + if bootstrap.is_empty() { + return; + } + std::mem::take(&mut *bootstrap) + }; + for id in ids { + teardown_interface(handle, id).await; + } +} + +fn build_announce_packet( + identity: &Identity, + app_name: &str, + app_data: Option<&[u8]>, +) -> Result, String> { + let announce = rns_identity::announce::AnnounceData::create(identity, app_name, app_data, None) + .map_err(|e| e.to_string())?; + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&announce.pack()); + Ok(raw) +} + +async fn start_blackhole_publisher(handle: &ReticulumHandle) -> Result<[u8; 16], String> { + let identity = handle.transport_identity.clone(); + let signing_key = identity + .get_signing_key() + .ok_or_else(|| "No signing key available for blackhole publisher".to_string())?; + let app_name = rns_transport::discovery::BLACKHOLE_ASPECT_FILTER; + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let event_rx = + crate::link_manager::register_destination(&handle.transport_tx, dest_hash, app_name); + let mut lm = LinkManager::with_destination( + handle.transport_tx.clone(), + event_rx, + &identity, + app_name, + signing_key, + ); + + let list_hash = rns_crypto::sha::truncated_hash(b"/list"); + let publisher = identity.hash; + let query_tx = handle.transport_tx.clone(); + lm.set_request_handler(move |_link_id, path_hash, _data| { + if path_hash != list_hash { + return None; + } + match blocking_transport_query( + &query_tx, + TransportQuery::BuildBlackholeManifest { publisher }, + ) { + Some(TransportQueryResponse::Data(payload)) => Some(payload), + Some(TransportQueryResponse::Error(e)) => { + tracing::warn!(error = %e, "blackhole manifest build failed"); + None + } + _ => None, + } + }); + + let announce_tx = handle.transport_tx.clone(); + let announce_identity = identity.clone(); + lm.set_announce_handler(move || { + send_announce_try(&announce_tx, &announce_identity, app_name, None); + }); + + tokio::spawn(async move { + lm.run().await; + }); + + send_announce_try(&handle.transport_tx, &identity, app_name, None); + Ok(dest_hash) +} + +async fn start_blackhole_subscriber(handle: ReticulumHandle) { + let mut started = handle.discovery.subscriber_started.lock().await; + if *started { + return; + } + *started = true; + drop(started); + + let identity = match clone_identity(&handle.transport_identity) { + Some(identity) => identity, + None => { + tracing::warn!("blackhole subscriber requires a local identity with private keys"); + return; + } + }; + + tokio::spawn(async move { + let client = LinkClient::new(handle.transport_tx.clone(), identity); + tokio::select! { + _ = handle.shutdown.wait() => return, + _ = tokio::time::sleep(BLACKHOLE_INITIAL_WAIT) => {} + } + + let mut state = BlackholeSubscriberState::new(); + loop { + let sources: Vec = handle + .config + .blackhole_sources + .iter() + .copied() + .map(Into::into) + .collect(); + state.prune(&sources); + let now = unix_now(); + for source in state.due_sources(&sources, now) { + let source_hash = source.into_bytes(); + match client + .query( + source_hash, + rns_transport::discovery::BLACKHOLE_ASPECT_FILTER, + "/list", + Vec::new(), + 8, + BLACKHOLE_SOURCE_TIMEOUT, + ) + .await + { + Ok(payload) => { + match handle + .query_transport(TransportQuery::ApplyBlackholeManifest { payload }) + .await + { + Some(TransportQueryResponse::IntResult(applied)) => { + state.mark_updated(source, unix_now()); + tracing::debug!( + source = %hex::encode(source_hash), + applied, + "blackhole manifest applied" + ); + } + Some(TransportQueryResponse::Error(e)) => { + tracing::warn!( + source = %hex::encode(source_hash), + error = %e, + "blackhole manifest rejected" + ); + } + _ => {} + } + } + Err(e) => { + tracing::debug!( + source = %hex::encode(source_hash), + error = %e, + "blackhole manifest pull failed" + ); + } + } + } + + tokio::select! { + _ = handle.shutdown.wait() => break, + _ = tokio::time::sleep(BLACKHOLE_JOB_INTERVAL.min(BLACKHOLE_UPDATE_INTERVAL)) => {} + } + } + }); +} + +fn clone_identity(identity: &Identity) -> Option { + let private_key = identity.get_private_key()?; + Identity::from_private_key(&*private_key).ok() +} + +fn send_announce_try( + tx: &mpsc::Sender, + identity: &Identity, + app_name: &str, + app_data: Option<&[u8]>, +) { + let raw = match build_announce_packet(identity, app_name, app_data) { + Ok(raw) => raw, + Err(e) => { + tracing::warn!(error = %e, app_name, "failed to build announce"); + return; + } + }; + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let _ = tx.try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: dest_hash, + })); +} + +fn blocking_transport_query( + tx: &mpsc::Sender, + query: TransportQuery, +) -> Option { + let (resp_tx, resp_rx) = tokio::sync::oneshot::channel(); + if tx + .try_send(TransportMessage::Rpc { + query, + response_tx: resp_tx, + }) + .is_err() + { + return None; + } + tokio::task::block_in_place(|| resp_rx.blocking_recv().ok()) +} + +/// Spawn a TCP client interface at runtime; returns the interface ID. +pub async fn spawn_tcp_client_runtime( + handle: &ReticulumHandle, + name: &str, + host: &str, + port: u16, +) -> Result { + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let config = rns_interface::tcp::TcpClientConfig::new(name, host, port); + let iface_handle = + rns_interface::tcp::spawn_tcp_client(config, id, handle.transport_tx.clone(), None) + .await + .map_err(|e| format!("TCP client spawn failed: {e}"))?; + + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime TCP client interface spawned"); + Ok(id) +} + +/// Spawn a TCP server interface at runtime. +pub async fn spawn_tcp_server_runtime( + handle: &ReticulumHandle, + name: &str, + listen_ip: &str, + port: u16, +) -> Result { + let id = next_id(&handle.id_gen); + let config = rns_interface::tcp::TcpServerConfig::new(name, listen_ip, port); + let iface_handle = rns_interface::tcp::spawn_tcp_server( + config, + id, + handle.id_gen.clone(), + handle.transport_tx.clone(), + handle.handle_tx.clone(), + ) + .await + .map_err(|e| format!("TCP server spawn failed: {e}"))?; + + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime TCP server interface spawned"); + Ok(id) +} + +/// Spawn a Backbone (HDLC-over-TCP) client interface at runtime. +pub async fn spawn_backbone_client_runtime( + handle: &ReticulumHandle, + name: &str, + host: &str, + port: u16, + prefer_ipv6: bool, + connect_timeout: Option, + max_reconnect_tries: Option, +) -> Result { + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let mut config = rns_interface::backbone::BackboneClientConfig::new(name, host, port); + config.prefer_ipv6 = prefer_ipv6; + if let Some(t) = connect_timeout { + config.connect_timeout_secs = t; + } + config.max_reconnect_tries = max_reconnect_tries; + + let iface_handle = + rns_interface::backbone::spawn_backbone_client(config, id, handle.transport_tx.clone()) + .await + .map_err(|e| format!("Backbone client spawn failed: {e}"))?; + + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime Backbone client interface spawned"); + Ok(id) +} + +/// Spawn a Backbone (HDLC-over-TCP) server interface at runtime. +pub async fn spawn_backbone_server_runtime( + handle: &ReticulumHandle, + name: &str, + listen_ip: &str, + port: u16, + prefer_ipv6: bool, + device: Option<&str>, +) -> Result { + let id = next_id(&handle.id_gen); + let mut config = rns_interface::backbone::BackboneServerConfig::new(name, listen_ip, port); + config.prefer_ipv6 = prefer_ipv6; + config.device = device.map(ToString::to_string); + + let iface_handle = rns_interface::backbone::spawn_backbone_server( + config, + id, + handle.id_gen.clone(), + handle.transport_tx.clone(), + handle.handle_tx.clone(), + ) + .await + .map_err(|e| format!("Backbone server spawn failed: {e}"))?; + + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime Backbone server interface spawned"); + Ok(id) +} + +/// Returns `(interface_id, online_flag)`; `online_flag` flips to `true` +/// after the first successful connect. +#[cfg(feature = "ble")] +pub async fn spawn_ble_rnode_runtime( + handle: &ReticulumHandle, + name: &str, + port: &str, + frequency: u32, + bandwidth: u32, + spreading_factor: u8, + coding_rate: u8, + tx_power: i8, +) -> Result<(u64, std::sync::Arc), String> { + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let mut config = rns_interface::ble_rnode::BleRNodeConfig::new(name, port); + config.frequency = frequency; + config.bandwidth = bandwidth; + config.spreading_factor = spreading_factor; + config.coding_rate = coding_rate; + config.tx_power = tx_power as u8; + + let iface_handle = rns_interface::ble_rnode::spawn_ble_rnode_interface( + config, + id, + handle.transport_tx.clone(), + ) + .await + .map_err(|e| format!("BLE RNode spawn failed: {e}"))?; + + let online = iface_handle.online.clone(); + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime BLE RNode interface spawned"); + Ok((id, online)) +} + +/// Desktop USB-serial RNode counterpart to [`spawn_ble_rnode_runtime`]. +#[cfg(feature = "serial")] +/// Settings for a runtime-spawned USB-serial RNode interface. +pub struct RnodeRuntimeArgs<'a> { + /// Interface name registered with the transport actor. + pub name: &'a str, + /// Serial device path. + pub port: &'a str, + /// Radio frequency in Hz. + pub frequency: u32, + /// Radio bandwidth in Hz. + pub bandwidth: u32, + /// LoRa spreading factor. + pub spreading_factor: u8, + /// LoRa coding rate denominator. + pub coding_rate: u8, + /// Transmit power in dBm. + pub tx_power: i8, +} + +#[cfg(feature = "serial")] +pub async fn spawn_rnode_runtime( + handle: &ReticulumHandle, + args: RnodeRuntimeArgs<'_>, +) -> Result<(u64, std::sync::Arc), String> { + let RnodeRuntimeArgs { + name, + port, + frequency, + bandwidth, + spreading_factor, + coding_rate, + tx_power, + } = args; + + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let mut config = rns_interface::rnode::RNodeConfig::new(name, port); + config.frequency = frequency; + config.bandwidth = bandwidth; + config.spreading_factor = spreading_factor; + config.coding_rate = coding_rate; + config.tx_power = tx_power as u8; + + let iface_handle = + rns_interface::rnode::spawn_rnode_interface(config, id, handle.transport_tx.clone()) + .await + .map_err(|e| format!("RNode spawn failed: {e}"))?; + + let online = iface_handle.online.clone(); + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime RNode interface spawned"); + Ok((id, online)) +} + +/// Android bridge variant: Kotlin owns GATT, Rust connects via a local TCP socket. +#[cfg(feature = "ble")] +pub async fn spawn_ble_rnode_runtime_native( + handle: &ReticulumHandle, + name: &str, + port: &str, + frequency: u32, + bandwidth: u32, + spreading_factor: u8, + coding_rate: u8, + tx_power: i8, + tcp_port: u16, +) -> Result<(u64, std::sync::Arc), String> { + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let mut config = rns_interface::ble_rnode::BleRNodeConfig::new(name, port); + config.frequency = frequency; + config.bandwidth = bandwidth; + config.spreading_factor = spreading_factor; + config.coding_rate = coding_rate; + config.tx_power = tx_power as u8; + + let iface_handle = rns_interface::ble_rnode::spawn_ble_rnode_interface_native( + config, + id, + handle.transport_tx.clone(), + tcp_port, + ) + .await + .map_err(|e| format!("BLE RNode native spawn failed: {e}"))?; + + let online = iface_handle.online.clone(); + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, tcp_port, "runtime BLE RNode interface spawned (native bridge)"); + Ok((id, online)) +} + +/// Spawn an AutoInterface (local-network discovery) with a resolved config. +pub async fn spawn_auto_interface_runtime_with_config( + handle: &ReticulumHandle, + config: rns_interface::auto::AutoInterfaceConfig, +) -> Result { + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let name = config.name.clone(); + let iface_handle = rns_interface::auto::spawn_auto_interface( + config, + id, + handle.transport_tx.clone(), + handle.is_foreground.clone(), + ) + .await + .map_err(|e| format!("Auto interface spawn failed: {e}"))?; + + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime Auto interface spawned"); + Ok(id) +} + +/// Spawns an AutoInterface with defaults (Link scope, Temporary address, +/// no NIC filter, 10 Mbps bitrate); only the four positional knobs differ. +pub async fn spawn_auto_interface_runtime( + handle: &ReticulumHandle, + name: &str, + group_id: &str, + discovery_port: u16, + data_port: u16, +) -> Result { + let config = rns_interface::auto::AutoInterfaceConfig { + name: name.to_string(), + group_id: group_id.to_string(), + discovery_port, + data_port, + ..rns_interface::auto::AutoInterfaceConfig::default() + }; + spawn_auto_interface_runtime_with_config(handle, config).await +} + +/// `event_tx` is a process-singleton dispatcher; each call replaces the prior sender. +#[cfg(feature = "ble")] +pub async fn spawn_ble_peer_runtime( + handle: &ReticulumHandle, + name: &str, + identity_hash: Vec, + event_tx: Option>, + foreground_wake: std::sync::Arc, + seed_identities: Vec, +) -> Result { + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let config = rns_interface::ble_peer::BlePeerConfig::new(name, identity_hash); + + // Install before start so initial scan/connect events aren't dropped. + if let Some(tx) = event_tx { + rns_interface::ble_peer::install_event_dispatcher(tx); + } + + let iface_handle = rns_interface::ble_peer::spawn_ble_peer_interface( + config, + id, + handle.transport_tx.clone(), + handle.is_foreground.clone(), + foreground_wake, + seed_identities, + ) + .await + .map_err(|e| { + // Clear the dispatcher so a retry doesn't leak the orphaned channel. + rns_interface::ble_peer::clear_event_dispatcher(); + format!("BLE Peer spawn failed: {e}") + })?; + + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime BLE Peer mesh interface spawned"); + Ok(id) +} + +#[cfg(feature = "ble")] +pub fn teardown_ble_peer_events() { + rns_interface::ble_peer::clear_event_dispatcher(); +} + +/// Stop peripheral (advertising + GATT server), clear dispatcher, deregister. +#[cfg(feature = "ble")] +pub async fn teardown_ble_peer_interface(handle: &ReticulumHandle, id: u64) { + rns_interface::ble_peer::stop_ble_peer_interface().await; + teardown_interface(handle, id).await; +} + +/// Stop per-id reconnect loop, then deregister. Per-id (multiple BLE RNode +/// interfaces coexist, each with its own `AtomicBool`); idempotent. +#[cfg(feature = "ble")] +pub async fn teardown_ble_rnode_interface(handle: &ReticulumHandle, id: u64) { + rns_interface::ble_rnode::stop_ble_rnode_interface(id); + teardown_interface(handle, id).await; +} + +#[cfg(target_os = "android")] +pub async fn spawn_android_usb_rnode_runtime( + handle: &ReticulumHandle, + name: &str, + device_name: &str, + frequency: u32, + bandwidth: u32, + spreading_factor: u8, + coding_rate: u8, + tx_power: i8, +) -> Result { + let id = handle + .id_gen + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let mut config = rns_interface::android_usb::AndroidUsbConfig::new(name, device_name); + config.frequency = frequency; + config.bandwidth = bandwidth; + config.spreading_factor = spreading_factor; + config.coding_rate = coding_rate; + config.tx_power = tx_power as u8; + + let iface_handle = rns_interface::android_usb::spawn_android_usb_rnode_interface( + config, + id, + handle.transport_tx.clone(), + ) + .await + .map_err(|e| format!("Android USB spawn failed: {e}"))?; + + register_interface_handle(&handle.transport_tx, iface_handle).await; + tracing::info!(name = %name, id, "runtime Android USB RNode interface spawned"); + Ok(id) +} + +pub async fn teardown_interface(handle: &ReticulumHandle, id: u64) { + // Abort the driver task FIRST so loops stop accepting traffic; then + // deregister so the dropped tx cascades through writer/forwarder. + // Order matters: dereg-first would let the master task reconnect once + // before the abort lands. + if let Some(task) = interface_tasks() + .lock() + .expect("interface_tasks mutex poisoned") + .remove(&id) + { + task.abort(); + tracing::debug!(id, "interface driver task aborted"); + } + let _ = handle + .transport_tx + .send(TransportMessage::DeregisterInterface { id }) + .await; + tracing::info!(id, "interface deregistered"); +} + +async fn spawn_interface( + iface_config: &interface_factory::InterfaceConfig, + id: u64, + transport_tx: mpsc::Sender, + id_gen: Arc, + handle_tx: mpsc::Sender, + socket_base: &Path, + is_foreground: Arc, +) -> Result, String> { + match iface_config { + interface_factory::InterfaceConfig::TcpClient(c) => { + rns_interface::tcp::spawn_tcp_client(c.clone(), id, transport_tx, None) + .await + .map(|h| vec![h]) + .map_err(|e| format!("TCP client: {e}")) + } + interface_factory::InterfaceConfig::TcpServer(c) => { + rns_interface::tcp::spawn_tcp_server(c.clone(), id, id_gen, transport_tx, handle_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("TCP server: {e}")) + } + interface_factory::InterfaceConfig::Udp(c) => { + rns_interface::udp::spawn_udp_interface(c.clone(), id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("UDP: {e}")) + } + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::Serial(c) => { + let mut serial_config = rns_interface::serial::SerialConfig::new(&c.name, &c.port); + serial_config.baud_rate = c.baud_rate; + serial_config.mode = c.mode; + rns_interface::serial::spawn_serial_interface(serial_config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("Serial: {e}")) + } + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::KissSerial(c) => { + let mut kiss_config = + rns_interface::kiss_iface::KissInterfaceConfig::new(&c.name, &c.port, c.baud_rate); + kiss_config.mode = c.mode; + rns_interface::kiss_iface::spawn_kiss_interface(kiss_config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("KISS: {e}")) + } + interface_factory::InterfaceConfig::Auto(c) => { + let auto_config = rns_interface::auto::AutoInterfaceConfig { + name: c.name.clone(), + group_id: c.group_id.clone(), + discovery_scope: c.discovery_scope, + discovery_port: c.discovery_port, + data_port: c.data_port, + multicast_address_type: c.multicast_address_type, + devices: c.devices.clone(), + ignored_devices: c.ignored_devices.clone(), + configured_bitrate: c.configured_bitrate, + mode: c.mode, + }; + rns_interface::auto::spawn_auto_interface(auto_config, id, transport_tx, is_foreground) + .await + .map(|h| vec![h]) + .map_err(|e| format!("Auto: {e}")) + } + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::RNode(c) => { + let mut rnode_config = rns_interface::rnode::RNodeConfig::new(&c.name, &c.port); + rnode_config.frequency = c.frequency; + rnode_config.bandwidth = c.bandwidth; + rnode_config.spreading_factor = c.spreading_factor; + rnode_config.coding_rate = c.coding_rate; + rnode_config.tx_power = c.tx_power as u8; + rnode_config.mode = c.mode; + rns_interface::rnode::spawn_rnode_interface(rnode_config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("RNode: {e}")) + } + interface_factory::InterfaceConfig::Local(c) => { + let local_config = rns_interface::local::LocalClientConfig { + socket_path: socket_base + .join(format!("reticulum_rs_{}.sock", c.name)) + .to_string_lossy() + .to_string(), + name: c.name.clone(), + }; + rns_interface::local::spawn_local_client(local_config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("Local: {e}")) + } + interface_factory::InterfaceConfig::I2P(c) => { + if c.connectable { + let mut server_config = rns_interface::i2p::I2PServerConfig::new(&c.name); + server_config.sam_host = c.i2p_sam_host.clone(); + server_config.sam_port = c.i2p_sam_port; + server_config.mode = c.mode; + rns_interface::i2p::spawn_i2p_server(server_config, id_gen, transport_tx, handle_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("I2P server: {e}")) + } else if let Some(peer) = c.peers.first() { + let mut client_config = rns_interface::i2p::I2PClientConfig::new(&c.name, peer); + client_config.sam_host = c.i2p_sam_host.clone(); + client_config.sam_port = c.i2p_sam_port; + client_config.mode = c.mode; + rns_interface::i2p::spawn_i2p_client(client_config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("I2P client: {e}")) + } else { + Err(format!( + "I2PInterface '{}': requires 'connectable' or 'peers'", + c.name + )) + } + } + interface_factory::InterfaceConfig::Pipe(c) => { + let pipe_config = rns_interface::pipe::PipeInterfaceConfig { + name: c.name.clone(), + command: c.command.clone(), + respawn_delay: c.respawn_delay as f64, + mode: c.mode, + }; + rns_interface::pipe::spawn_pipe_interface(pipe_config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("Pipe: {e}")) + } + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::RNodeMulti(c) => { + let mut multi_config = + rns_interface::rnode_multi::RNodeMultiConfig::new(&c.name, &c.port); + multi_config.baud_rate = c.baud_rate; + multi_config.flow_control = c.flow_control; + for sub in &c.subinterfaces { + let mut sub_config = rns_interface::rnode_multi::SubInterfaceConfig::new( + &sub.name, + sub.vport, + sub.frequency, + ); + sub_config.bandwidth = sub.bandwidth; + sub_config.spreading_factor = sub.spreading_factor; + sub_config.coding_rate = sub.coding_rate; + sub_config.tx_power = sub.tx_power; + sub_config.mode = sub.mode; + sub_config.flow_control = sub.flow_control; + sub_config.outgoing = sub.outgoing; + sub_config.st_alock = sub.st_alock; + sub_config.lt_alock = sub.lt_alock; + multi_config.subinterfaces.push(sub_config); + } + if multi_config.subinterfaces.is_empty() { + return Err(format!( + "RNodeMultiInterface '{}': no sub-interfaces configured", + c.name + )); + } + let mut sub_ids = Vec::with_capacity(multi_config.subinterfaces.len()); + sub_ids.push(id); + for _ in 1..multi_config.subinterfaces.len() { + sub_ids.push(id_gen.fetch_add(1, std::sync::atomic::Ordering::SeqCst)); + } + rns_interface::rnode_multi::spawn_rnode_multi_interface( + multi_config, + &sub_ids, + transport_tx, + ) + .await + .map_err(|e| format!("RNodeMulti: {e}")) + } + #[cfg(feature = "serial")] + interface_factory::InterfaceConfig::AX25KISS(c) => { + let ax25_config = + rns_interface::ax25kiss::AX25KISSConfig::new(&c.name, &c.port, &c.callsign, c.ssid); + let mut ax25_config = ax25_config; + ax25_config.baud_rate = c.baud_rate; + ax25_config.preamble = c.preamble as u16; + ax25_config.txtail = c.txtail as u16; + ax25_config.persistence = c.persistence as u8; + ax25_config.slottime = c.slottime as u16; + ax25_config.flow_control = c.flow_control; + ax25_config.mode = c.mode; + rns_interface::ax25kiss::spawn_ax25kiss_interface(ax25_config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("AX25KISS: {e}")) + } + #[cfg(feature = "ble")] + interface_factory::InterfaceConfig::BleRNode(c) => { + let mut config = rns_interface::ble_rnode::BleRNodeConfig::new(&c.name, &c.port); + config.frequency = c.frequency; + config.bandwidth = c.bandwidth; + config.spreading_factor = c.spreading_factor; + config.coding_rate = c.coding_rate; + config.tx_power = c.tx_power as u8; + config.mode = c.mode; + rns_interface::ble_rnode::spawn_ble_rnode_interface(config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("BLE RNode: {e}")) + } + interface_factory::InterfaceConfig::Backbone(c) => { + // `target_host` selects client mode; otherwise listen. + if let Some(host) = c.target_host.as_deref() { + let mut config = + rns_interface::backbone::BackboneClientConfig::new(&c.name, host, c.port); + config.mode = c.mode; + config.prefer_ipv6 = c.prefer_ipv6; + config.connect_timeout_secs = c.connect_timeout; + config.max_reconnect_tries = c.max_reconnect_tries; + rns_interface::backbone::spawn_backbone_client(config, id, transport_tx) + .await + .map(|h| vec![h]) + .map_err(|e| format!("Backbone client: {e}")) + } else { + let listen_ip = c.listen_on.as_deref().unwrap_or("0.0.0.0"); + let mut config = + rns_interface::backbone::BackboneServerConfig::new(&c.name, listen_ip, c.port); + config.mode = c.mode; + config.prefer_ipv6 = c.prefer_ipv6; + config.device = c.device.clone(); + rns_interface::backbone::spawn_backbone_server( + config, + id, + id_gen, + transport_tx, + handle_tx, + ) + .await + .map(|h| vec![h]) + .map_err(|e| format!("Backbone server: {e}")) + } + } + } +} + +pub fn get_instance() -> Option<&'static ReticulumHandle> { + INSTANCE.get() +} + +fn load_or_create_config(path: &Path) -> Result<(Config, bool), ReticulumError> { + if path.exists() { + Config::from_file(path) + .map(|config| (config, false)) + .map_err(ReticulumError::Config) + } else { + Config::write_default(path).map_err(ReticulumError::Config)?; + Config::parse(Config::default_config()) + .map(|config| (config, true)) + .map_err(ReticulumError::Config) + } +} + +fn load_or_create_network_identity(path: &Path) -> Result, ReticulumError> { + let identity = if path.is_file() { + Identity::from_file(path).map_err(|e| { + ReticulumError::Config(ConfigError::InvalidValue { + section: "reticulum".to_string(), + key: "network_identity".to_string(), + message: format!("could not load {}: {e}", path.display()), + }) + })? + } else { + let identity = Identity::new(); + identity.to_file(path).map_err(|e| { + ReticulumError::Config(ConfigError::InvalidValue { + section: "reticulum".to_string(), + key: "network_identity".to_string(), + message: format!("could not generate {}: {e}", path.display()), + }) + })?; + identity + }; + + Ok(Arc::new(identity)) +} + +fn synthesize_interfaces( + config: &Config, + panic_on_interface_error: bool, +) -> Result, ReticulumError> { + let mut interfaces = Vec::new(); + + for (name, section) in config.subsections("interfaces") { + match interface_factory::synthesize_interface(name, section) { + Ok(iface) => { + tracing::info!("configured interface: {name}"); + interfaces.push(iface); + } + Err(interface_factory::InterfaceFactoryError::Disabled(_)) => { + tracing::debug!("interface {name} is disabled"); + } + Err(e) => { + if panic_on_interface_error { + return Err(ReticulumError::Interface(format!( + "failed to synthesize interface {name}: {e}" + ))); + } else { + tracing::warn!("failed to synthesize interface {name}: {e}"); + } + } + } + } + + Ok(interfaces) +} + +async fn run_jobs( + transport_tx: mpsc::Sender, + cache_dir: PathBuf, + shutdown: ShutdownSignal, +) { + let mut scheduler = JobScheduler::new(); + let mut interval = tokio::time::interval(std::time::Duration::from_secs(JOB_INTERVAL)); + + loop { + tokio::select! { + _ = interval.tick() => { + let jobs = scheduler.tick(); + for job in jobs { + match job { + Job::CleanCache => { + tracing::debug!("running cache cleanup"); + clean_cache(&cache_dir); + } + Job::PersistData => { + tracing::debug!("persisting data"); + let _ = transport_tx.send(TransportMessage::Tick( + rns_transport::messages::TimerTick { + timestamp: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(), + }, + )).await; + } + } + } + } + _ = shutdown.wait() => { + tracing::info!("background jobs shutting down"); + break; + } + } + } +} + +fn clean_cache(cache_dir: &Path) { + let cache_ttl = std::time::Duration::from_secs(RESOURCE_CACHE); + let now = std::time::SystemTime::now(); + + if let Ok(entries) = std::fs::read_dir(cache_dir) { + for entry in entries.flatten() { + if let Ok(metadata) = entry.metadata() + && metadata.is_file() + && let Ok(modified) = metadata.modified() + && let Ok(age) = now.duration_since(modified) + && age > cache_ttl + { + let path = entry.path(); + if std::fs::remove_file(&path).is_ok() { + tracing::trace!("cleaned cache entry: {}", path.display()); + } + } + } + } +} + +fn hex_decode(s: &str) -> Option> { + if !s.len().is_multiple_of(2) { + return None; + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) + .collect() +} + +#[derive(Debug, thiserror::Error)] +pub enum ReticulumError { + #[error("config error: {0}")] + Config(#[from] ConfigError), + #[error("I/O error: {0}")] + Io(std::io::Error), + #[error("already initialized")] + AlreadyInitialized, + #[error("transport error: {0}")] + Transport(String), + #[error("interface error: {0}")] + Interface(String), +} + +#[cfg(test)] +mod tests { + use super::*; + + fn make_plain_data_packet(dest_hash: [u8; 16], body: &[u8]) -> bytes::Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Plain, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(body); + bytes::Bytes::from(raw) + } + + #[test] + fn test_default_config() { + let rc = ReticulumConfig::default(); + assert!(rc.share_instance); + assert_eq!(rc.instance_name, "default"); + assert_eq!(rc.shared_instance_port, 37428); + assert_eq!(rc.control_port, 37429); + assert!(!rc.enable_transport); + assert!(rc.use_implicit_proof); + assert_eq!(rc.loglevel, 4); + } + + #[test] + fn test_config_from_default_file() { + let config = Config::parse(Config::default_config()).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert!(rc.share_instance); + assert_eq!(rc.shared_instance_port, 37428); + assert_eq!(rc.loglevel, 4); + } + + #[test] + fn test_config_custom_values() { + let input = r#" +[reticulum] +share_instance = No +instance_name = testnode +shared_instance_port = 12345 +instance_control_port = 12346 +enable_transport = Yes +respond_to_probes = Yes +use_implicit_proof = No + +[logging] +loglevel = 7 +"#; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert!(!rc.share_instance); + assert_eq!(rc.instance_name, "testnode"); + assert_eq!(rc.shared_instance_port, 12345); + assert_eq!(rc.control_port, 12346); + assert!(rc.enable_transport); + assert!(rc.respond_to_probes); + assert!(!rc.use_implicit_proof); + assert_eq!(rc.loglevel, 7); + } + + #[test] + fn test_shared_instance_type_explicit_tcp() { + let input = "[reticulum]\nshared_instance_type = tcp\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!(rc.shared_instance_type, SharedInstanceType::Tcp); + } + + #[test] + fn test_shared_instance_type_explicit_unix() { + let input = "[reticulum]\nshared_instance_type = Unix\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!(rc.shared_instance_type, SharedInstanceType::Unix); + } + + #[test] + fn test_shared_instance_type_invalid_keeps_default() { + let input = "[reticulum]\nshared_instance_type = bogus\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!( + rc.shared_instance_type, + SharedInstanceType::platform_default() + ); + } + + #[test] + fn test_shared_tcp_client_config_has_no_reconnect_cap() { + let config = shared_tcp_client_config(12345); + assert_eq!(config.name, "SharedInstanceClient"); + assert_eq!(config.target_host, "127.0.0.1"); + assert_eq!(config.target_port, 12345); + assert_eq!(config.max_reconnect_tries, None); + } + + #[test] + fn test_force_shared_instance_bitrate_parsed() { + let input = "[reticulum]\nforce_shared_instance_bitrate = 1000000\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!(rc.force_shared_instance_bitrate, Some(1_000_000)); + } + + #[test] + fn test_force_shared_instance_bitrate_absent() { + let input = "[reticulum]\nshare_instance = Yes\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!(rc.force_shared_instance_bitrate, None); + } + + #[test] + fn test_instance_mode_variants() { + assert_ne!(InstanceMode::Shared, InstanceMode::Client); + assert_ne!(InstanceMode::Client, InstanceMode::Standalone); + } + + fn dummy_handle() -> ReticulumHandle { + let (tx, _rx) = mpsc::channel::(1); + let (htx, _hrx) = mpsc::channel::(1); + ReticulumHandle { + transport_tx: tx, + config_dir: PathBuf::from("/tmp/dummy"), + instance_mode: InstanceMode::Standalone, + interface_configs: Vec::new(), + id_gen: Arc::new(AtomicU64::new(0)), + handle_tx: htx, + socket_base: PathBuf::from("/tmp/dummy"), + config: ReticulumConfig::default(), + is_foreground: Arc::new(AtomicBool::new(true)), + shutdown: ShutdownSignal::new(), + transport_identity: Arc::new(Identity::new()), + network_identity: None, + discovery: Arc::new(DiscoveryRuntime::default()), + } + } + + struct StaticStamper; + impl DiscoveryStamper for StaticStamper { + fn generate(&self, _infohash: &[u8; 32], _target_value: u8) -> Option> { + Some(vec![0xAB; 32]) + } + fn value(&self, _infohash: &[u8; 32], _stamp: &[u8]) -> u8 { + 16 + } + fn valid(&self, _infohash: &[u8; 32], _stamp: &[u8], required_value: u8) -> bool { + required_value <= 16 + } + } + + #[tokio::test] + async fn discovery_disabled_by_default() { + let h = dummy_handle(); + assert!(!h.discovery_enabled().await); + assert!(h.discovered_interfaces().await.is_empty()); + assert!(h.blackhole_sources().is_empty()); + } + + #[tokio::test] + async fn enable_on_network_discovery_installs_stamper() { + let h = dummy_handle(); + h.enable_on_network_discovery(Arc::new(StaticStamper)).await; + assert!(h.discovery_enabled().await); + } + + #[tokio::test] + async fn enable_overrides_previous_stamper_without_error() { + let h = dummy_handle(); + h.enable_on_network_discovery(Arc::new(StaticStamper)).await; + h.enable_on_network_discovery(Arc::new(StaticStamper)).await; + assert!(h.discovery_enabled().await); + } + + #[tokio::test] + async fn discovered_interfaces_reads_from_installed_store() { + let dir = std::env::temp_dir().join(format!( + "reticulum_rs_runtime_discovery_store_{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let h = dummy_handle(); + h.install_discovery_store_for_tests(store.clone()).await; + + let v = h.discovered_interfaces().await; + assert_eq!(v.len(), 0); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn blackhole_sources_surfaces_config_value() { + let mut h = dummy_handle(); + h.config.blackhole_sources = vec![[0xAA; 16], [0xBB; 16]]; + assert_eq!(h.blackhole_sources().len(), 2); + assert_eq!(h.blackhole_sources()[0], [0xAA; 16]); + } + + #[test] + fn test_discovery_defaults_are_off() { + let rc = ReticulumConfig::default(); + assert!(!rc.discover_interfaces); + assert_eq!(rc.autoconnect_discovered_interfaces, 0); + assert_eq!(rc.discover_interfaces_required_value, 14); + assert_eq!(rc.network_identity_path, None); + assert!(rc.interface_discovery_sources.is_empty()); + assert!(rc.blackhole_sources.is_empty()); + assert!(!rc.publish_blackhole); + assert!(rc.bootstrap_configs.is_empty()); + } + + #[test] + fn test_discovery_keys_parsed() { + let input = "[reticulum]\n\ + discover_interfaces = Yes\n\ + autoconnect_discovered_interfaces = 2\n\ + required_discovery_value = 16\n\ + interface_discovery_sources = 521c87a83afb8f29e4455e77930b973b\n\ + publish_blackhole = Yes\n\ + network_identity = /opt/rnsd/network.identity\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert!(rc.discover_interfaces); + assert_eq!(rc.autoconnect_discovered_interfaces, 2); + assert_eq!(rc.discover_interfaces_required_value, 16); + assert_eq!(rc.interface_discovery_sources.len(), 1); + assert!(rc.publish_blackhole); + assert_eq!( + rc.network_identity_path, + Some(PathBuf::from("/opt/rnsd/network.identity")) + ); + } + + #[test] + fn test_network_identity_path_follows_python_expanduser_only_policy() { + let config = Config::parse("[reticulum]\nnetwork_identity = network.identity\n").unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!( + rc.network_identity_path, + Some(PathBuf::from("network.identity")) + ); + + if let Ok(home) = std::env::var("HOME") { + let config = + Config::parse("[reticulum]\nnetwork_identity = ~/network.identity\n").unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!( + rc.network_identity_path, + Some(PathBuf::from(home).join("network.identity")) + ); + } + } + + #[test] + fn test_network_identity_is_created_during_runtime_apply() { + let dir = std::env::temp_dir().join(format!( + "reticulum_rs_network_identity_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let identity_path = dir.join("network.identity"); + + let identity = load_or_create_network_identity(&identity_path).unwrap(); + assert!(identity_path.is_file()); + let loaded = load_or_create_network_identity(&identity_path).unwrap(); + assert_eq!(identity.hash, loaded.hash); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn test_discovery_legacy_aliases_parsed() { + let input = "[reticulum]\n\ + discover_interfaces_autoconnect = Yes\n\ + discover_interfaces_required_value = 16\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!(rc.autoconnect_discovered_interfaces, 1); + assert_eq!(rc.discover_interfaces_required_value, 16); + } + + #[test] + fn test_blackhole_sources_parsed() { + let input = "[reticulum]\n\ + blackhole_sources = 521c87a83afb8f29e4455e77930b973b, 11111111111111111111111111111111\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!(rc.blackhole_sources.len(), 2); + assert_eq!( + rc.blackhole_sources[0], + [ + 0x52, 0x1c, 0x87, 0xa8, 0x3a, 0xfb, 0x8f, 0x29, 0xe4, 0x45, 0x5e, 0x77, 0x93, 0x0b, + 0x97, 0x3b, + ] + ); + } + + #[test] + fn test_invalid_typed_config_values_fail_like_configobj() { + for (key, value) in [ + ("share_instance", "maybe"), + ("shared_instance_port", "notaport"), + ("autoconnect_discovered_interfaces", "Yes"), + ("blackhole_sources", "deadbeef"), + ] { + let input = format!("[reticulum]\n{key} = {value}\n"); + let config = Config::parse(&input).unwrap(); + assert!( + ReticulumConfig::try_from_config(&config).is_err(), + "{key} = {value} should be rejected" + ); + } + + let config = Config::parse("[logging]\nloglevel = fish\n").unwrap(); + assert!(ReticulumConfig::try_from_config(&config).is_err()); + } + + #[test] + fn test_bootstrap_configs_parsed() { + let input = "[reticulum]\nbootstrap_configs = interfaces/bootstrap1.conf, interfaces/bootstrap2.conf\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!( + rc.bootstrap_configs, + vec![ + PathBuf::from("interfaces/bootstrap1.conf"), + PathBuf::from("interfaces/bootstrap2.conf"), + ] + ); + } + + #[test] + fn test_discover_required_value_clamped_to_u8() { + let input = "[reticulum]\ndiscover_interfaces_required_value = 999\n"; + let config = Config::parse(input).unwrap(); + let rc = ReticulumConfig::from_config(&config); + assert_eq!(rc.discover_interfaces_required_value, 255); + } + + #[test] + fn test_convert_mode_all_variants() { + use rns_interface::traits::InterfaceMode as IM; + use rns_transport::constants::InterfaceMode as TM; + + assert_eq!(convert_mode(IM::AccessPoint), TM::AccessPoint); + assert_eq!(convert_mode(IM::Roaming), TM::Roaming); + assert_eq!(convert_mode(IM::Boundary), TM::Boundary); + assert_eq!(convert_mode(IM::Gateway), TM::Gateway); + assert_eq!(convert_mode(IM::Full), TM::Full); + assert_eq!(convert_mode(IM::PointToPoint), TM::PointToPoint); + } + + #[test] + fn test_synthesize_interfaces_from_config() { + let input = r#" +[interfaces] + +[[Test TCP Client]] +type = TCPClientInterface +target_host = 127.0.0.1 +target_port = 4242 +enabled = yes + +[[Disabled Interface]] +type = UDPInterface +enabled = no + +[[Test UDP]] +type = UDPInterface +listen_port = 5555 +"#; + let config = Config::parse(input).unwrap(); + let interfaces = synthesize_interfaces(&config, false).unwrap(); + assert_eq!(interfaces.len(), 2); + } + + #[test] + fn test_panic_on_interface_error_fails_bad_config() { + let input = r#" +[interfaces] + +[[Broken Interface]] +enabled = yes +"#; + let config = Config::parse(input).unwrap(); + let err = synthesize_interfaces(&config, true).unwrap_err(); + assert!( + matches!(err, ReticulumError::Interface(_)), + "panic_on_interface_error should fail interface synthesis" + ); + } + + #[tokio::test] + async fn test_init_and_shutdown() { + let dir = std::env::temp_dir().join("reticulum_rs_test_init"); + let _ = std::fs::remove_dir_all(&dir); + + let shutdown = ShutdownSignal::new(); + let is_foreground = Arc::new(AtomicBool::new(true)); + let result = init( + Some(dir.to_str().unwrap()), + None, + shutdown.clone(), + is_foreground, + ) + .await; + assert!(result.is_ok()); + + let handle = result.unwrap(); + assert_eq!(handle.interface_configs.len(), 1); + match &handle.interface_configs[0] { + interface_factory::InterfaceConfig::Auto(config) => { + assert_eq!(config.name, "Default Interface"); + } + other => panic!("expected default AutoInterface, got {other:?}"), + } + assert!( + handle.config.rpc_key.is_some(), + "shared-instance RPC key should derive from transport identity by default" + ); + + shutdown.trigger(); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let _ = std::fs::remove_dir_all(&dir); + } + + #[tokio::test] + async fn test_init_shared_instance_tcp_server_then_client() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + let control_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let control_port = control_listener.local_addr().unwrap().port(); + drop(control_listener); + + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir_a = std::env::temp_dir().join(format!("reticulum_rs_tcp_shared_a_{nonce}")); + let dir_b = std::env::temp_dir().join(format!("reticulum_rs_tcp_shared_b_{nonce}")); + let dir_c = std::env::temp_dir().join(format!("reticulum_rs_tcp_shared_c_{nonce}")); + std::fs::create_dir_all(&dir_a).unwrap(); + std::fs::create_dir_all(&dir_b).unwrap(); + std::fs::create_dir_all(&dir_c).unwrap(); + let rpc_key_hex = "4242424242424242424242424242424242424242424242424242424242424242"; + let cfg = format!( + "[reticulum]\nshare_instance = Yes\nshared_instance_type = tcp\nshared_instance_port = {port}\ninstance_control_port = {control_port}\nrpc_key = {rpc_key_hex}\nenable_transport = No\n\n[interfaces]\n" + ); + std::fs::write(dir_a.join("config"), &cfg).unwrap(); + std::fs::write(dir_b.join("config"), &cfg).unwrap(); + std::fs::write(dir_c.join("config"), &cfg).unwrap(); + + let shutdown_a = ShutdownSignal::new(); + let shutdown_b = ShutdownSignal::new(); + let shutdown_c = ShutdownSignal::new(); + let foreground_a = Arc::new(AtomicBool::new(true)); + let foreground_b = Arc::new(AtomicBool::new(true)); + let foreground_c = Arc::new(AtomicBool::new(true)); + + let handle_a = init( + Some(dir_a.to_str().unwrap()), + None, + shutdown_a.clone(), + foreground_a, + ) + .await + .unwrap(); + assert_eq!(handle_a.instance_mode, InstanceMode::Shared); + + let handle_b = init( + Some(dir_b.to_str().unwrap()), + None, + shutdown_b.clone(), + foreground_b, + ) + .await + .unwrap(); + assert_eq!(handle_b.instance_mode, InstanceMode::Client); + + let handle_c = init( + Some(dir_c.to_str().unwrap()), + None, + shutdown_c.clone(), + foreground_c, + ) + .await + .unwrap(); + assert_eq!(handle_c.instance_mode, InstanceMode::Client); + + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + + let (stats_tx, stats_rx) = tokio::sync::oneshot::channel(); + handle_a + .transport_tx + .send(TransportMessage::Rpc { + query: rns_transport::messages::TransportQuery::GetInterfaceStats, + response_tx: stats_tx, + }) + .await + .unwrap(); + let server_stats = stats_rx.await.unwrap(); + let roles: Vec = match server_stats { + rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => { + entries.into_iter().map(|entry| entry.role).collect() + } + other => panic!("unexpected stats response: {other:?}"), + }; + assert!( + roles.iter().any(|role| role == "shared_server"), + "shared instance must mark the listener" + ); + assert!( + roles.iter().filter(|role| *role == "local_client").count() >= 2, + "accepted shared clients must be marked for transport policy" + ); + + let shared_control_stats = handle_b + .query_control(rns_transport::messages::TransportQuery::GetInterfaceStats) + .await + .expect("client control query should reach shared instance"); + let shared_control_roles: Vec = match shared_control_stats { + rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => { + entries.into_iter().map(|entry| entry.role).collect() + } + other => panic!("unexpected shared control stats response: {other:?}"), + }; + assert!( + shared_control_roles + .iter() + .any(|role| role == "shared_server"), + "client control queries must proxy to the authoritative shared instance" + ); + assert!( + shared_control_roles + .iter() + .filter(|role| *role == "local_client") + .count() + >= 2, + "proxied shared control stats must include accepted local clients" + ); + + let client_stats = handle_b + .query_transport(rns_transport::messages::TransportQuery::GetInterfaceStats) + .await + .expect("client local stats should respond"); + let client_roles: Vec = match client_stats { + rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => { + entries.into_iter().map(|entry| entry.role).collect() + } + other => panic!("unexpected client stats response: {other:?}"), + }; + assert!( + client_roles + .iter() + .any(|role| role == "shared_instance_peer"), + "client mode must mark the interface to the shared instance" + ); + + let dest_hash = [0x42; 16]; + let (delivery_tx, mut delivery_rx) = + tokio::sync::mpsc::channel::(8); + handle_c + .transport_tx + .send(TransportMessage::RegisterDestination { + hash: dest_hash, + app_name: "reticulum.test.shared".to_string(), + delivery_tx: Some(delivery_tx), + }) + .await + .unwrap(); + + let raw = make_plain_data_packet(dest_hash, b"shared plain fanout"); + handle_b + .transport_tx + .send(TransportMessage::Outbound( + rns_transport::messages::OutboundRequest { + raw: raw.clone(), + destination_hash: dest_hash, + }, + )) + .await + .unwrap(); + + let received = tokio::time::timeout(std::time::Duration::from_secs(2), async { + loop { + match delivery_rx.recv().await { + Some(rns_transport::link_messages::DestinationEvent::InboundPacket { + raw, + .. + }) => break raw, + Some(rns_transport::link_messages::DestinationEvent::AnnounceRequested(_)) => { + continue; + } + Some(other) => panic!("expected inbound shared packet, got {other:?}"), + None => panic!("destination channel closed"), + } + } + }) + .await + .expect("shared instance did not forward local-client plain packet"); + assert_eq!(received.as_ref(), raw.as_ref()); + + shutdown_c.trigger(); + shutdown_b.trigger(); + shutdown_a.trigger(); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + let _ = std::fs::remove_dir_all(&dir_a); + let _ = std::fs::remove_dir_all(&dir_b); + let _ = std::fs::remove_dir_all(&dir_c); + } + + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_interfaces_with_new_types() { + let input = r#" +[interfaces] + +[[Serial Port]] +type = SerialInterface +port = /dev/ttyUSB0 +speed = 115200 + +[[KISS TNC]] +type = KISSInterface +port = /dev/ttyUSB1 +speed = 57600 + +[[Auto Discovery]] +type = AutoInterface +group_id = testgroup + +[[LoRa Radio]] +type = RNodeInterface +port = /dev/ttyACM0 +frequency = 868000000 +bandwidth = 125000 + +[[OpenCom XL]] +type = RNodeMultiInterface +port = /dev/ttyACM1 +baud_rate = 230400 + +[[[High Datarate]]] +enabled = yes +vport = 1 +frequency = 2400000000 +bandwidth = 1625000 +txpower = 0 +spreadingfactor = 5 +codingrate = 5 + +[[[Low Datarate]]] +enabled = yes +vport = 0 +frequency = 865600000 +bandwidth = 125000 +txpower = 14 +spreadingfactor = 7 +codingrate = 5 + +[[Local]] +type = LocalInterface +port = 37428 +"#; + let config = Config::parse(input).unwrap(); + let interfaces = synthesize_interfaces(&config, false).unwrap(); + assert_eq!(interfaces.len(), 6); + let rnode_multi = interfaces.iter().find_map(|iface| match iface { + interface_factory::InterfaceConfig::RNodeMulti(c) => Some(c), + _ => None, + }); + let rnode_multi = rnode_multi.expect("RNodeMultiInterface synthesized"); + assert_eq!(rnode_multi.baud_rate, 230400); + assert_eq!(rnode_multi.subinterfaces.len(), 2); + assert_eq!(rnode_multi.subinterfaces[0].vport, 0); + assert_eq!(rnode_multi.subinterfaces[1].vport, 1); + } + + #[test] + fn test_clean_cache_empty_dir() { + let dir = std::env::temp_dir().join("reticulum_rs_test_clean_cache"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + clean_cache(&dir); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_clean_cache_removes_old_files() { + use std::fs; + + let dir = std::env::temp_dir().join("reticulum_rs_test_clean_old"); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + + let file_path = dir.join("old_entry"); + fs::write(&file_path, b"test data").unwrap(); + + // A recent file must survive — we don't mock mtime here. + clean_cache(&dir); + assert!(file_path.exists()); + + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/crates/rns-runtime/src/rncp.rs b/crates/rns-runtime/src/rncp.rs new file mode 100644 index 0000000..db1a71d --- /dev/null +++ b/crates/rns-runtime/src/rncp.rs @@ -0,0 +1,1568 @@ +//! Wire-compatible with Python `RNS.Utilities.rncp`. Supports `-l` (listen), +//! send (default), and `-F` / `-f` (fetch serve / client). + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use tokio::sync::mpsc; +use tokio::time::timeout; + +use rns_crypto::ed25519::Ed25519PublicKey; +use rns_crypto::sha::truncated_hash; +use rns_identity::destination::{DestType, Destination, Direction}; +use rns_identity::identity::Identity; +use rns_link::encryption::link_encrypt; +use rns_link::link::{CloseReason, Link}; +use rns_protocol::resource::{ + MAX_EFFICIENT_SIZE, MultiSegmentOutbound, OutboundResource, OutboundTransfer, TransferAction, +}; +use rns_transport::link_messages::DestinationEvent; +use rns_transport::messages::{ + AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse, +}; +use tokio::sync::oneshot; + +use crate::link_manager::{LinkManager, RequestOutcome, ResourceCompletion}; + +/// Python `REQ_FETCH_NOT_ALLOWED` sentinel (rncp.py:70). +pub const REQ_FETCH_NOT_ALLOWED: u8 = 0xF0; + +pub const FETCH_PATH_NAME: &str = "fetch_file"; + +pub const DEFAULT_RNCP_APP_NAME: &str = "rncp.receive"; + +pub fn default_rncp_app_name() -> &'static str { + DEFAULT_RNCP_APP_NAME +} + +#[derive(Debug, thiserror::Error)] +pub enum RncpError { + #[error("transport channel unavailable")] + TransportUnavailable, + #[error("timed out waiting for {0}")] + Timeout(&'static str), + #[error("remote destination identity has not been announced")] + PathTimeout, + #[error("announce carried no public key")] + NoIdentity, + #[error("link handshake failed: {0}")] + HandshakeFailed(String), + #[error("link proof validation failed: {0}")] + ProofInvalid(String), + #[error("link crypto error: {0}")] + LinkCrypto(String), + #[error("resource build failed: {0}")] + ResourceCreate(String), + #[error("resource transfer failed: {0}")] + ResourceFailed(String), + #[error("I/O error: {0}")] + Io(String), + #[error("local identity has no signing key")] + NoSigningKey, + #[error("sender not in allow-list")] + Denied, +} + +#[derive(Debug, Clone)] +pub struct RncpOutcome { + pub file_name: String, + pub bytes: usize, + pub link_rtt: Duration, + pub duration: Duration, +} + +pub struct RncpSendRequest<'a> { + pub transport_tx: mpsc::Sender, + pub identity: Identity, + pub dest_hash: [u8; 16], + pub file_name: &'a str, + pub data: Vec, + pub auto_compress: bool, + pub overall_timeout: Duration, + pub path_wait: Duration, + pub progress_tx: Option>, +} + +#[derive(Debug, Clone)] +pub enum RncpEvent { + LinkEstablished { + link_id: [u8; 16], + }, + /// Zero `identity_hash` = remote never identified; only accepted under `allow_all`. + SenderIdentified { + link_id: [u8; 16], + identity_hash: [u8; 16], + }, + SenderDenied { + link_id: [u8; 16], + identity_hash: [u8; 16], + }, + Completed { + link_id: [u8; 16], + file_name: String, + saved_path: PathBuf, + bytes: usize, + }, + WriteFailed { + link_id: [u8; 16], + file_name: String, + reason: String, + }, + FetchServing { + link_id: [u8; 16], + file_name: String, + bytes: usize, + }, + FetchDenied { + link_id: [u8; 16], + reason: String, + }, +} + +/// Resolves a fetch path under the jail root (Python rncp.py:177-183). +/// Absolute paths replace the jail prefix; relatives join onto it; canonical +/// result must stay inside `jail_canonical`. +fn resolve_fetch_path(jail: Option<&Path>, data: &[u8]) -> Result { + let path_str = std::str::from_utf8(data).map_err(|_| "non-utf8 path".to_string())?; + if path_str.is_empty() { + return Err("empty path".into()); + } + match jail { + Some(jail_dir) => { + let jail_canonical = + std::fs::canonicalize(jail_dir).map_err(|e| format!("jail canonicalize: {e}"))?; + // canonicalize resolves symlinks (macOS `/var` → `/private/var`) + // before the containment check. + let requested = Path::new(path_str); + let combined = if requested.is_absolute() { + requested.to_path_buf() + } else { + jail_canonical.join(path_str) + }; + let canonical = + std::fs::canonicalize(&combined).map_err(|e| format!("not found: {e}"))?; + if !canonical.starts_with(&jail_canonical) { + return Err("outside fetch jail".into()); + } + Ok(canonical) + } + None => std::fs::canonicalize(path_str).map_err(|e| format!("not found: {e}")), + } +} + +pub struct RncpListenerConfig { + pub identity: Identity, + pub app_name: String, + pub save_dir: PathBuf, + /// Python `allow_all` / `-n`. + pub allow_all: bool, + /// Ignored when `allow_all` is set. + pub allowed: Vec<[u8; 16]>, + pub overwrite: bool, + /// Python `-F` / `--allow-fetch`. + pub allow_fetch: bool, + /// Python `-j` / `--jail`. + pub fetch_jail: Option, + /// Python default on; `--no-compress` disables. + pub fetch_auto_compress: bool, +} + +impl Default for RncpListenerConfig { + fn default() -> Self { + Self { + identity: Identity::new(), + app_name: DEFAULT_RNCP_APP_NAME.to_string(), + save_dir: PathBuf::from("."), + allow_all: false, + allowed: Vec::new(), + overwrite: false, + allow_fetch: false, + fetch_jail: None, + fetch_auto_compress: true, + } + } +} + +pub struct RncpListenerHandle { + pub destination_hash: [u8; 16], + task: tokio::task::JoinHandle<()>, +} + +impl RncpListenerHandle { + pub fn destination_hash(&self) -> [u8; 16] { + self.destination_hash + } + pub async fn shutdown(self) { + self.task.abort(); + let _ = self.task.await; + } +} + +pub async fn spawn_rncp_listener( + transport_tx: mpsc::Sender, + cfg: RncpListenerConfig, + events_tx: mpsc::Sender, +) -> Result { + let signing_key = cfg + .identity + .get_signing_key() + .ok_or(RncpError::NoSigningKey)?; + + let destination = Destination::new( + Some(&cfg.identity), + Direction::In, + DestType::Single, + &cfg.app_name, + ) + .map_err(|e| RncpError::HandshakeFailed(format!("destination: {e:?}")))?; + let dest_hash = destination.hash; + + let (dest_tx, dest_rx) = mpsc::channel::(256); + let link_control_tx = dest_tx.clone(); + transport_tx + .send(TransportMessage::RegisterDestination { + hash: dest_hash, + app_name: cfg.app_name.clone(), + delivery_tx: Some(dest_tx), + }) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let mut link_mgr = LinkManager::with_destination( + transport_tx.clone(), + dest_rx, + &cfg.identity, + &cfg.app_name, + signing_key, + ); + + let (completion_tx, mut completion_rx) = mpsc::channel::(64); + link_mgr.set_resource_completion_channel(completion_tx); + + // Gate the allow-list before parts arrive. + let (identified_tx, mut identified_rx) = mpsc::channel::<([u8; 16], [u8; 16])>(64); + link_mgr.set_link_identified_channel(identified_tx); + + if !cfg.allow_fetch && !cfg.allow_all { + let allowed_push: std::collections::HashSet<[u8; 16]> = + cfg.allowed.iter().copied().collect(); + link_mgr.set_link_identity_gate(move |_link_id, identity_hash| { + allowed_push.contains(&identity_hash) + }); + } + + if cfg.allow_fetch { + let jail = cfg.fetch_jail.clone(); + let auto_compress = cfg.fetch_auto_compress; + let allowed_fetch: Arc> = + Arc::new(cfg.allowed.iter().copied().collect()); + let allow_all_fetch = cfg.allow_all; + let link_identities = link_mgr.link_identities_handle(); + let fetch_events = events_tx.clone(); + let fetch_path_hash = truncated_hash(FETCH_PATH_NAME.as_bytes()); + link_mgr.set_request_handler_ex(move |link_id, path_hash, data| { + if path_hash != fetch_path_hash { + return RequestOutcome::Drop; + } + // Allow-all bypasses ident check; else peer must have sent + // LinkIdentify with an identity in `allowed`. + if !allow_all_fetch { + let ident = link_identities + .lock() + .ok() + .and_then(|m| m.get(&link_id).copied()); + match ident { + Some(h) if allowed_fetch.contains(&h) => {} + _ => { + let _ = fetch_events.try_send(RncpEvent::FetchDenied { + link_id, + reason: "not in allow-list".into(), + }); + return RequestOutcome::Reply(vec![REQ_FETCH_NOT_ALLOWED]); + } + } + } + match resolve_fetch_path(jail.as_deref(), &data) { + Ok(file_path) => match std::fs::read(&file_path) { + Ok(bytes) => { + let basename = file_path + .file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let metadata = pack_metadata(&basename); + let _ = fetch_events.try_send(RncpEvent::FetchServing { + link_id, + file_name: basename, + bytes: bytes.len(), + }); + RequestOutcome::ReplyWithResource { + ack: vec![0xC3], // msgpack `true` + data: bytes, + metadata: Some(metadata), + auto_compress, + } + } + Err(_) => RequestOutcome::Reply(vec![0xC2]), // msgpack `false` + }, + Err(reason) => { + let _ = fetch_events.try_send(RncpEvent::FetchDenied { link_id, reason }); + RequestOutcome::Reply(vec![REQ_FETCH_NOT_ALLOWED]) + } + } + }); + } + + let app_name = cfg.app_name.clone(); + let save_dir = cfg.save_dir.clone(); + let allow_all = cfg.allow_all; + let allowed: std::collections::HashSet<[u8; 16]> = cfg.allowed.iter().copied().collect(); + let overwrite = cfg.overwrite; + let allow_fetch_outer = cfg.allow_fetch; + let events_tx_cb = events_tx.clone(); + let link_control_tx_cb = link_control_tx.clone(); + + let task = tokio::spawn(async move { + let lm_task = tokio::spawn(async move { link_mgr.run().await }); + + let mut denied_links: std::collections::HashSet<[u8; 16]> = Default::default(); + + loop { + tokio::select! { + ident = identified_rx.recv() => { + let Some((link_id, ident_hash)) = ident else { break }; + if allow_all || allowed.contains(&ident_hash) { + let _ = events_tx_cb + .send(RncpEvent::SenderIdentified { + link_id, + identity_hash: ident_hash, + }) + .await; + } else { + denied_links.insert(link_id); + let _ = events_tx_cb + .send(RncpEvent::SenderDenied { + link_id, + identity_hash: ident_hash, + }) + .await; + // Keep the link open under fetch so the handler can + // reply REQ_FETCH_NOT_ALLOWED rather than a generic close. + if !allow_fetch_outer { + let _ = link_control_tx_cb + .send(DestinationEvent::LinkClosed { link_id }) + .await; + } + } + } + completion = completion_rx.recv() => { + let Some(evt) = completion else { break }; + if denied_links.contains(&evt.link_id) { + continue; + } + + let file_name = extract_filename(evt.metadata.as_deref()) + .unwrap_or_else(|| default_file_name(&evt.resource_hash)); + + match save_payload(&save_dir, &file_name, &evt.data, overwrite).await { + Ok(path) => { + let _ = events_tx_cb + .send(RncpEvent::Completed { + link_id: evt.link_id, + file_name, + saved_path: path, + bytes: evt.data.len(), + }) + .await; + } + Err(e) => { + let _ = events_tx_cb + .send(RncpEvent::WriteFailed { + link_id: evt.link_id, + file_name, + reason: e, + }) + .await; + } + } + } + } + } + + let _ = lm_task.await; + }); + + tracing::info!( + dest = hex::encode(dest_hash), + app_name = %app_name, + "rncp listener started" + ); + + Ok(RncpListenerHandle { + destination_hash: dest_hash, + task, + }) +} + +fn extract_filename(metadata: Option<&[u8]>) -> Option { + let meta = metadata?; + // Envelope: msgpack({"name": b"filename"}). + let map: rmpv::Value = rmpv::decode::read_value(&mut std::io::Cursor::new(meta)).ok()?; + let entries = match map { + rmpv::Value::Map(m) => m, + _ => return None, + }; + for (k, v) in entries { + let key = match k { + rmpv::Value::String(s) => s.into_str()?, + rmpv::Value::Binary(b) => String::from_utf8(b).ok()?, + _ => continue, + }; + if key == "name" { + let bytes = match v { + rmpv::Value::Binary(b) => b, + rmpv::Value::String(s) => s.into_bytes(), + _ => continue, + }; + return String::from_utf8(bytes).ok(); + } + } + None +} + +fn default_file_name(resource_hash: &[u8; 32]) -> String { + format!("rncp_{}", hex::encode(&resource_hash[..8])) +} + +async fn save_payload( + save_dir: &Path, + file_name: &str, + data: &[u8], + overwrite: bool, +) -> Result { + // Strip path traversal components. + let basename = Path::new(file_name) + .file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_else(|| file_name.to_string()); + if basename.is_empty() { + return Err("empty filename".into()); + } + + tokio::fs::create_dir_all(save_dir) + .await + .map_err(|e| format!("create save_dir: {e}"))?; + let mut path = save_dir.join(&basename); + if !overwrite && path.exists() { + let mut i = 1; + loop { + let candidate = save_dir.join(format!("{basename}.{i}")); + if !candidate.exists() { + path = candidate; + break; + } + i += 1; + } + } + tokio::fs::write(&path, data) + .await + .map_err(|e| format!("write {}: {e}", path.display()))?; + Ok(path) +} + +fn build_link_close(link: &mut Link) -> Option { + let link_id = link.link_id; + let teardown_data = link.teardown(CloseReason::InitiatorClosed)?; + Some(build_data_packet( + link_id, + rns_wire::context::PacketContext::LinkClose, + &teardown_data, + )) +} + +pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result { + let RncpSendRequest { + transport_tx, + identity, + dest_hash, + file_name, + data, + auto_compress, + overall_timeout, + path_wait, + progress_tx, + } = request; + + let started = Instant::now(); + let deadline = started + overall_timeout; + let byte_count = data.len(); + + let pubkey = + discover_pubkey(&transport_tx, dest_hash, path_wait.min(remaining(deadline))).await?; + + let (mut link, link_request_data) = Link::new_initiator(dest_hash, 1); + let link_id = link.link_id; + + // Route LRPROOF / link packets back to this task. + let (lpkt_tx, mut lpkt_rx) = mpsc::channel::(256); + transport_tx + .send(TransportMessage::RegisterDestination { + hash: link_id, + app_name: "rncp.sender".to_string(), + delivery_tx: Some(lpkt_tx), + }) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: link_req_pkt, + destination_hash: dest_hash, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let proof_body = match timeout(remaining(deadline), wait_for_proof(&mut lpkt_rx, link_id)).await + { + Ok(Ok(body)) => body, + Ok(Err(e)) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(e); + } + Err(_) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(RncpError::Timeout("link proof")); + } + }; + + let identity_ed25519_pub: [u8; 32] = pubkey[32..64] + .try_into() + .map_err(|_| RncpError::ProofInvalid("remote pub key length".into()))?; + let verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub) + .map_err(|e| RncpError::ProofInvalid(format!("verify key: {e}")))?; + + let rtt_data = link + .validate_proof(&proof_body, &verify_key, &identity_ed25519_pub) + .map_err(|e| RncpError::ProofInvalid(format!("{e:?}")))?; + + let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: rtt_pkt, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let our_pub = identity.get_public_key(); + let our_priv = identity.get_signing_key().ok_or(RncpError::NoSigningKey)?; + let ident_data = link + .identify(&our_pub, &our_priv) + .map_err(|e| RncpError::LinkCrypto(format!("identify: {e:?}")))?; + let ident_pkt = build_data_packet( + link_id, + rns_wire::context::PacketContext::LinkIdentify, + &ident_data, + ); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: ident_pkt, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + // Encrypt full payload BEFORE chunking (Resource.py:424). + let session_keys = link + .session_keys() + .ok_or_else(|| RncpError::LinkCrypto("no session keys".into()))?; + let session_keys_enc = session_keys.clone(); + let encrypt_fn = move |plaintext: &[u8]| -> Vec { + link_encrypt(&session_keys_enc, plaintext).unwrap_or_default() + }; + + let metadata_bytes = pack_metadata(file_name); + + let link_rtt = link.rtt.unwrap_or(Duration::from_millis(500)); + let resources = if metadata_bytes.len() + 3 + data.len() <= MAX_EFFICIENT_SIZE { + vec![ + OutboundResource::with_options( + data, + auto_compress, + Some(metadata_bytes), + None, + Some(&encrypt_fn), + ) + .map_err(|e| RncpError::ResourceCreate(format!("{e:?}")))?, + ] + } else { + MultiSegmentOutbound::with_options( + data, + auto_compress, + Some(metadata_bytes), + None, + false, + Some(&encrypt_fn), + ) + .map_err(|e| RncpError::ResourceCreate(format!("{e:?}")))? + .segments + }; + let resource_hash = resources + .first() + .map(|r| r.original_hash.unwrap_or(r.resource_hash)) + .unwrap_or([0u8; 32]); + let total_parts: usize = resources.iter().map(|r| r.parts.len()).sum(); + let total_parts_nonzero = total_parts.max(1); + + let proof_deadline = Instant::now() + overall_timeout.min(Duration::from_secs(120)); + let mut transfer_result = Ok(()); + let mut completed_parts = 0usize; + for resource in resources { + let segment_parts = resource.parts.len(); + transfer_result = drive_outbound(OutboundDrive { + transport_tx: &transport_tx, + link: &mut link, + link_id, + resource, + lpkt_rx: &mut lpkt_rx, + progress_tx: progress_tx.clone(), + progress_base: completed_parts as f32 / total_parts_nonzero as f32, + progress_span: segment_parts as f32 / total_parts_nonzero as f32, + deadline: proof_deadline.min(deadline), + }) + .await; + if transfer_result.is_err() { + break; + } + completed_parts += segment_parts; + } + + if let Some(close_pkt) = build_link_close(&mut link) { + let _ = transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: close_pkt, + destination_hash: link_id, + })) + .await; + } + cleanup_destination(&transport_tx, link_id).await; + + transfer_result?; + + tracing::info!( + dest = hex::encode(dest_hash), + link_id = hex::encode(link_id), + resource = hex::encode(&resource_hash[..8]), + bytes = byte_count, + parts = total_parts, + "rncp send complete" + ); + + Ok(RncpOutcome { + file_name: file_name.to_string(), + bytes: byte_count, + link_rtt, + duration: started.elapsed(), + }) +} + +fn pack_metadata(file_name: &str) -> Vec { + let entries = vec![( + rmpv::Value::String(rmpv::Utf8String::from("name")), + rmpv::Value::Binary(file_name.as_bytes().to_vec()), + )]; + let mut buf = Vec::new(); + let _ = rmpv::encode::write_value(&mut buf, &rmpv::Value::Map(entries)); + buf +} + +struct OutboundDrive<'a> { + transport_tx: &'a mpsc::Sender, + link: &'a mut Link, + link_id: [u8; 16], + resource: OutboundResource, + lpkt_rx: &'a mut mpsc::Receiver, + progress_tx: Option>, + progress_base: f32, + progress_span: f32, + deadline: Instant, +} + +async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> { + let OutboundDrive { + transport_tx, + link, + link_id, + resource, + lpkt_rx, + progress_tx, + progress_base, + progress_span, + deadline, + } = request; + + let rtt = link.rtt.unwrap_or(Duration::from_millis(500)); + let mut transfer = OutboundTransfer::from_prebuilt(resource, rtt); + let total = transfer.resource.parts.len(); + if let Some(ref tx) = progress_tx { + let _ = tx.try_send(if total == 0 { + progress_base + progress_span + } else { + progress_base + }); + } + + loop { + if Instant::now() >= deadline { + return Err(RncpError::Timeout("resource proof")); + } + + loop { + match transfer.tick() { + TransferAction::None => break, + TransferAction::Complete => return Ok(()), + TransferAction::Failed(reason) => return Err(RncpError::ResourceFailed(reason)), + action => send_transfer_action(transport_tx, link, link_id, action).await?, + } + } + + let recv_timeout = remaining(deadline).min(Duration::from_secs(5)); + let ev = match tokio::time::timeout(recv_timeout, lpkt_rx.recv()).await { + Ok(Some(ev)) => ev, + Ok(None) => return Err(RncpError::ResourceFailed("link channel closed".into())), + Err(_) => continue, + }; + + let DestinationEvent::InboundPacket { raw, .. } = ev else { + continue; + }; + let (header, off) = match rns_wire::header::PacketHeader::unpack(&raw) { + Ok(h) => h, + Err(_) => continue, + }; + if header.destination_hash != link_id { + continue; + } + let body = &raw[off..]; + match header.context { + rns_wire::context::PacketContext::Keepalive + if body.first() == Some(&rns_link::constants::KEEPALIVE_REQUEST) => + { + send_keepalive_response(transport_tx, link_id).await?; + } + rns_wire::context::PacketContext::ResourceHmu + | rns_wire::context::PacketContext::ResourceReq => { + let Ok(plaintext) = link.decrypt(body) else { + continue; + }; + if header.context == rns_wire::context::PacketContext::ResourceReq { + let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type); + for action in transfer.handle_request_packet(packet_hash, &plaintext) { + send_transfer_action(transport_tx, link, link_id, action).await?; + } + } else { + transfer.handle_hmu(&plaintext); + } + if let Some(ref tx) = progress_tx { + let confirmed_count = transfer.confirmed_parts.iter().filter(|c| **c).count(); + let frac = if total == 0 { + 1.0 + } else { + confirmed_count as f32 / total as f32 + }; + let _ = tx.try_send(progress_base + (progress_span * frac)); + } + } + rns_wire::context::PacketContext::ResourcePrf => { + // PROOF+RESOURCE_PRF plaintext = resource_hash(32) || proof(32) (Packet.py:195-197). + if body.len() < 64 { + continue; + } + if !transfer.handle_proof(body) { + return Err(RncpError::ResourceFailed("proof mismatch".into())); + } + if let Some(ref tx) = progress_tx { + let _ = tx.try_send(progress_base + progress_span); + } + return Ok(()); + } + rns_wire::context::PacketContext::ResourceRcl => { + return Err(RncpError::ResourceFailed("receiver cancelled".into())); + } + rns_wire::context::PacketContext::LinkClose if link.receive_teardown(body) => { + return Err(RncpError::ResourceFailed("link closed before proof".into())); + } + _ => {} + } + } +} + +async fn send_keepalive_response( + transport_tx: &mpsc::Sender, + link_id: [u8; 16], +) -> Result<(), RncpError> { + let raw = build_data_packet( + link_id, + rns_wire::context::PacketContext::Keepalive, + &[rns_link::constants::KEEPALIVE_RESPONSE], + ); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable) +} + +async fn send_transfer_action( + transport_tx: &mpsc::Sender, + link: &Link, + link_id: [u8; 16], + action: TransferAction, +) -> Result<(), RncpError> { + if let TransferAction::SendProof(proof) = action { + let raw = build_resource_proof_packet(link_id, &proof); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + return Ok(()); + } + + let (context, body) = match action { + TransferAction::SendAdvertisement(adv) => { + let encrypted = link + .encrypt(&adv) + .map_err(|e| RncpError::LinkCrypto(format!("adv encrypt: {e:?}")))?; + ( + rns_wire::context::PacketContext::ResourceAdv, + Bytes::from(encrypted), + ) + } + TransferAction::SendPart(_, part) => ( + rns_wire::context::PacketContext::Resource, + Bytes::from(part), + ), + TransferAction::SendHmu(hmu) => { + let encrypted = link + .encrypt(&hmu) + .map_err(|e| RncpError::LinkCrypto(format!("hmu encrypt: {e:?}")))?; + ( + rns_wire::context::PacketContext::ResourceHmu, + Bytes::from(encrypted), + ) + } + TransferAction::SendRequest(req) => { + let encrypted = link + .encrypt(&req) + .map_err(|e| RncpError::LinkCrypto(format!("request encrypt: {e:?}")))?; + ( + rns_wire::context::PacketContext::ResourceReq, + Bytes::from(encrypted), + ) + } + TransferAction::SendCancel(cancel_type, resource_hash) => { + let encrypted = link + .encrypt(&resource_hash) + .map_err(|e| RncpError::LinkCrypto(format!("cancel encrypt: {e:?}")))?; + 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 + } + }; + (context, Bytes::from(encrypted)) + } + TransferAction::SendProof(_) => unreachable!("proof handled before data-packet match"), + TransferAction::None | TransferAction::Complete => return Ok(()), + TransferAction::Failed(reason) => return Err(RncpError::ResourceFailed(reason)), + }; + let raw = build_data_packet(link_id, context, &body); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable) +} + +fn remaining(deadline: Instant) -> Duration { + deadline.saturating_duration_since(Instant::now()) +} + +async fn discover_pubkey( + transport_tx: &mpsc::Sender, + dest_hash: [u8; 16], + path_wait: Duration, +) -> Result<[u8; 64], RncpError> { + if let Some(pk) = lookup_pubkey(transport_tx, dest_hash).await? { + return Ok(pk); + } + + transport_tx + .send(TransportMessage::RequestPath { + destination_hash: dest_hash, + }) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + let (await_tx, await_rx) = oneshot::channel(); + transport_tx + .send(TransportMessage::AwaitPath { + dest: dest_hash, + reply: await_tx, + }) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + let found = timeout(path_wait, await_rx) + .await + .map_err(|_| RncpError::PathTimeout)? + .unwrap_or(false); + if !found { + return Err(RncpError::PathTimeout); + } + + lookup_pubkey(transport_tx, dest_hash) + .await? + .ok_or(RncpError::NoIdentity) +} + +/// `Ok(None)` = peer not in announce cache. +async fn lookup_pubkey( + transport_tx: &mpsc::Sender, + dest_hash: [u8; 16], +) -> Result, RncpError> { + let (resp_tx, resp_rx) = oneshot::channel(); + transport_tx + .send(TransportMessage::Rpc { + query: TransportQuery::GetRecentAnnounces, + response_tx: resp_tx, + }) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + let resp = resp_rx.await.map_err(|_| RncpError::TransportUnavailable)?; + let announces: Vec = match resp { + TransportQueryResponse::Announces(v) => v, + _ => Vec::new(), + }; + Ok(announces + .into_iter() + .find(|a| a.dest_hash == dest_hash) + .and_then(|a| a.public_key)) +} + +async fn wait_for_proof( + rx: &mut mpsc::Receiver, + link_id: [u8; 16], +) -> Result, RncpError> { + while let Some(ev) = rx.recv().await { + let DestinationEvent::InboundPacket { raw, .. } = ev else { + continue; + }; + let Ok((header, off)) = rns_wire::header::PacketHeader::unpack(&raw) else { + continue; + }; + if header.flags.packet_type == rns_wire::flags::PacketType::Proof + && header.destination_hash == link_id + && raw.len() > off + { + return Ok(raw[off..].to_vec()); + } + } + Err(RncpError::HandshakeFailed("channel closed".into())) +} + +async fn cleanup_destination(transport_tx: &mpsc::Sender, link_id: [u8; 16]) { + let _ = transport_tx.try_send(TransportMessage::DeregisterDestination { hash: link_id }); +} + +fn build_link_request_packet(dest_hash: [u8; 16], request_data: &[u8]) -> Bytes { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::LinkRequest, + }, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(request_data); + Bytes::from(raw) +} + +fn build_data_packet( + link_id: [u8; 16], + context: rns_wire::context::PacketContext, + body: &[u8], +) -> Bytes { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(body); + Bytes::from(raw) +} + +fn build_resource_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::ResourcePrf, + }; + let mut raw = header.pack(); + raw.extend_from_slice(proof); + Bytes::from(raw) +} + +#[derive(Debug, Clone)] +pub struct RncpFetchOutcome { + pub file_name: String, + pub saved_path: PathBuf, + pub bytes: usize, + pub link_rtt: Duration, + pub duration: Duration, +} + +pub struct RncpFetchRequest<'a> { + pub transport_tx: mpsc::Sender, + pub identity: Identity, + pub dest_hash: [u8; 16], + pub remote_path: &'a str, + pub save_dir: &'a Path, + pub overwrite: bool, + pub overall_timeout: Duration, + pub path_wait: Duration, + pub progress_tx: Option>, +} + +/// Fetches a remote file via `rncp --fetch`. Wire flow: +/// link + identify → REQUEST `fetch_file` → ack byte (`0xC3` ok, `0xC2` not +/// found, [`REQ_FETCH_NOT_ALLOWED`] denied) → resource → write to `save_dir`. +pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result { + use rns_protocol::resource::{ + InboundTransfer, MAX_SEGMENTS, MultiSegmentInbound, TransferAction, + }; + + let RncpFetchRequest { + transport_tx, + identity, + dest_hash, + remote_path, + save_dir, + overwrite, + overall_timeout, + path_wait, + progress_tx, + } = request; + + let started = Instant::now(); + let deadline = started + overall_timeout; + + let pubkey = + discover_pubkey(&transport_tx, dest_hash, path_wait.min(remaining(deadline))).await?; + + let (mut link, link_request_data) = Link::new_initiator(dest_hash, 1); + let link_id = link.link_id; + + let (lpkt_tx, mut lpkt_rx) = mpsc::channel::(256); + transport_tx + .send(TransportMessage::RegisterDestination { + hash: link_id, + app_name: "rncp.fetch".to_string(), + delivery_tx: Some(lpkt_tx), + }) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: link_req_pkt, + destination_hash: dest_hash, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let proof_body = match timeout(remaining(deadline), wait_for_proof(&mut lpkt_rx, link_id)).await + { + Ok(Ok(body)) => body, + Ok(Err(e)) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(e); + } + Err(_) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(RncpError::Timeout("link proof")); + } + }; + + let identity_ed25519_pub: [u8; 32] = pubkey[32..64] + .try_into() + .map_err(|_| RncpError::ProofInvalid("remote pub key length".into()))?; + let verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub) + .map_err(|e| RncpError::ProofInvalid(format!("verify key: {e}")))?; + + let rtt_data = link + .validate_proof(&proof_body, &verify_key, &identity_ed25519_pub) + .map_err(|e| RncpError::ProofInvalid(format!("{e:?}")))?; + + let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: rtt_pkt, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let our_pub = identity.get_public_key(); + let our_priv = identity.get_signing_key().ok_or(RncpError::NoSigningKey)?; + let ident_data = link + .identify(&our_pub, &our_priv) + .map_err(|e| RncpError::LinkCrypto(format!("identify: {e:?}")))?; + let ident_pkt = build_data_packet( + link_id, + rns_wire::context::PacketContext::LinkIdentify, + &ident_data, + ); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: ident_pkt, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let (req_encrypted, _req_id) = link + .request_str(FETCH_PATH_NAME, remote_path, remaining(deadline)) + .map_err(|e| RncpError::LinkCrypto(format!("request: {e:?}")))?; + let req_pkt = build_data_packet( + link_id, + rns_wire::context::PacketContext::Request, + &req_encrypted, + ); + let packet_request_id = + rns_wire::hash::truncated_packet_hash(&req_pkt, rns_wire::flags::HeaderType::Header1); + link.update_pending_request_id(&_req_id, packet_request_id); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: req_pkt, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + + let session_keys = link + .session_keys() + .ok_or_else(|| RncpError::LinkCrypto("no session keys".into()))?; + let session_keys_dec = session_keys.clone(); + let decrypt_fn = + move |ciphertext: &[u8]| -> Result, rns_protocol::resource::ResourceError> { + rns_link::encryption::link_decrypt(&session_keys_dec, ciphertext) + .map_err(|_| rns_protocol::resource::ResourceError::DecryptFailed) + }; + + let link_rtt = link.rtt.unwrap_or(Duration::from_millis(500)); + let mut ack_seen = false; + let mut transfers: std::collections::HashMap<[u8; 32], InboundTransfer> = + std::collections::HashMap::new(); + let mut split_resources: std::collections::HashMap<[u8; 32], MultiSegmentInbound> = + std::collections::HashMap::new(); + let mut segment_routes: std::collections::HashMap<[u8; 32], ([u8; 32], usize)> = + std::collections::HashMap::new(); + + let result: Result<(String, Vec), RncpError> = loop { + if Instant::now() >= deadline { + break Err(RncpError::Timeout("fetch")); + } + let recv_timeout = remaining(deadline).min(Duration::from_secs(5)); + let ev = match tokio::time::timeout(recv_timeout, lpkt_rx.recv()).await { + Ok(Some(ev)) => ev, + Ok(None) => break Err(RncpError::ResourceFailed("link channel closed".into())), + Err(_) => continue, + }; + + let DestinationEvent::InboundPacket { raw, .. } = ev else { + continue; + }; + let (header, off) = match rns_wire::header::PacketHeader::unpack(&raw) { + Ok(h) => h, + Err(_) => continue, + }; + if header.destination_hash != link_id { + continue; + } + let body = &raw[off..]; + match header.context { + rns_wire::context::PacketContext::Keepalive + if body.first() == Some(&rns_link::constants::KEEPALIVE_REQUEST) => + { + send_keepalive_response(&transport_tx, link_id).await?; + } + rns_wire::context::PacketContext::Response => { + let Ok((_req_id, resp)) = link.handle_response(body) else { + continue; + }; + match resp.first().copied() { + Some(0xC3) => ack_seen = true, + Some(0xC2) => break Err(RncpError::ResourceFailed("remote: not found".into())), + Some(REQ_FETCH_NOT_ALLOWED) => break Err(RncpError::Denied), + _ => break Err(RncpError::ResourceFailed("unknown ack".into())), + } + } + rns_wire::context::PacketContext::ResourceAdv => { + if !ack_seen { + // Some implementations race ADV with ack; treat ADV as implicit consent. + ack_seen = true; + } + let Ok(plaintext) = link.decrypt(body) else { + continue; + }; + let Ok(adv) = rns_protocol::resource_adv::ResourceAdvertisement::unpack(&plaintext) + else { + continue; + }; + if adv.total_segments > 1 { + if adv.total_segments > MAX_SEGMENTS + || adv.segment_index == 0 + || adv.segment_index > adv.total_segments + { + break Err(RncpError::ResourceFailed( + "invalid split-resource advertisement".into(), + )); + } + let coord = split_resources.entry(adv.original_hash).or_insert_with(|| { + MultiSegmentInbound::new(adv.total_segments, adv.original_hash) + }); + if coord.total_segments != adv.total_segments { + break Err(RncpError::ResourceFailed( + "split-resource total_segments changed".into(), + )); + } + segment_routes + .insert(adv.resource_hash, (adv.original_hash, adv.segment_index)); + } + let map_hashes = adv.get_map_hashes(); + let mut transfer_flags = adv.flags; + if adv.total_segments > 1 && adv.segment_index > 1 { + transfer_flags.has_metadata = false; + } + let mut rh = [0u8; rns_protocol::resource::RANDOM_HASH_SIZE]; + let copy_len = adv.random_hash.len().min(rh.len()); + rh[..copy_len].copy_from_slice(&adv.random_hash[..copy_len]); + let Ok(mut t) = InboundTransfer::from_advertisement( + adv.num_parts, + adv.transfer_size, + adv.data_size, + rh, + adv.resource_hash, + transfer_flags, + map_hashes, + link_rtt, + ) else { + continue; + }; + if let TransferAction::SendRequest(req_data) = t.request_next() + && let Ok(encrypted) = link.encrypt(&req_data) + { + let req_raw = build_data_packet( + link_id, + rns_wire::context::PacketContext::ResourceReq, + &encrypted, + ); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: req_raw, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + } + transfers.insert(adv.resource_hash, t); + } + rns_wire::context::PacketContext::Resource => { + let mut resource_action_to_send = None; + let mut completed_rh = None; + for (rh, t) in &mut transfers { + let action = t.receive_part(body.to_vec()); + if let Some(ref tx) = progress_tx { + let _ = tx.try_send(t.resource.progress() as f32); + } + match action { + TransferAction::SendHmu(_) | TransferAction::SendRequest(_) => { + resource_action_to_send = Some(action); + } + TransferAction::Complete => { + completed_rh = Some(*rh); + } + _ => {} + } + if completed_rh.is_none() && t.resource.is_complete() { + completed_rh = Some(*rh); + } + if resource_action_to_send.is_some() || completed_rh.is_some() { + break; + } + } + + if let Some(action) = resource_action_to_send { + let (context, payload) = match action { + TransferAction::SendHmu(hmu) => { + (rns_wire::context::PacketContext::ResourceHmu, hmu) + } + TransferAction::SendRequest(req) => { + (rns_wire::context::PacketContext::ResourceReq, req) + } + _ => unreachable!(), + }; + if let Ok(encrypted) = link.encrypt(&payload) { + let raw = build_data_packet(link_id, context, &encrypted); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + } + } + + if let Some(rh) = completed_rh { + let (payload, proof, metadata, resource_hash) = match transfers.get_mut(&rh) { + Some(t) => match t.complete(Some(&decrypt_fn)) { + Ok((payload, proof)) => ( + payload, + proof, + t.resource.metadata.clone(), + t.resource.resource_hash, + ), + Err(e) => { + break Err(RncpError::ResourceFailed(format!( + "resource assemble/proof failed: {e:?}; parts={}/{} map_hashes={} total_size={} data_size={} flags={:?}", + t.resource.received_count(), + t.resource.total_parts, + t.resource.map_hashes.len(), + t.resource.total_size, + t.resource.data_size, + t.resource.flags, + ))); + } + }, + None => { + break Err(RncpError::ResourceFailed( + "resource assemble/proof failed: transfer missing".into(), + )); + } + }; + let prf_raw = build_resource_proof_packet(link_id, &proof); + let _ = transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: prf_raw, + destination_hash: link_id, + })) + .await; + + transfers.remove(&rh); + + if let Some((original_hash, segment_index)) = segment_routes.remove(&rh) { + let Some(coord) = split_resources.get_mut(&original_hash) else { + break Err(RncpError::ResourceFailed( + "split-resource coordinator missing".into(), + )); + }; + if let Some(meta) = metadata { + coord.set_metadata(meta); + } + if let Err(e) = coord.set_segment_data(segment_index, payload) { + break Err(RncpError::ResourceFailed(format!( + "split segment rejected: {e:?}" + ))); + } + if !coord.is_complete() { + if let Some(ref tx) = progress_tx { + let _ = tx.try_send(coord.progress() as f32); + } + continue; + } + + let payload = match coord.reassemble() { + Ok(p) => p, + Err(e) => { + break Err(RncpError::ResourceFailed(format!( + "split reassemble: {e:?}" + ))); + } + }; + let meta_bytes = coord.metadata.clone(); + let file_name = extract_filename(meta_bytes.as_deref()) + .unwrap_or_else(|| default_file_name(&original_hash)); + split_resources.remove(&original_hash); + if let Some(ref tx) = progress_tx { + let _ = tx.try_send(1.0); + } + break Ok((file_name, payload)); + } + + let file_name = extract_filename(metadata.as_deref()) + .unwrap_or_else(|| default_file_name(&resource_hash)); + if let Some(ref tx) = progress_tx { + let _ = tx.try_send(1.0); + } + break Ok((file_name, payload)); + } + } + rns_wire::context::PacketContext::ResourceHmu => { + let Ok(plaintext) = link.decrypt(body) else { + continue; + }; + let Ok((rh, segment, hashmap)) = + rns_protocol::resource::parse_hashmap_update(&plaintext) + else { + continue; + }; + let Some(t) = transfers.get_mut(&rh) else { + continue; + }; + if let TransferAction::SendRequest(req) = t.hashmap_update(segment, &hashmap) + && let Ok(encrypted) = link.encrypt(&req) + { + let req_raw = build_data_packet( + link_id, + rns_wire::context::PacketContext::ResourceReq, + &encrypted, + ); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: req_raw, + destination_hash: link_id, + })) + .await + .map_err(|_| RncpError::TransportUnavailable)?; + } + } + rns_wire::context::PacketContext::LinkClose if link.receive_teardown(body) => { + break Err(RncpError::ResourceFailed("link closed".into())); + } + _ => {} + } + }; + + if let Some(close_pkt) = build_link_close(&mut link) { + let _ = transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: close_pkt, + destination_hash: link_id, + })) + .await; + } + cleanup_destination(&transport_tx, link_id).await; + + let (file_name, payload) = result?; + let bytes = payload.len(); + let saved_path = save_payload(save_dir, &file_name, &payload, overwrite) + .await + .map_err(RncpError::Io)?; + + tracing::info!( + dest = hex::encode(dest_hash), + link_id = hex::encode(link_id), + bytes = bytes, + file_name = %file_name, + "rncp fetch complete" + ); + + Ok(RncpFetchOutcome { + file_name, + saved_path, + bytes, + link_rtt, + duration: started.elapsed(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn metadata_roundtrip() { + let packed = pack_metadata("hello.txt"); + let parsed = extract_filename(Some(&packed)).unwrap(); + assert_eq!(parsed, "hello.txt"); + } + + #[test] + fn default_file_name_uses_resource_hash_prefix() { + let rh = [0xAB; 32]; + let name = default_file_name(&rh); + assert!(name.starts_with("rncp_")); + assert_eq!(name.len(), "rncp_".len() + 16); + } + + #[test] + fn default_app_name_matches_python() { + assert_eq!(default_rncp_app_name(), "rncp.receive"); + } + + #[test] + fn resource_proof_packet_uses_proof_type() { + let raw = build_resource_proof_packet([0x11; 16], &[0x22; 64]); + let (header, off) = rns_wire::header::PacketHeader::unpack(&raw).unwrap(); + assert_eq!(header.flags.packet_type, rns_wire::flags::PacketType::Proof); + assert_eq!( + header.context, + rns_wire::context::PacketContext::ResourcePrf + ); + assert_eq!(&raw[off..], &[0x22; 64]); + } + + #[test] + fn link_close_packet_uses_authenticated_teardown_payload() { + let dest_hash = [0x33; 16]; + let responder_key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let responder_pub = responder_key.public_key(); + let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1); + let (mut responder, proof_data) = + Link::new_responder(&request_data, &responder_key, dest_hash, 1).unwrap(); + let rtt_data = initiator + .validate_proof(&proof_data, &responder_pub, &responder_pub.to_bytes()) + .unwrap(); + responder.receive_rtt_packet(&rtt_data).unwrap(); + + let raw = build_link_close(&mut initiator).expect("active link emits teardown"); + let (header, offset) = rns_wire::header::PacketHeader::unpack(&raw).unwrap(); + assert_eq!(header.context, rns_wire::context::PacketContext::LinkClose); + assert!(responder.receive_teardown(&raw[offset..])); + } +} diff --git a/crates/rns-runtime/src/rnsh.rs b/crates/rns-runtime/src/rnsh.rs new file mode 100644 index 0000000..9bf5b16 --- /dev/null +++ b/crates/rns-runtime/src/rnsh.rs @@ -0,0 +1,2146 @@ +//! Runtime support for `rnsh`, the Reticulum remote shell utility. + +use std::collections::{HashMap, HashSet, VecDeque}; +#[cfg(unix)] +use std::fs::File; +#[cfg(unix)] +use std::io; +#[cfg(unix)] +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::path::PathBuf; +use std::process::Stdio; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; +use tokio::process::Command; +use tokio::sync::{mpsc, oneshot}; + +use rns_crypto::ed25519::Ed25519PublicKey; +use rns_identity::destination::{DestType, Destination, Direction}; +use rns_identity::identity::Identity; +use rns_link::link::{CloseReason, Link}; +use rns_protocol::channel::{ChannelError, LinkChannel}; +use rns_protocol::channel_message::MessageBase; +use rns_protocol::rnsh::{ + CommandExitedMessage, ErrorMessage, ExecuteCommandMessage, NoopMessage, PROTOCOL_VERSION, + RnshMessage, RnshStreamDataMessage, STREAM_ID_STDERR, STREAM_ID_STDIN, STREAM_ID_STDOUT, + VersionInfoMessage, WindowSizeMessage, +}; +use rns_transport::link_messages::DestinationEvent; +use rns_transport::messages::{ + AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse, +}; + +use crate::link_manager::{ + ChannelSendError, LinkChannelMessage, LinkManager, LinkManagerCommand, register_destination, +}; + +pub const RNSH_APP_NAME: &str = "rnsh"; +pub const RNSH_SOFTWARE_VERSION: &str = "0.2.0"; +const CLIENT_CHUNK_LEN: usize = 240; +const CHANNEL_SEND_RETRY: Duration = Duration::from_millis(20); +const CLIENT_PRE_EOF_DRAIN_MIN: Duration = Duration::from_secs(3); +const CLIENT_PRE_EOF_DRAIN_MAX: Duration = Duration::from_secs(3); +const CLIENT_PRE_EOF_DRAIN_POLL: Duration = Duration::from_millis(25); +const SIGTERM_NUM: i32 = 15; +const SIGKILL_NUM: i32 = 9; + +#[derive(Debug, thiserror::Error)] +pub enum RnshError { + #[error("transport channel unavailable")] + TransportUnavailable, + #[error("timed out waiting for {0}")] + Timeout(&'static str), + #[error("path not found")] + PathTimeout, + #[error("destination identity has not been announced")] + NoIdentity, + #[error("invalid destination hash")] + InvalidDestination, + #[error("link proof validation failed: {0}")] + ProofInvalid(String), + #[error("link handshake failed: {0}")] + HandshakeFailed(String), + #[error("link crypto error: {0}")] + LinkCrypto(String), + #[error("channel error: {0}")] + Channel(String), + #[error("remote error: {0}")] + Remote(String), + #[error("local process error: {0}")] + Process(String), + #[error("local identity has no signing key")] + NoSigningKey, + #[error("listener denied the connection")] + Denied, +} + +impl From for RnshError { + fn from(value: ChannelError) -> Self { + Self::Channel(value.to_string()) + } +} + +pub struct RnshClientConfig { + pub identity: Identity, + pub destination_hash: [u8; 16], + pub command: Vec, + pub no_id: bool, + pub timeout: Duration, + pub stdin_data: Vec, + pub stdin_rx: Option>>, + pub stdout_tx: Option>>, + pub stderr_tx: Option>>, + pub window_rx: Option>, + pub pipe_stdin: bool, + pub pipe_stdout: bool, + pub pipe_stderr: bool, + pub term: Option, + pub rows: Option, + pub cols: Option, + pub hpix: Option, + pub vpix: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RnshWindowSize { + pub rows: Option, + pub cols: Option, + pub hpix: Option, + pub vpix: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RnshClientOutcome { + pub stdout: Vec, + pub stderr: Vec, + pub return_code: i64, +} + +pub struct RnshListenerConfig { + pub identity: Identity, + pub command: Vec, + pub allow_all: bool, + pub allowed: Vec<[u8; 16]>, + pub allowed_identity_files: Vec, + pub allow_remote_command: bool, + pub remote_command_as_args: bool, + pub announce_period: Option, +} + +pub async fn run_rnsh_listener( + transport_tx: mpsc::Sender, + cfg: RnshListenerConfig, +) -> Result<(), RnshError> { + let signing_key = cfg + .identity + .get_signing_key() + .ok_or(RnshError::NoSigningKey)?; + let destination = Destination::new( + Some(&cfg.identity), + Direction::In, + DestType::Single, + RNSH_APP_NAME, + ) + .map_err(|e| RnshError::HandshakeFailed(format!("destination: {e:?}")))?; + let destination_hash = destination.hash; + let event_rx = register_destination(&transport_tx, destination_hash, RNSH_APP_NAME); + + let mut link_mgr = LinkManager::with_destination( + transport_tx.clone(), + event_rx, + &cfg.identity, + RNSH_APP_NAME, + signing_key, + ); + + let announce_tx = transport_tx.clone(); + let announce_packet = build_announce_packet(&cfg.identity, RNSH_APP_NAME)?; + link_mgr.set_announce_handler(move || { + let _ = announce_tx.try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(announce_packet.clone()), + destination_hash, + })); + }); + + let (command_tx, command_rx) = mpsc::channel::(256); + let (channel_tx, mut channel_rx) = mpsc::channel::(256); + let (established_tx, mut established_rx) = mpsc::channel::<[u8; 16]>(64); + let (identified_tx, mut identified_rx) = mpsc::channel::<([u8; 16], [u8; 16])>(64); + let (closed_tx, mut closed_rx) = mpsc::channel::<[u8; 16]>(64); + link_mgr.set_channel_message_channel(channel_tx); + link_mgr.set_link_established_channel(established_tx); + link_mgr.set_link_identified_channel(identified_tx); + link_mgr.set_link_closed_channel(closed_tx); + + let manager_task = tokio::spawn(async move { + link_mgr.run_with_commands(command_rx).await; + }); + + if cfg.announce_period.is_some() { + send_announce(&transport_tx, &cfg.identity, RNSH_APP_NAME).await?; + } + let mut announce_interval = cfg + .announce_period + .filter(|period| *period > 0) + .map(|period| tokio::time::interval(Duration::from_secs(period.max(1)))); + + let mut sessions: HashMap<[u8; 16], ListenerSession> = HashMap::new(); + + loop { + tokio::select! { + maybe_link = established_rx.recv() => { + let Some(link_id) = maybe_link else { break }; + sessions.insert(link_id, ListenerSession::new(cfg.allow_all)); + } + maybe_identified = identified_rx.recv() => { + let Some((link_id, identity_hash)) = maybe_identified else { break }; + let allowed = listener_allowed_identities(&cfg); + if cfg.allow_all || allowed.contains(&identity_hash) { + let session = sessions.entry(link_id).or_insert_with(|| ListenerSession::new(cfg.allow_all)); + session.authorized = true; + session.remote_identity_hash = Some(identity_hash); + session.state = ListenerState::WaitVersion; + } else { + send_manager_message( + &command_tx, + link_id, + ErrorMessage::new(Some("Identity is not allowed.".into()), true, None), + ).await?; + let _ = command_tx.send(LinkManagerCommand::CloseLink { + link_id, + reason: CloseReason::DestinationClosed, + send_teardown: true, + }).await; + } + } + maybe_closed = closed_rx.recv() => { + let Some(link_id) = maybe_closed else { break }; + sessions.remove(&link_id); + } + maybe_msg = channel_rx.recv() => { + let Some(msg) = maybe_msg else { break }; + handle_listener_channel_message( + &command_tx, + &cfg, + &mut sessions, + msg, + ).await?; + } + _ = async { + if let Some(interval) = announce_interval.as_mut() { + interval.tick().await; + } else { + std::future::pending::<()>().await; + } + } => { + send_announce(&transport_tx, &cfg.identity, RNSH_APP_NAME).await?; + } + } + } + + let _ = command_tx.send(LinkManagerCommand::Shutdown).await; + let _ = manager_task.await; + Ok(()) +} + +pub async fn rnsh_client_execute( + transport_tx: mpsc::Sender, + mut cfg: RnshClientConfig, +) -> Result { + let started = Instant::now(); + let deadline = started + cfg.timeout; + let destination_hash = cfg.destination_hash; + + let pubkey = discover_pubkey( + &transport_tx, + destination_hash, + remaining(deadline).min(cfg.timeout), + ) + .await?; + + let (mut link, request_data) = Link::new_initiator(destination_hash, 1); + let link_id = link.link_id; + let (lpkt_tx, mut lpkt_rx) = mpsc::channel::(256); + transport_tx + .send(TransportMessage::RegisterDestination { + hash: link_id, + app_name: "rnsh.client".to_string(), + delivery_tx: Some(lpkt_tx), + }) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + + let link_req_pkt = build_link_request_packet(destination_hash, &request_data); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: link_req_pkt, + destination_hash, + })) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + + let proof_body = match tokio::time::timeout( + remaining(deadline), + wait_for_link_proof(&mut lpkt_rx, link_id), + ) + .await + { + Ok(Ok(body)) => body, + Ok(Err(e)) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(e); + } + Err(_) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(RnshError::Timeout("link proof")); + } + }; + + let identity_ed25519_pub: [u8; 32] = pubkey[32..64] + .try_into() + .map_err(|_| RnshError::ProofInvalid("remote public key length".into()))?; + let verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub) + .map_err(|e| RnshError::ProofInvalid(format!("verify key: {e}")))?; + + let rtt_data = link + .validate_proof(&proof_body, &verify_key, &identity_ed25519_pub) + .map_err(|e| RnshError::ProofInvalid(format!("{e:?}")))?; + let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: rtt_pkt, + destination_hash: link_id, + })) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + + let signing_key = cfg + .identity + .get_signing_key() + .ok_or(RnshError::NoSigningKey)?; + if !cfg.no_id { + let identify_delay = (link.rtt_secs() * 1.1 + 0.05).min(1.0); + let post_identify_delay = identify_delay.clamp(0.25, 1.0); + tokio::time::sleep(Duration::from_secs_f64(post_identify_delay)).await; + let identify_data = link + .identify(&cfg.identity.get_public_key(), &signing_key) + .map_err(|e| RnshError::LinkCrypto(format!("identify: {e:?}")))?; + let identify_pkt = build_data_packet( + link_id, + rns_wire::context::PacketContext::LinkIdentify, + &identify_data, + ); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: identify_pkt, + destination_hash: link_id, + })) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + tokio::time::sleep(Duration::from_secs_f64(post_identify_delay)).await; + } + + let session_keys = link + .session_keys() + .ok_or_else(|| RnshError::LinkCrypto("no session keys".into()))?; + let mut channel = LinkChannel::new_encrypted(link_id, link.rtt_secs(), session_keys); + link.mark_channel_created(); + let mut pending_messages = VecDeque::new(); + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + + send_client_message_when_ready( + &transport_tx, + &mut lpkt_rx, + &mut link, + &mut channel, + &mut pending_messages, + VersionInfoMessage::new(RNSH_SOFTWARE_VERSION), + deadline, + ) + .await?; + + loop { + if let Some(message) = pop_or_receive_client_message( + &transport_tx, + &mut lpkt_rx, + &mut link, + &mut channel, + &mut pending_messages, + deadline, + ) + .await? + { + match message { + RnshMessage::VersionInfo(version) => { + if version.protocol_version != PROTOCOL_VERSION { + cleanup_destination(&transport_tx, link_id).await; + return Err(RnshError::Remote("incompatible rnsh protocol".into())); + } + tokio::time::sleep(Duration::from_millis(75)).await; + break; + } + RnshMessage::Error(err) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(RnshError::Remote( + err.msg.unwrap_or_else(|| "remote error".into()), + )); + } + _ => {} + } + } + } + + let execute = ExecuteCommandMessage::new( + Some(cfg.command.clone()), + cfg.pipe_stdin, + cfg.pipe_stdout, + cfg.pipe_stderr, + None, + cfg.term.clone(), + cfg.rows, + cfg.cols, + cfg.hpix, + cfg.vpix, + ); + send_client_message_when_ready( + &transport_tx, + &mut lpkt_rx, + &mut link, + &mut channel, + &mut pending_messages, + execute, + deadline, + ) + .await?; + + let return_code = match run_client_io_loop( + &transport_tx, + &mut lpkt_rx, + &mut link, + &mut channel, + &mut pending_messages, + ClientIoState { + stdout: &mut stdout, + stderr: &mut stderr, + cfg: &mut cfg, + }, + deadline, + ) + .await + { + Ok(return_code) => return_code, + Err(error) => { + cleanup_destination(&transport_tx, link_id).await; + return Err(error); + } + }; + + if let Some(close_pkt) = build_link_close(&mut link) { + let _ = transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: close_pkt, + destination_hash: link_id, + })) + .await; + } + cleanup_destination(&transport_tx, link_id).await; + + Ok(RnshClientOutcome { + stdout, + stderr, + return_code, + }) +} + +fn pending_has_remote_terminal(pending_messages: &VecDeque) -> bool { + pending_messages.iter().any(|message| { + matches!( + message, + RnshMessage::CommandExited(_) | RnshMessage::Error(_) + ) + }) +} + +struct ClientIoState<'a> { + stdout: &'a mut Vec, + stderr: &'a mut Vec, + cfg: &'a mut RnshClientConfig, +} + +async fn run_client_io_loop( + transport_tx: &mpsc::Sender, + lpkt_rx: &mut mpsc::Receiver, + link: &mut Link, + channel: &mut LinkChannel, + pending_messages: &mut VecDeque, + io: ClientIoState<'_>, + deadline: Instant, +) -> Result { + let ClientIoState { + stdout, + stderr, + cfg, + } = io; + + let mut stdin_rx = cfg.stdin_rx.take(); + if stdin_rx.is_none() && cfg.pipe_stdin { + let (tx, rx) = mpsc::channel(16); + let stdin_data = std::mem::take(&mut cfg.stdin_data); + tokio::spawn(async move { + for chunk in stdin_data.chunks(CLIENT_CHUNK_LEN) { + if tx.send(chunk.to_vec()).await.is_err() { + return; + } + } + let _ = tx.send(Vec::new()).await; + }); + stdin_rx = Some(rx); + } + let mut stdin_eof_sent = stdin_rx.is_none(); + let stdout_tx = cfg.stdout_tx.take(); + let stderr_tx = cfg.stderr_tx.take(); + let mut window_rx = cfg.window_rx.take(); + + loop { + while let Some(message) = pending_messages.pop_front() { + if let Some(return_code) = handle_client_message( + transport_tx, + link, + channel, + ClientMessageOutput { + stdout, + stderr, + stdout_tx: stdout_tx.as_ref(), + stderr_tx: stderr_tx.as_ref(), + }, + message, + ) + .await? + { + return Ok(return_code); + } + } + + resend_timed_out_client_channel_messages(transport_tx, link, channel).await?; + if Instant::now() >= deadline { + return Err(RnshError::Timeout("rnsh channel")); + } + + let retry_wait = channel + .next_timeout_duration() + .unwrap_or_else(|| Duration::from_secs(1)) + .min(Duration::from_secs(1)) + .min(remaining(deadline)); + let deadline_wait = remaining(deadline); + + tokio::select! { + maybe_event = lpkt_rx.recv() => { + let Some(event) = maybe_event else { + return Err(RnshError::HandshakeFailed("link channel closed".into())); + }; + process_client_destination_event( + transport_tx, + link, + channel, + pending_messages, + event, + ).await?; + } + maybe_chunk = recv_optional_stdin_chunk(&mut stdin_rx), if !stdin_eof_sent => { + match maybe_chunk { + Some(data) if !data.is_empty() => { + for chunk in data.chunks(CLIENT_CHUNK_LEN) { + if pending_has_remote_terminal(pending_messages) { + break; + } + send_client_message_when_ready( + transport_tx, + lpkt_rx, + link, + channel, + pending_messages, + RnshStreamDataMessage::new(STREAM_ID_STDIN, chunk.to_vec(), false), + deadline, + ).await?; + } + } + Some(_) | None => { + if !pending_has_remote_terminal(pending_messages) { + drain_client_messages_before_stdin_eof( + transport_tx, + lpkt_rx, + link, + channel, + pending_messages, + deadline, + ) + .await?; + } + if !pending_has_remote_terminal(pending_messages) { + send_client_message_when_ready( + transport_tx, + lpkt_rx, + link, + channel, + pending_messages, + RnshStreamDataMessage::new(STREAM_ID_STDIN, Vec::new(), true), + deadline, + ).await?; + } + stdin_eof_sent = true; + } + } + } + maybe_window = recv_optional_window_size(&mut window_rx) => { + match maybe_window { + Some(window) => { + send_client_message_when_ready( + transport_tx, + lpkt_rx, + link, + channel, + pending_messages, + WindowSizeMessage::new(window.rows, window.cols, window.hpix, window.vpix), + deadline, + ).await?; + } + None => { + window_rx = None; + } + } + } + _ = tokio::time::sleep(retry_wait) => {} + _ = tokio::time::sleep(deadline_wait) => { + return Err(RnshError::Timeout("rnsh channel")); + } + } + } +} + +async fn recv_optional_stdin_chunk(rx: &mut Option>>) -> Option> { + match rx { + Some(rx) => rx.recv().await, + None => std::future::pending::>>().await, + } +} + +async fn recv_optional_window_size( + rx: &mut Option>, +) -> Option { + match rx { + Some(rx) => rx.recv().await, + None => std::future::pending::>().await, + } +} + +struct ClientMessageOutput<'a> { + stdout: &'a mut Vec, + stderr: &'a mut Vec, + stdout_tx: Option<&'a mpsc::Sender>>, + stderr_tx: Option<&'a mpsc::Sender>>, +} + +async fn handle_client_message( + transport_tx: &mpsc::Sender, + link: &mut Link, + channel: &mut LinkChannel, + output: ClientMessageOutput<'_>, + message: RnshMessage, +) -> Result, RnshError> { + let ClientMessageOutput { + stdout, + stderr, + stdout_tx, + stderr_tx, + } = output; + + match message { + RnshMessage::StreamData(stream) => match stream.stream_id { + STREAM_ID_STDOUT => { + stdout.extend_from_slice(&stream.data); + if let Some(tx) = stdout_tx + && !stream.data.is_empty() + { + tx.send(stream.data) + .await + .map_err(|_| RnshError::Process("stdout stream receiver closed".into()))?; + } + Ok(None) + } + STREAM_ID_STDERR => { + stderr.extend_from_slice(&stream.data); + if let Some(tx) = stderr_tx + && !stream.data.is_empty() + { + tx.send(stream.data) + .await + .map_err(|_| RnshError::Process("stderr stream receiver closed".into()))?; + } + Ok(None) + } + _ => Ok(None), + }, + RnshMessage::CommandExited(exited) => Ok(Some(exited.return_code)), + RnshMessage::Error(err) => Err(RnshError::Remote( + err.msg.unwrap_or_else(|| "remote error".into()), + )), + RnshMessage::Noop(_) => { + let _ = send_client_channel_message(transport_tx, link, channel, &NoopMessage).await; + Ok(None) + } + _ => Ok(None), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ListenerState { + WaitIdent, + WaitVersion, + WaitCommand, + Running, +} + +struct ListenerSession { + authorized: bool, + remote_identity_hash: Option<[u8; 16]>, + state: ListenerState, + stdin: Option, + window: Option, + process_cleanup: Option, +} + +impl ListenerSession { + fn new(allow_all: bool) -> Self { + Self { + authorized: allow_all, + remote_identity_hash: None, + state: if allow_all { + ListenerState::WaitVersion + } else { + ListenerState::WaitIdent + }, + stdin: None, + window: None, + process_cleanup: None, + } + } +} + +enum ProcessInput { + Pipe(tokio::process::ChildStdin), + #[cfg(unix)] + Pty(tokio::fs::File), +} + +impl ProcessInput { + async fn write_all(&mut self, data: &[u8]) -> Result<(), RnshError> { + match self { + Self::Pipe(stdin) => stdin + .write_all(data) + .await + .map_err(|e| RnshError::Process(format!("write stdin: {e}"))), + #[cfg(unix)] + Self::Pty(master) => master + .write_all(data) + .await + .map_err(|e| RnshError::Process(format!("write pty: {e}"))), + } + } + + async fn eof(&mut self) -> Result<(), RnshError> { + match self { + Self::Pipe(_) => Ok(()), + #[cfg(unix)] + Self::Pty(master) => master + .write_all(&[0x04]) + .await + .map_err(|e| RnshError::Process(format!("write pty eof: {e}"))), + } + } +} + +struct PtyWindowTarget { + #[cfg(unix)] + file: File, +} + +impl PtyWindowTarget { + #[cfg(unix)] + fn set_size( + &self, + rows: Option, + cols: Option, + hpix: Option, + vpix: Option, + ) -> Result<(), RnshError> { + let winsize = libc_winsize(rows, cols, hpix, vpix); + let rc = + unsafe { nix::libc::ioctl(self.file.as_raw_fd(), nix::libc::TIOCSWINSZ, &winsize) }; + if rc == -1 { + return Err(RnshError::Process(format!( + "set pty window size: {}", + std::io::Error::last_os_error() + ))); + } + Ok(()) + } + + #[cfg(not(unix))] + fn set_size( + &self, + _rows: Option, + _cols: Option, + _hpix: Option, + _vpix: Option, + ) -> Result<(), RnshError> { + Ok(()) + } +} + +struct ListenerProcess { + stdin: ProcessInput, + window: Option, + cleanup: ListenerProcessCleanup, +} + +struct ListenerProcessCleanup { + stop_tx: Option>, +} + +impl Drop for ListenerProcessCleanup { + fn drop(&mut self) { + if let Some(tx) = self.stop_tx.take() { + let _ = tx.send(()); + } + } +} + +#[cfg(unix)] +struct ProcessPty { + master: File, + slave: OwnedFd, +} + +#[cfg(not(unix))] +struct ProcessPty; + +#[cfg(unix)] +fn libc_winsize( + rows: Option, + cols: Option, + hpix: Option, + vpix: Option, +) -> nix::libc::winsize { + nix::libc::winsize { + ws_row: rows.unwrap_or(0).min(u16::MAX as u32) as u16, + ws_col: cols.unwrap_or(0).min(u16::MAX as u32) as u16, + ws_xpixel: hpix.unwrap_or(0).min(u16::MAX as u32) as u16, + ws_ypixel: vpix.unwrap_or(0).min(u16::MAX as u32) as u16, + } +} + +#[cfg(unix)] +fn open_process_pty( + rows: Option, + cols: Option, + hpix: Option, + vpix: Option, +) -> Result { + let winsize = nix::pty::Winsize { + ws_row: rows.unwrap_or(0).min(u16::MAX as u32) as u16, + ws_col: cols.unwrap_or(0).min(u16::MAX as u32) as u16, + ws_xpixel: hpix.unwrap_or(0).min(u16::MAX as u32) as u16, + ws_ypixel: vpix.unwrap_or(0).min(u16::MAX as u32) as u16, + }; + let pty = nix::pty::openpty(Some(&winsize), None) + .map_err(|e| RnshError::Process(format!("open pty: {e}")))?; + Ok(ProcessPty { + master: File::from(pty.master), + slave: pty.slave, + }) +} + +#[cfg(not(unix))] +fn open_process_pty( + _rows: Option, + _cols: Option, + _hpix: Option, + _vpix: Option, +) -> Result { + Err(RnshError::Process( + "PTY-backed local process mode is only supported on Unix".into(), + )) +} + +#[cfg(unix)] +fn pty_stdio(pty: &ProcessPty) -> Result { + let fd = nix::unistd::dup(pty.slave.as_raw_fd()) + .map_err(|e| RnshError::Process(format!("dup pty: {e}")))?; + let owned = unsafe { OwnedFd::from_raw_fd(fd) }; + Ok(Stdio::from(File::from(owned))) +} + +#[cfg(not(unix))] +fn pty_stdio(_pty: &ProcessPty) -> Result { + Err(RnshError::Process( + "PTY-backed local process mode is only supported on Unix".into(), + )) +} + +#[cfg(unix)] +fn configure_pty_child(cmd: &mut Command, pty: &ProcessPty) { + let slave_fd = pty.slave.as_raw_fd(); + unsafe { + cmd.pre_exec(move || { + if nix::libc::setsid() == -1 { + return Err(io::Error::last_os_error()); + } + #[cfg(target_os = "android")] + let tiocsctty = nix::libc::TIOCSCTTY as nix::libc::c_int; + #[cfg(not(target_os = "android"))] + let tiocsctty = nix::libc::TIOCSCTTY as nix::libc::c_ulong; + if nix::libc::ioctl(slave_fd, tiocsctty, 0) == -1 { + return Err(io::Error::last_os_error()); + } + let pid = nix::libc::getpid(); + if nix::libc::tcsetpgrp(slave_fd, pid) == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } +} + +#[cfg(not(unix))] +fn configure_pty_child(_cmd: &mut Command, _pty: &ProcessPty) {} + +#[cfg(unix)] +fn pty_input(pty: &ProcessPty) -> Result { + let file = pty + .master + .try_clone() + .map_err(|e| RnshError::Process(format!("clone pty stdin: {e}")))?; + Ok(ProcessInput::Pty(tokio::fs::File::from_std(file))) +} + +#[cfg(not(unix))] +fn pty_input(_pty: &ProcessPty) -> Result { + Err(RnshError::Process( + "PTY-backed local process mode is only supported on Unix".into(), + )) +} + +#[cfg(unix)] +fn pty_reader_file(pty: &ProcessPty) -> Result { + let file = pty + .master + .try_clone() + .map_err(|e| RnshError::Process(format!("clone pty output: {e}")))?; + Ok(tokio::fs::File::from_std(file)) +} + +#[cfg(not(unix))] +fn pty_reader_file(_pty: &ProcessPty) -> Result { + Err(RnshError::Process( + "PTY-backed local process mode is only supported on Unix".into(), + )) +} + +#[cfg(unix)] +fn pty_window_target(pty: ProcessPty) -> PtyWindowTarget { + PtyWindowTarget { file: pty.master } +} + +#[cfg(not(unix))] +fn pty_window_target(_pty: ProcessPty) -> PtyWindowTarget { + PtyWindowTarget {} +} + +async fn handle_listener_channel_message( + command_tx: &mpsc::Sender, + cfg: &RnshListenerConfig, + sessions: &mut HashMap<[u8; 16], ListenerSession>, + msg: LinkChannelMessage, +) -> Result<(), RnshError> { + let session = sessions + .entry(msg.link_id) + .or_insert_with(|| ListenerSession::new(cfg.allow_all)); + + if !session.authorized { + return Ok(()); + } + + let decoded = RnshMessage::decode(msg.msg_type, &msg.payload) + .map_err(|e| RnshError::Channel(e.to_string()))?; + + match session.state { + ListenerState::WaitIdent => Ok(()), + ListenerState::WaitVersion => match decoded { + RnshMessage::VersionInfo(version) => { + if version.protocol_version != PROTOCOL_VERSION { + send_manager_message( + command_tx, + msg.link_id, + ErrorMessage::new(Some("Incompatible protocol".into()), true, None), + ) + .await?; + return Err(RnshError::Remote("incompatible rnsh protocol".into())); + } + send_manager_message( + command_tx, + msg.link_id, + VersionInfoMessage::new(RNSH_SOFTWARE_VERSION), + ) + .await?; + session.state = ListenerState::WaitCommand; + Ok(()) + } + _ => { + send_manager_message( + command_tx, + msg.link_id, + ErrorMessage::new( + Some("Protocol error (LSSTATE_WAIT_VERS)".into()), + true, + None, + ), + ) + .await + } + }, + ListenerState::WaitCommand => match decoded { + RnshMessage::ExecuteCommand(execute) => { + let command = match select_listener_command( + &cfg.command, + execute.cmdline.as_deref(), + cfg.allow_remote_command, + cfg.remote_command_as_args, + ) { + Ok(command) => command, + Err(reason) => { + send_manager_message( + command_tx, + msg.link_id, + ErrorMessage::new(Some(reason), true, None), + ) + .await?; + close_link_after_error(command_tx.clone(), msg.link_id); + return Ok(()); + } + }; + let stdin = match start_listener_process( + command_tx.clone(), + msg.link_id, + ListenerProcessRequest { + command: &command, + pipe_stdin: execute.pipe_stdin, + pipe_stdout: execute.pipe_stdout, + pipe_stderr: execute.pipe_stderr, + term: execute.term.as_deref(), + rows: execute.rows, + cols: execute.cols, + hpix: execute.hpix, + vpix: execute.vpix, + remote_identity_hash: session.remote_identity_hash, + }, + ) + .await + { + Ok(stdin) => stdin, + Err(error) => { + send_manager_message( + command_tx, + msg.link_id, + ErrorMessage::new(Some(error.to_string()), true, None), + ) + .await?; + close_link_after_error(command_tx.clone(), msg.link_id); + return Ok(()); + } + }; + session.stdin = Some(stdin.stdin); + session.window = stdin.window; + session.process_cleanup = Some(stdin.cleanup); + session.state = ListenerState::Running; + Ok(()) + } + _ => { + send_manager_message( + command_tx, + msg.link_id, + ErrorMessage::new(Some("Protocol error (LSSTATE_WAIT_CMD)".into()), true, None), + ) + .await + } + }, + ListenerState::Running => match decoded { + RnshMessage::StreamData(stream) => { + if stream.stream_id != STREAM_ID_STDIN { + send_manager_message( + command_tx, + msg.link_id, + ErrorMessage::new( + Some("Protocol error (LSSTATE_RUNNING)".into()), + true, + None, + ), + ) + .await?; + return Ok(()); + } + if let Some(stdin) = session.stdin.as_mut() + && !stream.data.is_empty() + { + stdin.write_all(&stream.data).await?; + } + if stream.eof { + if let Some(stdin) = session.stdin.as_mut() { + stdin.eof().await?; + } + if session + .stdin + .as_ref() + .is_some_and(|stdin| matches!(stdin, ProcessInput::Pipe(_))) + { + session.stdin.take(); + } + } + Ok(()) + } + RnshMessage::WindowSize(window) => { + if let Some(target) = session.window.as_ref() { + target.set_size(window.rows, window.cols, window.hpix, window.vpix)?; + } + Ok(()) + } + RnshMessage::Noop(_) => { + send_manager_message(command_tx, msg.link_id, NoopMessage).await + } + _ => Ok(()), + }, + } +} + +struct ListenerProcessRequest<'a> { + command: &'a [String], + pipe_stdin: bool, + pipe_stdout: bool, + pipe_stderr: bool, + term: Option<&'a str>, + rows: Option, + cols: Option, + hpix: Option, + vpix: Option, + remote_identity_hash: Option<[u8; 16]>, +} + +async fn start_listener_process( + command_tx: mpsc::Sender, + link_id: [u8; 16], + request: ListenerProcessRequest<'_>, +) -> Result { + let ListenerProcessRequest { + command, + pipe_stdin, + pipe_stdout, + pipe_stderr, + term, + rows, + cols, + hpix, + vpix, + remote_identity_hash, + } = request; + + if command.is_empty() { + return Err(RnshError::Process("no command specified".into())); + } + + let uses_pty = !(pipe_stdin && pipe_stdout && pipe_stderr); + let mut cmd = Command::new(&command[0]); + cmd.args(&command[1..]) + .env("TERM", term.unwrap_or("xterm")) + .env( + "RNS_REMOTE_IDENTITY", + remote_identity_hash + .map(|hash| format!("<{}>", hex::encode(hash))) + .unwrap_or_default(), + ); + + let mut pty = if uses_pty { + Some(open_process_pty(rows, cols, hpix, vpix)?) + } else { + None + }; + + if pipe_stdin { + cmd.stdin(Stdio::piped()); + } else { + let Some(ref pty) = pty else { + return Err(RnshError::Process("pty unavailable".into())); + }; + cmd.stdin(pty_stdio(pty)?); + } + if pipe_stdout { + cmd.stdout(Stdio::piped()); + } else { + let Some(ref pty) = pty else { + return Err(RnshError::Process("pty unavailable".into())); + }; + cmd.stdout(pty_stdio(pty)?); + } + if pipe_stderr { + cmd.stderr(Stdio::piped()); + } else { + let Some(ref pty) = pty else { + return Err(RnshError::Process("pty unavailable".into())); + }; + cmd.stderr(pty_stdio(pty)?); + } + if let Some(ref pty) = pty { + configure_pty_child(&mut cmd, pty); + } + + let mut child = cmd + .spawn() + .map_err(|e| RnshError::Process(format!("could not start {}: {e}", command[0])))?; + + let stdin = if pipe_stdin { + ProcessInput::Pipe( + child + .stdin + .take() + .ok_or_else(|| RnshError::Process("could not open process stdin".into()))?, + ) + } else { + let pty = pty + .as_ref() + .ok_or_else(|| RnshError::Process("pty unavailable".into()))?; + pty_input(pty)? + }; + + let mut reader_tasks = Vec::new(); + if pipe_stdout { + let stdout = child + .stdout + .take() + .ok_or_else(|| RnshError::Process("could not open process stdout".into()))?; + reader_tasks.push(tokio::spawn(stream_reader_task( + command_tx.clone(), + link_id, + STREAM_ID_STDOUT, + stdout, + ))); + } + if pipe_stderr { + let stderr = child + .stderr + .take() + .ok_or_else(|| RnshError::Process("could not open process stderr".into()))?; + reader_tasks.push(tokio::spawn(stream_reader_task( + command_tx.clone(), + link_id, + STREAM_ID_STDERR, + stderr, + ))); + } + if let Some(ref pty) = pty + && (!pipe_stdout || !pipe_stderr) + { + let stream_id = if !pipe_stdout { + STREAM_ID_STDOUT + } else { + STREAM_ID_STDERR + }; + reader_tasks.push(tokio::spawn(stream_reader_task( + command_tx.clone(), + link_id, + stream_id, + pty_reader_file(pty)?, + ))); + } + + let window = pty.take().map(pty_window_target); + let child_pid = if uses_pty { child.id() } else { None }; + let (stop_tx, stop_rx) = oneshot::channel(); + tokio::spawn(async move { + let mut stopped = false; + let code = tokio::select! { + status = child.wait() => { + match status { + Ok(status) => status.code().unwrap_or(255) as i64, + Err(_) => 255, + } + } + _ = stop_rx => { + stopped = true; + terminate_child_process_group(child_pid, SIGTERM_NUM); + tokio::time::sleep(Duration::from_millis(200)).await; + match tokio::time::timeout(Duration::from_millis(500), child.wait()).await { + Ok(Ok(status)) => status.code().unwrap_or(255) as i64, + _ => { + terminate_child_process_group(child_pid, SIGKILL_NUM); + let _ = child.kill().await; + 255 + } + } + } + }; + for task in reader_tasks { + let _ = task.await; + } + if !stopped { + let _ = + send_manager_message(&command_tx, link_id, CommandExitedMessage::new(code)).await; + } + }); + + Ok(ListenerProcess { + stdin, + window, + cleanup: ListenerProcessCleanup { + stop_tx: Some(stop_tx), + }, + }) +} + +#[cfg(unix)] +fn terminate_child_process_group(child_pid: Option, signal: i32) { + let Some(pid) = child_pid else { + return; + }; + let pgid = -(pid as i32); + unsafe { + nix::libc::kill(pgid, signal); + } +} + +#[cfg(not(unix))] +fn terminate_child_process_group(_child_pid: Option, _signal: i32) {} + +fn close_link_after_error(command_tx: mpsc::Sender, link_id: [u8; 16]) { + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(750)).await; + let _ = command_tx + .send(LinkManagerCommand::CloseLink { + link_id, + reason: CloseReason::DestinationClosed, + send_teardown: true, + }) + .await; + }); +} + +async fn stream_reader_task( + command_tx: mpsc::Sender, + link_id: [u8; 16], + stream_id: u16, + mut reader: R, +) where + R: AsyncRead + Unpin, +{ + let mut buf = [0u8; CLIENT_CHUNK_LEN]; + loop { + match reader.read(&mut buf).await { + Ok(0) => break, + Ok(n) => { + let msg = RnshStreamDataMessage::new(stream_id, buf[..n].to_vec(), false); + if send_manager_message(&command_tx, link_id, msg) + .await + .is_err() + { + return; + } + } + Err(_) => break, + } + } + let _ = send_manager_message( + &command_tx, + link_id, + RnshStreamDataMessage::new(stream_id, Vec::new(), true), + ) + .await; +} + +async fn send_manager_message( + command_tx: &mpsc::Sender, + link_id: [u8; 16], + message: M, +) -> Result<(), RnshError> +where + M: MessageBase + Clone + 'static, +{ + loop { + let (result_tx, result_rx) = oneshot::channel(); + command_tx + .send(LinkManagerCommand::SendChannelMessage { + link_id, + message: Box::new(message.clone()), + result_tx: Some(result_tx), + }) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + match result_rx + .await + .map_err(|_| RnshError::TransportUnavailable)? + { + Ok(_) => return Ok(()), + Err(ChannelSendError::Channel(ChannelError::NotReady)) => { + tokio::time::sleep(CHANNEL_SEND_RETRY).await; + } + Err(ChannelSendError::LinkNotFound) => { + return Err(RnshError::Channel("link not found".into())); + } + Err(e) => return Err(RnshError::Channel(e.to_string())), + } + } +} + +async fn send_client_message_when_ready( + transport_tx: &mpsc::Sender, + lpkt_rx: &mut mpsc::Receiver, + link: &mut Link, + channel: &mut LinkChannel, + pending_messages: &mut VecDeque, + message: M, + deadline: Instant, +) -> Result<(), RnshError> +where + M: MessageBase, +{ + loop { + match send_client_channel_message(transport_tx, link, channel, &message).await { + Ok(()) => return Ok(()), + Err(RnshError::Channel(err)) if err.contains("not ready") => { + let _ = receive_client_messages( + transport_tx, + lpkt_rx, + link, + channel, + pending_messages, + deadline, + Duration::from_millis(100), + ) + .await?; + } + Err(e) => return Err(e), + } + } +} + +async fn send_client_channel_message( + transport_tx: &mpsc::Sender, + link: &mut Link, + channel: &mut LinkChannel, + message: &dyn MessageBase, +) -> Result<(), RnshError> { + let prepared = channel.prepare_send_tracked(message)?; + send_client_channel_data( + transport_tx, + link, + channel, + prepared.sequence, + &prepared.data, + ) + .await +} + +async fn send_client_channel_data( + transport_tx: &mpsc::Sender, + link: &mut Link, + channel: &mut LinkChannel, + sequence: u16, + data: &[u8], +) -> Result<(), RnshError> { + let link_id = *channel.link_id(); + let channel_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Channel, + }; + let mut raw = channel_header.pack(); + raw.extend_from_slice(data); + let packet_hash = rns_wire::hash::packet_hash(&raw, channel_header.flags.header_type); + channel.track_outbound_packet_hash(packet_hash, sequence); + link.record_tx(raw.len()); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: link_id, + })) + .await + .map_err(|_| RnshError::TransportUnavailable) +} + +async fn resend_timed_out_client_channel_messages( + transport_tx: &mpsc::Sender, + link: &mut Link, + channel: &mut LinkChannel, +) -> Result<(), RnshError> { + for sequence in channel.timed_out_sequences() { + let Some(data) = channel.timeout(sequence)? else { + continue; + }; + send_client_channel_data(transport_tx, link, channel, sequence, &data).await?; + } + Ok(()) +} + +async fn pop_or_receive_client_message( + transport_tx: &mpsc::Sender, + lpkt_rx: &mut mpsc::Receiver, + link: &mut Link, + channel: &mut LinkChannel, + pending_messages: &mut VecDeque, + deadline: Instant, +) -> Result, RnshError> { + if let Some(message) = pending_messages.pop_front() { + return Ok(Some(message)); + } + receive_client_messages( + transport_tx, + lpkt_rx, + link, + channel, + pending_messages, + deadline, + remaining(deadline), + ) + .await?; + Ok(pending_messages.pop_front()) +} + +async fn drain_client_messages_before_stdin_eof( + transport_tx: &mpsc::Sender, + lpkt_rx: &mut mpsc::Receiver, + link: &mut Link, + channel: &mut LinkChannel, + pending_messages: &mut VecDeque, + deadline: Instant, +) -> Result<(), RnshError> { + let rtt_scaled = Duration::from_secs_f64((link.rtt_secs() * 5.0).max(0.0)); + let drain_for = rtt_scaled + .max(CLIENT_PRE_EOF_DRAIN_MIN) + .min(CLIENT_PRE_EOF_DRAIN_MAX) + .min(remaining(deadline)); + let drain_until = Instant::now() + drain_for; + + while Instant::now() < drain_until && !pending_has_remote_terminal(pending_messages) { + let wait = + CLIENT_PRE_EOF_DRAIN_POLL.min(drain_until.saturating_duration_since(Instant::now())); + if wait.is_zero() { + break; + } + receive_client_messages( + transport_tx, + lpkt_rx, + link, + channel, + pending_messages, + deadline, + wait, + ) + .await?; + } + + Ok(()) +} + +async fn receive_client_messages( + transport_tx: &mpsc::Sender, + lpkt_rx: &mut mpsc::Receiver, + link: &mut Link, + channel: &mut LinkChannel, + pending_messages: &mut VecDeque, + deadline: Instant, + wait: Duration, +) -> Result { + if Instant::now() >= deadline { + return Err(RnshError::Timeout("rnsh channel")); + } + resend_timed_out_client_channel_messages(transport_tx, link, channel).await?; + let wait = wait + .min(channel.next_timeout_duration().unwrap_or(wait)) + .min(remaining(deadline)); + let event = match tokio::time::timeout(wait, lpkt_rx.recv()).await { + Ok(Some(event)) => event, + Ok(None) => return Err(RnshError::HandshakeFailed("link channel closed".into())), + Err(_) => { + resend_timed_out_client_channel_messages(transport_tx, link, channel).await?; + return Ok(false); + } + }; + + process_client_destination_event(transport_tx, link, channel, pending_messages, event).await +} + +async fn process_client_destination_event( + transport_tx: &mpsc::Sender, + link: &mut Link, + channel: &mut LinkChannel, + pending_messages: &mut VecDeque, + event: DestinationEvent, +) -> Result { + let DestinationEvent::InboundPacket { raw, .. } = event else { + return Ok(false); + }; + let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) { + Ok(parsed) => parsed, + Err(_) => return Ok(false), + }; + if header.destination_hash != *channel.link_id() { + return Ok(false); + } + let body = &raw[data_offset..]; + match header.flags.packet_type { + rns_wire::flags::PacketType::Proof if body.len() >= 96 => { + let mut packet_hash = [0u8; 32]; + packet_hash.copy_from_slice(&body[..32]); + if link.validate_packet_proof(&packet_hash, body) { + channel.delivered_by_packet_hash(&packet_hash, link.rtt_secs()); + } + } + rns_wire::flags::PacketType::Data => match header.context { + rns_wire::context::PacketContext::Keepalive + if body.first() == Some(&rns_link::constants::KEEPALIVE_REQUEST) => + { + send_keepalive_response(transport_tx, *channel.link_id()).await?; + } + rns_wire::context::PacketContext::LinkClose if link.receive_teardown(body) => { + return Err(RnshError::HandshakeFailed("link closed by remote".into())); + } + rns_wire::context::PacketContext::Channel => { + link.record_inbound(); + let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type); + if let Ok(proof_data) = link.prove_packet_with_link_key(&packet_hash) { + send_link_packet_proof( + transport_tx, + *channel.link_id(), + &proof_data, + rns_wire::context::PacketContext::None, + ) + .await?; + } + for (msg_type, payload) in channel.receive_data(body)? { + let decoded = RnshMessage::decode(msg_type, &payload) + .map_err(|e| RnshError::Channel(e.to_string()))?; + pending_messages.push_back(decoded); + } + return Ok(true); + } + _ => {} + }, + _ => {} + } + Ok(false) +} + +async fn discover_pubkey( + transport_tx: &mpsc::Sender, + dest_hash: [u8; 16], + path_wait: Duration, +) -> Result<[u8; 64], RnshError> { + if let Some(pk) = lookup_pubkey(transport_tx, dest_hash).await? { + return Ok(pk); + } + + transport_tx + .send(TransportMessage::RequestPath { + destination_hash: dest_hash, + }) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + let (await_tx, await_rx) = oneshot::channel(); + transport_tx + .send(TransportMessage::AwaitPath { + dest: dest_hash, + reply: await_tx, + }) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + let found = tokio::time::timeout(path_wait, await_rx) + .await + .map_err(|_| RnshError::PathTimeout)? + .unwrap_or(false); + if !found { + return Err(RnshError::PathTimeout); + } + lookup_pubkey(transport_tx, dest_hash) + .await? + .ok_or(RnshError::NoIdentity) +} + +async fn lookup_pubkey( + transport_tx: &mpsc::Sender, + dest_hash: [u8; 16], +) -> Result, RnshError> { + let (resp_tx, resp_rx) = oneshot::channel(); + transport_tx + .send(TransportMessage::Rpc { + query: TransportQuery::GetRecentAnnounces, + response_tx: resp_tx, + }) + .await + .map_err(|_| RnshError::TransportUnavailable)?; + let resp = resp_rx.await.map_err(|_| RnshError::TransportUnavailable)?; + let announces: Vec = match resp { + TransportQueryResponse::Announces(v) => v, + _ => Vec::new(), + }; + Ok(announces + .into_iter() + .find(|a| a.dest_hash == dest_hash) + .and_then(|a| a.public_key)) +} + +async fn wait_for_link_proof( + rx: &mut mpsc::Receiver, + link_id: [u8; 16], +) -> Result, RnshError> { + while let Some(event) = rx.recv().await { + let DestinationEvent::InboundPacket { raw, .. } = event else { + continue; + }; + let Ok((header, data_offset)) = rns_wire::header::PacketHeader::unpack(&raw) else { + continue; + }; + if header.flags.packet_type == rns_wire::flags::PacketType::Proof + && header.destination_hash == link_id + && raw.len() > data_offset + { + return Ok(raw[data_offset..].to_vec()); + } + } + Err(RnshError::HandshakeFailed("channel closed".into())) +} + +async fn cleanup_destination(transport_tx: &mpsc::Sender, link_id: [u8; 16]) { + let _ = transport_tx.try_send(TransportMessage::DeregisterDestination { hash: link_id }); +} + +async fn send_keepalive_response( + transport_tx: &mpsc::Sender, + link_id: [u8; 16], +) -> Result<(), RnshError> { + let raw = build_data_packet( + link_id, + rns_wire::context::PacketContext::Keepalive, + &[rns_link::constants::KEEPALIVE_RESPONSE], + ); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw, + destination_hash: link_id, + })) + .await + .map_err(|_| RnshError::TransportUnavailable) +} + +async fn send_link_packet_proof( + transport_tx: &mpsc::Sender, + link_id: [u8; 16], + proof_data: &[u8], + context: rns_wire::context::PacketContext, +) -> Result<(), RnshError> { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Proof, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(proof_data); + transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: link_id, + })) + .await + .map_err(|_| RnshError::TransportUnavailable) +} + +fn build_link_close(link: &mut Link) -> Option { + let link_id = link.link_id; + let teardown_data = link.teardown(CloseReason::InitiatorClosed)?; + Some(build_data_packet( + link_id, + rns_wire::context::PacketContext::LinkClose, + &teardown_data, + )) +} + +fn build_link_request_packet(dest_hash: [u8; 16], request_data: &[u8]) -> Bytes { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::LinkRequest, + }, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(request_data); + Bytes::from(raw) +} + +fn build_data_packet( + link_id: [u8; 16], + context: rns_wire::context::PacketContext, + body: &[u8], +) -> Bytes { + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(body); + Bytes::from(raw) +} + +async fn send_announce( + tx: &mpsc::Sender, + identity: &Identity, + app_name: &str, +) -> Result<(), RnshError> { + let raw = build_announce_packet(identity, app_name)?; + let dest_hash = Destination::hash_from_name_and_identity(app_name, Some(&identity.hash)); + tx.send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: dest_hash, + })) + .await + .map_err(|_| RnshError::TransportUnavailable) +} + +fn build_announce_packet(identity: &Identity, app_name: &str) -> Result, RnshError> { + let announce = rns_identity::announce::AnnounceData::create(identity, app_name, None, None) + .map_err(|e| RnshError::LinkCrypto(format!("announce: {e}")))?; + let dest_hash = Destination::hash_from_name_and_identity(app_name, Some(&identity.hash)); + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&announce.pack()); + Ok(raw) +} + +fn remaining(deadline: Instant) -> Duration { + deadline.saturating_duration_since(Instant::now()) +} + +fn select_listener_command( + default_command: &[String], + remote_command: Option<&[String]>, + allow_remote_command: bool, + remote_command_as_args: bool, +) -> Result, String> { + let remote_command = remote_command.unwrap_or(&[]); + let has_remote_command = !remote_command.is_empty(); + + if !allow_remote_command && has_remote_command { + return Err("Remote command line not allowed by listener".to_string()); + } + + if default_command.is_empty() && (!has_remote_command || remote_command_as_args) { + return Err("no command configured for listener".to_string()); + } + + if remote_command_as_args && has_remote_command { + let mut command = default_command.to_vec(); + command.extend_from_slice(remote_command); + return Ok(command); + } + + if has_remote_command { + Ok(remote_command.to_vec()) + } else { + Ok(default_command.to_vec()) + } +} + +fn listener_allowed_identities(cfg: &RnshListenerConfig) -> HashSet<[u8; 16]> { + let mut allowed: HashSet<[u8; 16]> = cfg.allowed.iter().copied().collect(); + for path in &cfg.allowed_identity_files { + let Ok(content) = std::fs::read_to_string(path) else { + continue; + }; + for line in content.replace('\r', "").lines() { + if let Some(hash) = parse_identity_hash16(line.trim()) { + allowed.insert(hash); + } + } + } + allowed +} + +fn parse_identity_hash16(input: &str) -> Option<[u8; 16]> { + if input.len() != 32 { + return None; + } + let decoded = hex::decode(input).ok()?; + let mut hash = [0u8; 16]; + hash.copy_from_slice(decoded.get(..16)?); + Some(hash) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + fn spawn_ack_manager( + mut rx: mpsc::Receiver, + messages: Arc>>, + ) { + tokio::spawn(async move { + let mut sequence = 0u16; + while let Some(command) = rx.recv().await { + match command { + LinkManagerCommand::SendChannelMessage { + link_id, + message, + result_tx, + } => { + if let Ok(decoded) = + RnshMessage::decode(message.msg_type(), &message.pack()) + { + messages.lock().unwrap().push(decoded); + } + if let Some(tx) = result_tx { + let _ = tx.send(Ok(crate::link_manager::ChannelSendReceipt { + link_id, + sequence, + packet_hash: [0; 32], + })); + sequence = sequence.wrapping_add(1); + } + } + LinkManagerCommand::Shutdown => break, + _ => {} + } + } + }); + } + + async fn wait_for_stream_text(messages: &Arc>>, needle: &str) { + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + let text = messages + .lock() + .unwrap() + .iter() + .filter_map(|message| match message { + RnshMessage::StreamData(stream) => { + Some(String::from_utf8_lossy(&stream.data).into_owned()) + } + _ => None, + }) + .collect::(); + if text.replace('\r', "").contains(needle) { + return; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + panic!("stream text did not contain {needle:?}"); + } + + async fn wait_for_exit_code(messages: &Arc>>, code: i64) { + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if messages.lock().unwrap().iter().any(|message| { + matches!(message, RnshMessage::CommandExited(exited) if exited.return_code == code) + }) { + return; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + panic!("command exit code {code} was not observed"); + } + + fn process_exists(pid: i32) -> bool { + let rc = unsafe { nix::libc::kill(pid, 0) }; + rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(nix::libc::EPERM) + } + + #[tokio::test] + async fn unix_pty_stdin_stdout_and_ctrl_d() { + let (command_tx, command_rx) = mpsc::channel(64); + let messages = Arc::new(Mutex::new(Vec::new())); + spawn_ack_manager(command_rx, messages.clone()); + let command = vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "if test -t 0 && test -t 1; then cat >/dev/null; printf 'eof-ok\\n'; else printf 'tty-missing\\n'; exit 44; fi".to_string(), + ]; + + let mut process = start_listener_process( + command_tx, + [0x11; 16], + ListenerProcessRequest { + command: &command, + pipe_stdin: false, + pipe_stdout: false, + pipe_stderr: true, + term: Some("xterm"), + rows: Some(24), + cols: Some(80), + hpix: None, + vpix: None, + remote_identity_hash: None, + }, + ) + .await + .expect("start pty process"); + + process.stdin.write_all(&[0x04]).await.expect("send ctrl-d"); + wait_for_stream_text(&messages, "eof-ok\n").await; + wait_for_exit_code(&messages, 0).await; + } + + #[tokio::test] + async fn unix_pty_ctrl_c_reaches_foreground_process_group() { + let (command_tx, command_rx) = mpsc::channel(64); + let messages = Arc::new(Mutex::new(Vec::new())); + spawn_ack_manager(command_rx, messages.clone()); + let command = vec![ + "python3".to_string(), + "-c".to_string(), + "import signal, sys, time; signal.signal(signal.SIGINT, lambda s, f: (print('interrupted', flush=True), sys.exit(23))); print('ready', flush=True); time.sleep(30)".to_string(), + ]; + + let mut process = start_listener_process( + command_tx, + [0x22; 16], + ListenerProcessRequest { + command: &command, + pipe_stdin: false, + pipe_stdout: false, + pipe_stderr: true, + term: Some("xterm"), + rows: Some(24), + cols: Some(80), + hpix: None, + vpix: None, + remote_identity_hash: None, + }, + ) + .await + .expect("start pty process"); + + wait_for_stream_text(&messages, "ready\n").await; + process.stdin.write_all(&[0x03]).await.expect("send ctrl-c"); + wait_for_stream_text(&messages, "interrupted\n").await; + wait_for_exit_code(&messages, 23).await; + } + + #[tokio::test] + async fn unix_pty_process_is_cleaned_up_on_session_drop() { + let (command_tx, command_rx) = mpsc::channel(64); + let messages = Arc::new(Mutex::new(Vec::new())); + spawn_ack_manager(command_rx, messages); + let pid_path = std::env::temp_dir().join(format!( + "rnsh-cleanup-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let command = vec![ + "/bin/sh".to_string(), + "-c".to_string(), + format!( + "echo $$ > '{}'; while :; do sleep 1; done", + pid_path.display() + ), + ]; + + let process = start_listener_process( + command_tx, + [0x33; 16], + ListenerProcessRequest { + command: &command, + pipe_stdin: false, + pipe_stdout: true, + pipe_stderr: true, + term: Some("xterm"), + rows: Some(24), + cols: Some(80), + hpix: None, + vpix: None, + remote_identity_hash: None, + }, + ) + .await + .expect("start pty process"); + + let deadline = Instant::now() + Duration::from_secs(3); + let pid: i32 = loop { + if Instant::now() >= deadline { + panic!("child pid file was not populated at {}", pid_path.display()); + } + match std::fs::read_to_string(&pid_path) { + Ok(contents) => match contents.trim().parse() { + Ok(pid) => break pid, + Err(_) if contents.trim().is_empty() => {} + Err(e) => panic!("parse child pid from {contents:?}: {e}"), + }, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => panic!("read child pid file {}: {e}", pid_path.display()), + } + tokio::time::sleep(Duration::from_millis(25)).await; + }; + assert!(process_exists(pid), "child process should be running"); + + drop(process); + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline && process_exists(pid) { + tokio::time::sleep(Duration::from_millis(25)).await; + } + let _ = std::fs::remove_file(&pid_path); + assert!(!process_exists(pid), "child process survived session drop"); + } +} diff --git a/crates/rns-runtime/src/rpc.rs b/crates/rns-runtime/src/rpc.rs new file mode 100644 index 0000000..f9e4c15 --- /dev/null +++ b/crates/rns-runtime/src/rpc.rs @@ -0,0 +1,1713 @@ +//! Shared-instance control RPC over TCP. +//! +//! Python Reticulum uses `multiprocessing.connection.Listener/Client` for the +//! local control port. Keep the Rust control socket wire-compatible with that: +//! framed auth challenge (`#CHALLENGE#` + `{sha256}` payload), framed pickle +//! request dictionaries, and framed pickle responses. + +use serde::{Deserialize, Serialize}; + +pub(crate) const MP_CHALLENGE: &[u8] = b"#CHALLENGE#"; +pub(crate) const MP_WELCOME: &[u8] = b"#WELCOME#"; +pub(crate) const MP_FAILURE: &[u8] = b"#FAILURE#"; +const MP_DIGEST_PREFIX: &[u8] = b"{sha256}"; +const MP_CHALLENGE_RANDOM_LEN: usize = 40; +const MAX_MP_FRAME_SIZE: usize = 16 * 1024 * 1024; + +#[derive(Debug, Clone, PartialEq)] +enum PyValue { + None, + Bool(bool), + Int(i128), + Float(f64), + Bytes(Vec), + String(String), + List(Vec), + Dict(Vec<(PyDictKey, PyValue)>), +} + +#[derive(Debug, Clone, PartialEq)] +enum PyDictKey { + String(String), + Bytes(Vec), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum RpcRequest { + GetPathTable { + max_hops: Option, + }, + GetInterfaceStats, + GetRateTable, + GetNextHopIfName { + destination_hash: Vec, + }, + GetNextHop { + destination_hash: Vec, + }, + GetFirstHopTimeout { + destination_hash: Vec, + }, + GetLinkCount, + GetPacketRssi { + packet_hash: Vec, + }, + GetPacketSnr { + packet_hash: Vec, + }, + GetPacketQ { + packet_hash: Vec, + }, + GetBlackholedIdentities, + DropPath { + destination_hash: Vec, + }, + DropAllVia { + transport_hash: Vec, + }, + DropAnnounceQueues, + BlackholeIdentity { + identity_hash: Vec, + until: Option, + reason: Option, + }, + UnblackholeIdentity { + identity_hash: Vec, + }, + UseDestination { + destination_hash: Vec, + }, + RetainDestination { + destination_hash: Vec, + }, + UnretainDestination { + destination_hash: Vec, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum RpcResponse { + PathTable(Vec), + InterfaceStats(Vec), + RateTable(Vec), + StringResult(Option), + HashResult(Option>), + FloatResult(Option), + IntResult(i64), + BoolResult(bool), + BlackholeList(Vec), + Ok, + Error(String), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PathTableEntry { + pub hash: Vec, + pub timestamp: f64, + pub via: Option>, + pub hops: u8, + pub expires: f64, + pub interface: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InterfaceStatEntry { + pub id: u64, + pub name: String, + pub rx_bytes: u64, + pub tx_bytes: u64, + pub rx_rate: u64, + pub tx_rate: u64, + pub online: bool, + pub bitrate: u64, + pub mtu: u32, + pub mode: String, + pub role: String, + pub announce_queue: Option, + pub held_announces: u64, + pub incoming_announce_frequency: f64, + pub outgoing_announce_frequency: f64, + pub clients: Option, + pub announce_rate_target: Option, + pub announce_rate_grace: Option, + pub announce_rate_penalty: Option, + pub announce_cap: f64, + pub ifac_size: usize, + pub tx_drops: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RateTableEntry { + pub hash: Vec, + pub rate: f64, + pub last: f64, + pub rate_violations: u32, + pub blocked_until: f64, + pub timestamps: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BlackholeEntry { + pub identity_hash: Vec, + pub source: Option>, + pub until: Option, + pub reason: Option, +} + +pub fn encode_request(req: &RpcRequest) -> Result, RpcError> { + encode_python_pickle(&request_to_py_value(req)) +} + +pub fn decode_request(data: &[u8]) -> Result { + let value = decode_python_pickle(data)?; + py_value_to_request(&value) +} + +pub fn encode_response(resp: &RpcResponse) -> Result, RpcError> { + encode_python_pickle(&response_to_py_value(resp)) +} + +pub fn decode_response(data: &[u8]) -> Result { + let value = decode_python_pickle(data)?; + py_value_to_response(&value) +} + +pub fn decode_response_for_request( + data: &[u8], + request: &RpcRequest, +) -> Result { + let value = decode_python_pickle(data)?; + py_value_to_response_for_request(&value, request) +} + +pub fn compute_auth_hmac(key: &[u8], challenge: &[u8]) -> [u8; 32] { + use hmac::{Hmac, Mac}; + use sha2::Sha256; + + let mut mac = Hmac::::new_from_slice(key).expect("HMAC key can be any length"); + mac.update(challenge); + let result = mac.finalize(); + let mut out = [0u8; 32]; + out.copy_from_slice(&result.into_bytes()); + out +} + +/// Constant-time comparison; handshake MUST NOT leak via timing. +pub fn verify_auth_hmac(key: &[u8], challenge: &[u8], provided: &[u8; 32]) -> bool { + use subtle::ConstantTimeEq; + let expected = compute_auth_hmac(key, challenge); + expected.ct_eq(provided).into() +} + +/// Derived from the transport identity so server + local CLI share a secret +/// without extra on-disk state. +pub fn derive_rpc_key(identity_private_key: &[u8]) -> [u8; 32] { + rns_crypto::sha::sha256(identity_private_key) +} + +fn request_to_py_value(req: &RpcRequest) -> PyValue { + match req { + RpcRequest::GetPathTable { max_hops } => py_dict(vec![ + ("get", PyValue::String("path_table".to_string())), + ( + "max_hops", + max_hops + .map(|v| PyValue::Int(i128::from(v))) + .unwrap_or(PyValue::None), + ), + ]), + RpcRequest::GetInterfaceStats => py_get("interface_stats"), + RpcRequest::GetRateTable => py_get("rate_table"), + RpcRequest::GetNextHopIfName { destination_hash } => py_dict(vec![ + ("get", PyValue::String("next_hop_if_name".to_string())), + ("destination_hash", PyValue::Bytes(destination_hash.clone())), + ]), + RpcRequest::GetNextHop { destination_hash } => py_dict(vec![ + ("get", PyValue::String("next_hop".to_string())), + ("destination_hash", PyValue::Bytes(destination_hash.clone())), + ]), + RpcRequest::GetFirstHopTimeout { destination_hash } => py_dict(vec![ + ("get", PyValue::String("first_hop_timeout".to_string())), + ("destination_hash", PyValue::Bytes(destination_hash.clone())), + ]), + RpcRequest::GetLinkCount => py_get("link_count"), + RpcRequest::GetPacketRssi { packet_hash } => py_dict(vec![ + ("get", PyValue::String("packet_rssi".to_string())), + ("packet_hash", PyValue::Bytes(packet_hash.clone())), + ]), + RpcRequest::GetPacketSnr { packet_hash } => py_dict(vec![ + ("get", PyValue::String("packet_snr".to_string())), + ("packet_hash", PyValue::Bytes(packet_hash.clone())), + ]), + RpcRequest::GetPacketQ { packet_hash } => py_dict(vec![ + ("get", PyValue::String("packet_q".to_string())), + ("packet_hash", PyValue::Bytes(packet_hash.clone())), + ]), + RpcRequest::GetBlackholedIdentities => py_get("blackholed_identities"), + RpcRequest::DropPath { destination_hash } => py_dict(vec![ + ("drop", PyValue::String("path".to_string())), + ("destination_hash", PyValue::Bytes(destination_hash.clone())), + ]), + RpcRequest::DropAllVia { transport_hash } => py_dict(vec![ + ("drop", PyValue::String("all_via".to_string())), + ("destination_hash", PyValue::Bytes(transport_hash.clone())), + ]), + RpcRequest::DropAnnounceQueues => py_dict(vec![( + "drop", + PyValue::String("announce_queues".to_string()), + )]), + RpcRequest::BlackholeIdentity { + identity_hash, + until, + reason, + } => py_dict(vec![ + ("blackhole_identity", PyValue::Bytes(identity_hash.clone())), + ("until", until.map(PyValue::Float).unwrap_or(PyValue::None)), + ( + "reason", + reason.clone().map(PyValue::String).unwrap_or(PyValue::None), + ), + ]), + RpcRequest::UnblackholeIdentity { identity_hash } => py_dict(vec![( + "unblackhole_identity", + PyValue::Bytes(identity_hash.clone()), + )]), + RpcRequest::UseDestination { destination_hash } => py_dict(vec![ + ("destination_data", PyValue::String("used".to_string())), + ("destination_hash", PyValue::Bytes(destination_hash.clone())), + ]), + RpcRequest::RetainDestination { destination_hash } => py_dict(vec![ + ("destination_data", PyValue::String("retain".to_string())), + ("destination_hash", PyValue::Bytes(destination_hash.clone())), + ]), + RpcRequest::UnretainDestination { destination_hash } => py_dict(vec![ + ("destination_data", PyValue::String("unretain".to_string())), + ("destination_hash", PyValue::Bytes(destination_hash.clone())), + ]), + } +} + +fn py_get(path: &str) -> PyValue { + py_dict(vec![("get", PyValue::String(path.to_string()))]) +} + +fn py_dict(entries: Vec<(&str, PyValue)>) -> PyValue { + PyValue::Dict( + entries + .into_iter() + .map(|(k, v)| (PyDictKey::String(k.to_string()), v)) + .collect(), + ) +} + +fn py_value_to_request(value: &PyValue) -> Result { + let entries = as_dict(value)?; + if let Some(PyValue::String(path)) = dict_get(entries, "get") { + return match path.as_str() { + "path_table" => Ok(RpcRequest::GetPathTable { + max_hops: dict_get(entries, "max_hops").and_then(py_u8), + }), + "interface_stats" => Ok(RpcRequest::GetInterfaceStats), + "rate_table" => Ok(RpcRequest::GetRateTable), + "next_hop_if_name" => Ok(RpcRequest::GetNextHopIfName { + destination_hash: dict_bytes(entries, "destination_hash")?, + }), + "next_hop" => Ok(RpcRequest::GetNextHop { + destination_hash: dict_bytes(entries, "destination_hash")?, + }), + "first_hop_timeout" => Ok(RpcRequest::GetFirstHopTimeout { + destination_hash: dict_bytes(entries, "destination_hash")?, + }), + "link_count" => Ok(RpcRequest::GetLinkCount), + "packet_rssi" => Ok(RpcRequest::GetPacketRssi { + packet_hash: dict_bytes(entries, "packet_hash")?, + }), + "packet_snr" => Ok(RpcRequest::GetPacketSnr { + packet_hash: dict_bytes(entries, "packet_hash")?, + }), + "packet_q" => Ok(RpcRequest::GetPacketQ { + packet_hash: dict_bytes(entries, "packet_hash")?, + }), + "blackholed_identities" => Ok(RpcRequest::GetBlackholedIdentities), + other => Err(RpcError::Deserialize(format!( + "unknown Python RPC get path: {other}" + ))), + }; + } + + if let Some(PyValue::String(path)) = dict_get(entries, "drop") { + return match path.as_str() { + "path" => Ok(RpcRequest::DropPath { + destination_hash: dict_bytes(entries, "destination_hash")?, + }), + "all_via" => Ok(RpcRequest::DropAllVia { + transport_hash: dict_bytes(entries, "destination_hash")?, + }), + "announce_queues" => Ok(RpcRequest::DropAnnounceQueues), + other => Err(RpcError::Deserialize(format!( + "unknown Python RPC drop path: {other}" + ))), + }; + } + + if let Some(PyValue::Bytes(identity_hash)) = dict_get(entries, "blackhole_identity") { + return Ok(RpcRequest::BlackholeIdentity { + identity_hash: identity_hash.clone(), + until: dict_get(entries, "until").and_then(py_f64), + reason: dict_get(entries, "reason").and_then(py_string), + }); + } + + if let Some(PyValue::Bytes(identity_hash)) = dict_get(entries, "unblackhole_identity") { + return Ok(RpcRequest::UnblackholeIdentity { + identity_hash: identity_hash.clone(), + }); + } + + if let Some(PyValue::String(operation)) = dict_get(entries, "destination_data") { + let destination_hash = dict_bytes(entries, "destination_hash")?; + return match operation.as_str() { + "used" => Ok(RpcRequest::UseDestination { destination_hash }), + "retain" => Ok(RpcRequest::RetainDestination { destination_hash }), + "unretain" => Ok(RpcRequest::UnretainDestination { destination_hash }), + other => Err(RpcError::Deserialize(format!( + "unknown Python RPC destination_data operation: {other}" + ))), + }; + } + + Err(RpcError::Deserialize( + "Python RPC request dictionary has no known operation".to_string(), + )) +} + +fn response_to_py_value(resp: &RpcResponse) -> PyValue { + match resp { + RpcResponse::PathTable(entries) => PyValue::List( + entries + .iter() + .map(|e| { + py_dict(vec![ + ("hash", PyValue::Bytes(e.hash.clone())), + ("timestamp", PyValue::Float(e.timestamp)), + ( + "via", + e.via.clone().map(PyValue::Bytes).unwrap_or(PyValue::None), + ), + ("hops", PyValue::Int(i128::from(e.hops))), + ("expires", PyValue::Float(e.expires)), + ("interface", PyValue::String(e.interface.clone())), + ]) + }) + .collect(), + ), + RpcResponse::InterfaceStats(entries) => { + let interfaces = entries + .iter() + .map(|e| { + py_dict(vec![ + ("id", PyValue::Int(i128::from(e.id))), + ("name", PyValue::String(e.name.clone())), + ("short_name", PyValue::String(e.name.clone())), + ("type", PyValue::String(e.role.clone())), + ("rxb", PyValue::Int(i128::from(e.rx_bytes))), + ("txb", PyValue::Int(i128::from(e.tx_bytes))), + ("rxs", PyValue::Int(i128::from(e.rx_rate))), + ("txs", PyValue::Int(i128::from(e.tx_rate))), + ("status", PyValue::Bool(e.online)), + ( + "mode", + PyValue::Int(i128::from(mode_to_python_int(&e.mode))), + ), + ("bitrate", PyValue::Int(i128::from(e.bitrate))), + ("mtu", PyValue::Int(i128::from(e.mtu))), + ("ifac_size", PyValue::Int(i128::from(e.ifac_size as u64))), + ( + "announce_queue", + e.announce_queue + .map(|v| PyValue::Int(i128::from(v))) + .unwrap_or(PyValue::None), + ), + ("held_announces", PyValue::Int(i128::from(e.held_announces))), + ( + "incoming_announce_frequency", + PyValue::Float(e.incoming_announce_frequency), + ), + ( + "outgoing_announce_frequency", + PyValue::Float(e.outgoing_announce_frequency), + ), + ( + "clients", + e.clients + .map(|v| PyValue::Int(i128::from(v))) + .unwrap_or(PyValue::None), + ), + ("tx_drops", PyValue::Int(i128::from(e.tx_drops))), + ]) + }) + .collect(); + let rxb = entries.iter().map(|e| e.rx_bytes).sum::(); + let txb = entries.iter().map(|e| e.tx_bytes).sum::(); + let rxs = entries.iter().map(|e| e.rx_rate).sum::(); + let txs = entries.iter().map(|e| e.tx_rate).sum::(); + py_dict(vec![ + ("interfaces", PyValue::List(interfaces)), + ("rxb", PyValue::Int(i128::from(rxb))), + ("txb", PyValue::Int(i128::from(txb))), + ("rxs", PyValue::Int(i128::from(rxs))), + ("txs", PyValue::Int(i128::from(txs))), + ("rss", PyValue::None), + ]) + } + RpcResponse::RateTable(entries) => PyValue::List( + entries + .iter() + .map(|e| { + py_dict(vec![ + ("hash", PyValue::Bytes(e.hash.clone())), + ("rate", PyValue::Float(e.rate)), + ("last", PyValue::Float(e.last)), + ( + "rate_violations", + PyValue::Int(i128::from(e.rate_violations)), + ), + ("blocked_until", PyValue::Float(e.blocked_until)), + ( + "timestamps", + PyValue::List( + e.timestamps.iter().copied().map(PyValue::Float).collect(), + ), + ), + ]) + }) + .collect(), + ), + RpcResponse::StringResult(v) => v.clone().map(PyValue::String).unwrap_or(PyValue::None), + RpcResponse::HashResult(v) => v.clone().map(PyValue::Bytes).unwrap_or(PyValue::None), + RpcResponse::FloatResult(v) => v.map(PyValue::Float).unwrap_or(PyValue::None), + RpcResponse::IntResult(v) => PyValue::Int(i128::from(*v)), + RpcResponse::BoolResult(v) => PyValue::Bool(*v), + RpcResponse::BlackholeList(entries) => PyValue::Dict( + entries + .iter() + .map(|e| { + ( + PyDictKey::Bytes(e.identity_hash.clone()), + py_dict(vec![ + ( + "source", + e.source + .clone() + .map(PyValue::Bytes) + .unwrap_or_else(|| PyValue::Bytes(e.identity_hash.clone())), + ), + ( + "until", + e.until.map(PyValue::Float).unwrap_or(PyValue::None), + ), + ( + "reason", + e.reason + .clone() + .map(PyValue::String) + .unwrap_or(PyValue::None), + ), + ]), + ) + }) + .collect(), + ), + RpcResponse::Ok => PyValue::Bool(true), + RpcResponse::Error(e) => py_dict(vec![("error", PyValue::String(e.clone()))]), + } +} + +fn py_value_to_response(value: &PyValue) -> Result { + match value { + PyValue::Dict(entries) if dict_get(entries, "interfaces").is_some() => { + Ok(RpcResponse::InterfaceStats(parse_interface_stats(value)?)) + } + PyValue::Dict(entries) if dict_get(entries, "error").is_some() => Ok(RpcResponse::Error( + dict_get(entries, "error") + .and_then(py_string) + .unwrap_or_else(|| "RPC error".to_string()), + )), + PyValue::List(values) => infer_list_response(values), + PyValue::String(s) => Ok(RpcResponse::StringResult(Some(s.clone()))), + PyValue::Bytes(b) => Ok(RpcResponse::HashResult(Some(b.clone()))), + PyValue::Float(f) => Ok(RpcResponse::FloatResult(Some(*f))), + PyValue::Int(i) => Ok(RpcResponse::IntResult(i64_from_i128(*i)?)), + PyValue::Bool(b) => Ok(RpcResponse::BoolResult(*b)), + PyValue::None => Ok(RpcResponse::StringResult(None)), + PyValue::Dict(_) => Err(RpcError::Deserialize( + "unrecognised Python RPC response dictionary".to_string(), + )), + } +} + +fn py_value_to_response_for_request( + value: &PyValue, + request: &RpcRequest, +) -> Result { + match request { + RpcRequest::GetPathTable { .. } => Ok(RpcResponse::PathTable(parse_path_table(value)?)), + RpcRequest::GetInterfaceStats => { + Ok(RpcResponse::InterfaceStats(parse_interface_stats(value)?)) + } + RpcRequest::GetRateTable => Ok(RpcResponse::RateTable(parse_rate_table(value)?)), + RpcRequest::GetNextHopIfName { .. } => { + Ok(RpcResponse::StringResult(py_optional_string(value)?)) + } + RpcRequest::GetNextHop { .. } => Ok(RpcResponse::HashResult(py_optional_bytes(value)?)), + RpcRequest::GetFirstHopTimeout { .. } + | RpcRequest::GetPacketRssi { .. } + | RpcRequest::GetPacketSnr { .. } + | RpcRequest::GetPacketQ { .. } => Ok(RpcResponse::FloatResult(py_optional_float(value)?)), + RpcRequest::GetLinkCount | RpcRequest::DropAllVia { .. } => { + Ok(RpcResponse::IntResult(py_required_int(value)?)) + } + RpcRequest::GetBlackholedIdentities => { + Ok(RpcResponse::BlackholeList(parse_blackhole_list(value)?)) + } + RpcRequest::DropPath { .. } + | RpcRequest::DropAnnounceQueues + | RpcRequest::BlackholeIdentity { .. } + | RpcRequest::UnblackholeIdentity { .. } => Ok(RpcResponse::Ok), + RpcRequest::UseDestination { .. } + | RpcRequest::RetainDestination { .. } + | RpcRequest::UnretainDestination { .. } => Ok(RpcResponse::BoolResult(match value { + PyValue::Bool(v) => *v, + PyValue::None => false, + _ => py_required_int(value)? != 0, + })), + } +} + +fn infer_list_response(values: &[PyValue]) -> Result { + let Some(PyValue::Dict(first)) = values.first() else { + return Ok(RpcResponse::PathTable(Vec::new())); + }; + if dict_get(first, "identity_hash").is_some() { + Ok(RpcResponse::BlackholeList(parse_blackhole_list( + &PyValue::List(values.to_vec()), + )?)) + } else if dict_get(first, "rate_violations").is_some() { + Ok(RpcResponse::RateTable(parse_rate_table(&PyValue::List( + values.to_vec(), + ))?)) + } else { + Ok(RpcResponse::PathTable(parse_path_table(&PyValue::List( + values.to_vec(), + ))?)) + } +} + +fn parse_path_table(value: &PyValue) -> Result, RpcError> { + let PyValue::List(entries) = value else { + return Err(RpcError::Deserialize( + "expected path table list".to_string(), + )); + }; + entries + .iter() + .map(|entry| { + let m = as_dict(entry)?; + Ok(PathTableEntry { + hash: dict_bytes(m, "hash")?, + timestamp: dict_get(m, "timestamp").and_then(py_f64).unwrap_or(0.0), + via: match dict_get(m, "via") { + Some(PyValue::Bytes(v)) => Some(v.clone()), + _ => None, + }, + hops: dict_get(m, "hops").and_then(py_u8).unwrap_or(0), + expires: dict_get(m, "expires").and_then(py_f64).unwrap_or(0.0), + interface: dict_get(m, "interface") + .and_then(py_string) + .unwrap_or_default(), + }) + }) + .collect() +} + +fn parse_interface_stats(value: &PyValue) -> Result, RpcError> { + let list = match value { + PyValue::Dict(entries) => match dict_get(entries, "interfaces") { + Some(PyValue::List(v)) => v, + _ => return Ok(Vec::new()), + }, + PyValue::List(v) => v, + _ => { + return Err(RpcError::Deserialize( + "expected interface stats dictionary".to_string(), + )); + } + }; + list.iter() + .enumerate() + .map(|(idx, entry)| { + let m = as_dict(entry)?; + Ok(InterfaceStatEntry { + id: dict_get(m, "id") + .and_then(py_u64) + .unwrap_or((idx as u64) + 1), + name: dict_get(m, "name").and_then(py_string).unwrap_or_default(), + rx_bytes: dict_get(m, "rxb") + .or_else(|| dict_get(m, "rx_bytes")) + .and_then(py_u64) + .unwrap_or(0), + tx_bytes: dict_get(m, "txb") + .or_else(|| dict_get(m, "tx_bytes")) + .and_then(py_u64) + .unwrap_or(0), + rx_rate: dict_get(m, "rxs").and_then(py_u64).unwrap_or(0), + tx_rate: dict_get(m, "txs").and_then(py_u64).unwrap_or(0), + online: dict_get(m, "status") + .or_else(|| dict_get(m, "online")) + .and_then(py_bool) + .unwrap_or(false), + bitrate: dict_get(m, "bitrate").and_then(py_u64).unwrap_or(0), + mtu: dict_get(m, "mtu").and_then(py_u32).unwrap_or(0), + mode: dict_get(m, "mode") + .map(mode_from_py_value) + .unwrap_or_else(|| "Full".to_string()), + role: dict_get(m, "role") + .or_else(|| dict_get(m, "type")) + .and_then(py_string) + .unwrap_or_else(|| "normal".to_string()), + announce_queue: match dict_get(m, "announce_queue") { + Some(PyValue::None) | None => None, + Some(value) => py_u64(value), + }, + held_announces: dict_get(m, "held_announces").and_then(py_u64).unwrap_or(0), + incoming_announce_frequency: dict_get(m, "incoming_announce_frequency") + .and_then(py_f64) + .unwrap_or(0.0), + outgoing_announce_frequency: dict_get(m, "outgoing_announce_frequency") + .and_then(py_f64) + .unwrap_or(0.0), + clients: match dict_get(m, "clients") { + Some(PyValue::None) | None => None, + Some(value) => py_u64(value), + }, + announce_rate_target: dict_get(m, "announce_rate_target").and_then(py_f64), + announce_rate_grace: dict_get(m, "announce_rate_grace").and_then(py_u32), + announce_rate_penalty: dict_get(m, "announce_rate_penalty").and_then(py_f64), + announce_cap: dict_get(m, "announce_cap").and_then(py_f64).unwrap_or(0.0), + ifac_size: dict_get(m, "ifac_size") + .and_then(py_u64) + .map(|v| v as usize) + .unwrap_or(0), + tx_drops: dict_get(m, "tx_drops").and_then(py_u64).unwrap_or(0), + }) + }) + .collect() +} + +fn parse_rate_table(value: &PyValue) -> Result, RpcError> { + let PyValue::List(entries) = value else { + return Err(RpcError::Deserialize( + "expected rate table list".to_string(), + )); + }; + entries + .iter() + .map(|entry| { + let m = as_dict(entry)?; + let timestamps = match dict_get(m, "timestamps") { + Some(PyValue::List(v)) => v.iter().filter_map(py_f64).collect(), + _ => Vec::new(), + }; + Ok(RateTableEntry { + hash: dict_bytes(m, "hash")?, + rate: dict_get(m, "rate").and_then(py_f64).unwrap_or(0.0), + last: dict_get(m, "last").and_then(py_f64).unwrap_or(0.0), + rate_violations: dict_get(m, "rate_violations").and_then(py_u32).unwrap_or(0), + blocked_until: dict_get(m, "blocked_until").and_then(py_f64).unwrap_or(0.0), + timestamps, + }) + }) + .collect() +} + +fn parse_blackhole_list(value: &PyValue) -> Result, RpcError> { + match value { + PyValue::List(entries) => entries + .iter() + .map(|entry| { + let m = as_dict(entry)?; + Ok(BlackholeEntry { + identity_hash: dict_bytes(m, "identity_hash")?, + source: match dict_get(m, "source") { + Some(PyValue::Bytes(v)) => Some(v.clone()), + _ => None, + }, + until: dict_get(m, "until").and_then(py_f64), + reason: dict_get(m, "reason").and_then(py_string), + }) + }) + .collect(), + PyValue::Dict(entries) => entries + .iter() + .map(|(key, entry)| { + let identity_hash = match key { + PyDictKey::Bytes(bytes) => bytes.clone(), + PyDictKey::String(hex) => hex::decode(hex).map_err(|e| { + RpcError::Deserialize(format!("invalid blackhole identity hash key: {e}")) + })?, + }; + let m = as_dict(entry)?; + Ok(BlackholeEntry { + identity_hash, + source: match dict_get(m, "source") { + Some(PyValue::Bytes(v)) => Some(v.clone()), + _ => None, + }, + until: dict_get(m, "until").and_then(py_f64), + reason: dict_get(m, "reason").and_then(py_string), + }) + }) + .collect(), + _ => Err(RpcError::Deserialize( + "expected blackhole list or dictionary".to_string(), + )), + } +} + +fn as_dict(value: &PyValue) -> Result<&[(PyDictKey, PyValue)], RpcError> { + match value { + PyValue::Dict(entries) => Ok(entries), + _ => Err(RpcError::Deserialize("expected dictionary".to_string())), + } +} + +fn dict_get<'a>(entries: &'a [(PyDictKey, PyValue)], key: &str) -> Option<&'a PyValue> { + entries + .iter() + .find(|(k, _)| matches!(k, PyDictKey::String(s) if s == key)) + .map(|(_, v)| v) +} + +fn dict_bytes(entries: &[(PyDictKey, PyValue)], key: &str) -> Result, RpcError> { + match dict_get(entries, key) { + Some(PyValue::Bytes(v)) => Ok(v.clone()), + Some(_) => Err(RpcError::Deserialize(format!("{key} is not bytes"))), + None => Err(RpcError::Deserialize(format!("missing {key}"))), + } +} + +fn py_string(value: &PyValue) -> Option { + match value { + PyValue::String(v) => Some(v.clone()), + _ => None, + } +} + +fn py_bool(value: &PyValue) -> Option { + match value { + PyValue::Bool(v) => Some(*v), + _ => None, + } +} + +fn py_f64(value: &PyValue) -> Option { + match value { + PyValue::Float(v) => Some(*v), + PyValue::Int(v) => Some(*v as f64), + _ => None, + } +} + +fn py_u8(value: &PyValue) -> Option { + py_u64(value).and_then(|v| u8::try_from(v).ok()) +} + +fn py_u32(value: &PyValue) -> Option { + py_u64(value).and_then(|v| u32::try_from(v).ok()) +} + +fn py_u64(value: &PyValue) -> Option { + match value { + PyValue::Int(v) => u64::try_from(*v).ok(), + _ => None, + } +} + +fn py_optional_string(value: &PyValue) -> Result, RpcError> { + match value { + PyValue::None => Ok(None), + PyValue::String(v) => Ok(Some(v.clone())), + _ => Err(RpcError::Deserialize( + "expected optional string".to_string(), + )), + } +} + +fn py_optional_bytes(value: &PyValue) -> Result>, RpcError> { + match value { + PyValue::None => Ok(None), + PyValue::Bytes(v) => Ok(Some(v.clone())), + _ => Err(RpcError::Deserialize("expected optional bytes".to_string())), + } +} + +fn py_optional_float(value: &PyValue) -> Result, RpcError> { + match value { + PyValue::None => Ok(None), + PyValue::Float(v) => Ok(Some(*v)), + PyValue::Int(v) => Ok(Some(*v as f64)), + _ => Err(RpcError::Deserialize("expected optional float".to_string())), + } +} + +fn py_required_int(value: &PyValue) -> Result { + match value { + PyValue::Int(v) => i64_from_i128(*v), + PyValue::Bool(v) => Ok(i64::from(*v)), + _ => Err(RpcError::Deserialize("expected integer".to_string())), + } +} + +fn i64_from_i128(v: i128) -> Result { + i64::try_from(v).map_err(|_| RpcError::Deserialize(format!("integer out of range: {v}"))) +} + +fn mode_to_python_int(mode: &str) -> u8 { + match mode { + "Full" => 0x01, + "PointToPoint" => 0x02, + "Access" | "AccessPoint" => 0x03, + "Roaming" => 0x04, + "Boundary" => 0x05, + "Gateway" => 0x06, + _ => 0x01, + } +} + +fn mode_from_py_value(value: &PyValue) -> String { + match value { + PyValue::Int(1) => "Full", + PyValue::Int(2) => "PointToPoint", + PyValue::Int(3) => "AccessPoint", + PyValue::Int(4) => "Roaming", + PyValue::Int(5) => "Boundary", + PyValue::Int(6) => "Gateway", + PyValue::String(s) => s.as_str(), + _ => "Full", + } + .to_string() +} + +fn encode_python_pickle(value: &PyValue) -> Result, RpcError> { + let mut out = vec![0x80, 0x04]; // PROTO 4, no FRAME needed for small control messages. + encode_pickle_value(value, &mut out)?; + out.push(b'.'); // STOP + Ok(out) +} + +fn encode_pickle_value(value: &PyValue, out: &mut Vec) -> Result<(), RpcError> { + match value { + PyValue::None => out.push(b'N'), + PyValue::Bool(true) => out.push(0x88), + PyValue::Bool(false) => out.push(0x89), + PyValue::Int(v) => encode_pickle_int(*v, out)?, + PyValue::Float(v) => { + out.push(b'G'); + out.extend_from_slice(&v.to_be_bytes()); + } + PyValue::Bytes(bytes) => encode_pickle_bytes(bytes, out)?, + PyValue::String(s) => encode_pickle_string(s, out)?, + PyValue::List(values) => { + out.push(b']'); + if !values.is_empty() { + out.push(b'('); + for value in values { + encode_pickle_value(value, out)?; + } + out.push(b'e'); // APPENDS + } + } + PyValue::Dict(entries) => { + out.push(b'}'); + if !entries.is_empty() { + out.push(b'('); + for (key, value) in entries { + encode_pickle_key(key, out)?; + encode_pickle_value(value, out)?; + } + out.push(b'u'); // SETITEMS + } + } + } + Ok(()) +} + +fn encode_pickle_key(key: &PyDictKey, out: &mut Vec) -> Result<(), RpcError> { + match key { + PyDictKey::String(s) => encode_pickle_string(s, out), + PyDictKey::Bytes(bytes) => encode_pickle_bytes(bytes, out), + } +} + +fn encode_pickle_string(s: &str, out: &mut Vec) -> Result<(), RpcError> { + let bytes = s.as_bytes(); + if let Ok(len) = u8::try_from(bytes.len()) { + out.push(0x8c); // SHORT_BINUNICODE + out.push(len); + } else { + let len = u32::try_from(bytes.len()) + .map_err(|_| RpcError::Serialize("string too large for pickle".to_string()))?; + out.push(b'X'); // BINUNICODE + out.extend_from_slice(&len.to_le_bytes()); + } + out.extend_from_slice(bytes); + Ok(()) +} + +fn encode_pickle_bytes(bytes: &[u8], out: &mut Vec) -> Result<(), RpcError> { + if let Ok(len) = u8::try_from(bytes.len()) { + out.push(b'C'); // SHORT_BINBYTES + out.push(len); + } else { + let len = u32::try_from(bytes.len()) + .map_err(|_| RpcError::Serialize("bytes too large for pickle".to_string()))?; + out.push(b'B'); // BINBYTES + out.extend_from_slice(&len.to_le_bytes()); + } + out.extend_from_slice(bytes); + Ok(()) +} + +fn encode_pickle_int(value: i128, out: &mut Vec) -> Result<(), RpcError> { + if let Ok(v) = u8::try_from(value) { + out.push(b'K'); // BININT1 + out.push(v); + } else if let Ok(v) = u16::try_from(value) { + out.push(b'M'); // BININT2 + out.extend_from_slice(&v.to_le_bytes()); + } else if let Ok(v) = i32::try_from(value) { + out.push(b'J'); // BININT + out.extend_from_slice(&v.to_le_bytes()); + } else if value >= 0 { + let mut n = u128::try_from(value) + .map_err(|_| RpcError::Serialize("negative big integers unsupported".to_string()))?; + let mut bytes = Vec::new(); + while n > 0 { + bytes.push((n & 0xff) as u8); + n >>= 8; + } + if bytes.last().is_some_and(|b| b & 0x80 != 0) { + bytes.push(0); + } + let len = u8::try_from(bytes.len()) + .map_err(|_| RpcError::Serialize("integer too large for pickle".to_string()))?; + out.push(0x8a); // LONG1 + out.push(len); + out.extend_from_slice(&bytes); + } else { + return Err(RpcError::Serialize( + "negative big integers unsupported".to_string(), + )); + } + Ok(()) +} + +#[derive(Debug, Clone)] +enum StackItem { + Mark, + Value(PyValue), +} + +fn decode_python_pickle(data: &[u8]) -> Result { + let mut i = 0usize; + let mut stack: Vec = Vec::new(); + let mut memo: Vec = Vec::new(); + + while i < data.len() { + let op = data[i]; + i += 1; + match op { + 0x80 => { + read_exact(data, &mut i, 1)?; + } + 0x95 => { + read_exact(data, &mut i, 8)?; + } + 0x94 => { + let value = stack_value(stack.last())?.clone(); + memo.push(value); + } + b'h' => { + let idx = read_u8(data, &mut i)? as usize; + let value = memo.get(idx).cloned().ok_or_else(|| { + RpcError::Deserialize(format!("pickle memo index out of range: {idx}")) + })?; + stack.push(StackItem::Value(value)); + } + b'j' => { + let idx = read_u32_le(data, &mut i)? as usize; + let value = memo.get(idx).cloned().ok_or_else(|| { + RpcError::Deserialize(format!("pickle memo index out of range: {idx}")) + })?; + stack.push(StackItem::Value(value)); + } + b'}' => stack.push(StackItem::Value(PyValue::Dict(Vec::new()))), + b']' => stack.push(StackItem::Value(PyValue::List(Vec::new()))), + b'(' => stack.push(StackItem::Mark), + 0x8c => { + let len = read_u8(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?; + let s = std::str::from_utf8(bytes) + .map_err(|e| RpcError::Deserialize(e.to_string()))? + .to_string(); + stack.push(StackItem::Value(PyValue::String(s))); + } + b'X' => { + let len = read_u32_le(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?; + let s = std::str::from_utf8(bytes) + .map_err(|e| RpcError::Deserialize(e.to_string()))? + .to_string(); + stack.push(StackItem::Value(PyValue::String(s))); + } + 0x8d => { + let len = read_u64_le(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?; + let s = std::str::from_utf8(bytes) + .map_err(|e| RpcError::Deserialize(e.to_string()))? + .to_string(); + stack.push(StackItem::Value(PyValue::String(s))); + } + b'C' => { + let len = read_u8(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?.to_vec(); + stack.push(StackItem::Value(PyValue::Bytes(bytes))); + } + b'B' => { + let len = read_u32_le(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?.to_vec(); + stack.push(StackItem::Value(PyValue::Bytes(bytes))); + } + 0x8e => { + let len = read_u64_le(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?.to_vec(); + stack.push(StackItem::Value(PyValue::Bytes(bytes))); + } + b'N' => stack.push(StackItem::Value(PyValue::None)), + 0x88 => stack.push(StackItem::Value(PyValue::Bool(true))), + 0x89 => stack.push(StackItem::Value(PyValue::Bool(false))), + b'K' => { + let v = read_u8(data, &mut i)?; + stack.push(StackItem::Value(PyValue::Int(i128::from(v)))); + } + b'M' => { + let v = read_u16_le(data, &mut i)?; + stack.push(StackItem::Value(PyValue::Int(i128::from(v)))); + } + b'J' => { + let bytes = read_exact(data, &mut i, 4)?; + let v = i32::from_le_bytes(bytes.try_into().unwrap()); + stack.push(StackItem::Value(PyValue::Int(i128::from(v)))); + } + 0x8a => { + let len = read_u8(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?; + stack.push(StackItem::Value(PyValue::Int(decode_pickle_long(bytes)?))); + } + 0x8b => { + let len = read_u32_le(data, &mut i)? as usize; + let bytes = read_exact(data, &mut i, len)?; + stack.push(StackItem::Value(PyValue::Int(decode_pickle_long(bytes)?))); + } + b'G' => { + let bytes = read_exact(data, &mut i, 8)?; + let v = f64::from_be_bytes(bytes.try_into().unwrap()); + stack.push(StackItem::Value(PyValue::Float(v))); + } + b's' => apply_setitem(&mut stack)?, + b'u' => apply_setitems(&mut stack)?, + b'a' => apply_append(&mut stack)?, + b'e' => apply_appends(&mut stack)?, + b'.' => { + return match stack.pop() { + Some(StackItem::Value(value)) => Ok(value), + _ => Err(RpcError::Deserialize( + "pickle ended without value".to_string(), + )), + }; + } + other => { + return Err(RpcError::Deserialize(format!( + "unsupported pickle opcode 0x{other:02x}" + ))); + } + } + } + + Err(RpcError::Deserialize("pickle missing STOP".to_string())) +} + +fn stack_value(item: Option<&StackItem>) -> Result<&PyValue, RpcError> { + match item { + Some(StackItem::Value(value)) => Ok(value), + _ => Err(RpcError::Deserialize("expected pickle value".to_string())), + } +} + +fn pop_value(stack: &mut Vec) -> Result { + match stack.pop() { + Some(StackItem::Value(value)) => Ok(value), + _ => Err(RpcError::Deserialize("expected pickle value".to_string())), + } +} + +fn apply_setitem(stack: &mut Vec) -> Result<(), RpcError> { + let value = pop_value(stack)?; + let key = pop_value(stack)?; + let Some(StackItem::Value(PyValue::Dict(entries))) = stack.last_mut() else { + return Err(RpcError::Deserialize( + "SETITEM target is not a dictionary".to_string(), + )); + }; + entries.push((py_key(key)?, value)); + Ok(()) +} + +fn apply_setitems(stack: &mut Vec) -> Result<(), RpcError> { + let mark = find_mark(stack)?; + let items = stack.split_off(mark + 1); + stack.pop(); + let Some(StackItem::Value(PyValue::Dict(entries))) = stack.last_mut() else { + return Err(RpcError::Deserialize( + "SETITEMS target is not a dictionary".to_string(), + )); + }; + let mut values = items.into_iter().map(|item| match item { + StackItem::Value(value) => Ok(value), + StackItem::Mark => Err(RpcError::Deserialize("nested mark in SETITEMS".to_string())), + }); + while let Some(key) = values.next() { + let key = key?; + let value = values + .next() + .ok_or_else(|| RpcError::Deserialize("odd SETITEMS count".to_string()))??; + entries.push((py_key(key)?, value)); + } + Ok(()) +} + +fn apply_append(stack: &mut Vec) -> Result<(), RpcError> { + let value = pop_value(stack)?; + let Some(StackItem::Value(PyValue::List(values))) = stack.last_mut() else { + return Err(RpcError::Deserialize( + "APPEND target is not a list".to_string(), + )); + }; + values.push(value); + Ok(()) +} + +fn apply_appends(stack: &mut Vec) -> Result<(), RpcError> { + let mark = find_mark(stack)?; + let items = stack.split_off(mark + 1); + stack.pop(); + let Some(StackItem::Value(PyValue::List(values))) = stack.last_mut() else { + return Err(RpcError::Deserialize( + "APPENDS target is not a list".to_string(), + )); + }; + for item in items { + match item { + StackItem::Value(value) => values.push(value), + StackItem::Mark => { + return Err(RpcError::Deserialize("nested mark in APPENDS".to_string())); + } + } + } + Ok(()) +} + +fn find_mark(stack: &[StackItem]) -> Result { + stack + .iter() + .rposition(|item| matches!(item, StackItem::Mark)) + .ok_or_else(|| RpcError::Deserialize("pickle mark not found".to_string())) +} + +fn py_key(value: PyValue) -> Result { + match value { + PyValue::String(s) => Ok(PyDictKey::String(s)), + PyValue::Bytes(bytes) => Ok(PyDictKey::Bytes(bytes)), + _ => Err(RpcError::Deserialize( + "dictionary key is not a string or bytes".to_string(), + )), + } +} + +fn decode_pickle_long(bytes: &[u8]) -> Result { + if bytes.is_empty() { + return Ok(0); + } + if bytes.len() > 16 { + return Err(RpcError::Deserialize( + "pickle LONG exceeds i128 range".to_string(), + )); + } + let mut value = 0i128; + for (shift, byte) in bytes.iter().enumerate() { + value |= i128::from(*byte) << (shift * 8); + } + if bytes.last().is_some_and(|b| b & 0x80 != 0) { + value -= 1i128 << (bytes.len() * 8); + } + Ok(value) +} + +fn read_exact<'a>(data: &'a [u8], index: &mut usize, len: usize) -> Result<&'a [u8], RpcError> { + let end = index + .checked_add(len) + .ok_or_else(|| RpcError::Deserialize("pickle length overflow".to_string()))?; + if end > data.len() { + return Err(RpcError::Deserialize("truncated pickle".to_string())); + } + let out = &data[*index..end]; + *index = end; + Ok(out) +} + +fn read_u8(data: &[u8], index: &mut usize) -> Result { + Ok(read_exact(data, index, 1)?[0]) +} + +fn read_u16_le(data: &[u8], index: &mut usize) -> Result { + let bytes = read_exact(data, index, 2)?; + Ok(u16::from_le_bytes(bytes.try_into().unwrap())) +} + +fn read_u32_le(data: &[u8], index: &mut usize) -> Result { + let bytes = read_exact(data, index, 4)?; + Ok(u32::from_le_bytes(bytes.try_into().unwrap())) +} + +fn read_u64_le(data: &[u8], index: &mut usize) -> Result { + let bytes = read_exact(data, index, 8)?; + Ok(u64::from_le_bytes(bytes.try_into().unwrap())) +} + +pub fn compute_python_auth_response(key: &[u8], message: &[u8]) -> Vec { + let mut response = Vec::with_capacity(MP_DIGEST_PREFIX.len() + 32); + response.extend_from_slice(MP_DIGEST_PREFIX); + response.extend_from_slice(&compute_auth_hmac(key, message)); + response +} + +pub fn verify_python_auth_response(key: &[u8], message: &[u8], response: &[u8]) -> bool { + use subtle::ConstantTimeEq; + if !response.starts_with(MP_DIGEST_PREFIX) { + return false; + } + let mac = &response[MP_DIGEST_PREFIX.len()..]; + let expected = compute_auth_hmac(key, message); + expected.as_slice().ct_eq(mac).into() +} + +pub fn new_python_challenge() -> Vec { + let mut message = Vec::with_capacity(MP_DIGEST_PREFIX.len() + MP_CHALLENGE_RANDOM_LEN); + message.extend_from_slice(MP_DIGEST_PREFIX); + message.extend_from_slice(&rns_crypto::random::random_bytes(MP_CHALLENGE_RANDOM_LEN)); + message +} + +pub async fn write_mp_frame(stream: &mut S, data: &[u8]) -> Result<(), RpcError> +where + S: tokio::io::AsyncWrite + Unpin, +{ + use tokio::io::AsyncWriteExt; + let len = i32::try_from(data.len()) + .map_err(|_| RpcError::Serialize("frame too large".to_string()))?; + stream + .write_all(&len.to_be_bytes()) + .await + .map_err(RpcError::Io)?; + stream.write_all(data).await.map_err(RpcError::Io) +} + +pub async fn read_mp_frame(stream: &mut S, max_size: usize) -> Result, RpcError> +where + S: tokio::io::AsyncRead + Unpin, +{ + use tokio::io::AsyncReadExt; + let mut len_buf = [0u8; 4]; + stream + .read_exact(&mut len_buf) + .await + .map_err(RpcError::Io)?; + let len = i32::from_be_bytes(len_buf); + let len = if len == -1 { + let mut long_buf = [0u8; 8]; + stream + .read_exact(&mut long_buf) + .await + .map_err(RpcError::Io)?; + usize::try_from(u64::from_be_bytes(long_buf)) + .map_err(|_| RpcError::Deserialize("frame length out of range".to_string()))? + } else if len >= 0 { + len as usize + } else { + return Err(RpcError::Deserialize(format!( + "invalid multiprocessing frame length: {len}" + ))); + }; + if len > max_size { + return Err(RpcError::Deserialize(format!( + "frame too large: {len} > {max_size}" + ))); + } + let mut data = vec![0u8; len]; + stream.read_exact(&mut data).await.map_err(RpcError::Io)?; + Ok(data) +} + +/// Every I/O step is bounded by `timeout` so a stuck daemon never hangs the CLI. +pub async fn connect_and_request( + port: u16, + rpc_key: &[u8], + request: &RpcRequest, + timeout: std::time::Duration, +) -> Result { + let addr = format!("127.0.0.1:{port}"); + + let mut stream = tokio::time::timeout(timeout, tokio::net::TcpStream::connect(&addr)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "connect timeout", + )) + })? + .map_err(RpcError::Io)?; + + request_over_stream(&mut stream, rpc_key, request, timeout).await +} + +#[cfg(unix)] +pub async fn connect_unix_and_request( + socket_path: &str, + rpc_key: &[u8], + request: &RpcRequest, + timeout: std::time::Duration, +) -> Result { + let mut stream = tokio::time::timeout(timeout, connect_unix_stream(socket_path)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "connect timeout", + )) + })? + .map_err(RpcError::Io)?; + + request_over_stream(&mut stream, rpc_key, request, timeout).await +} + +#[cfg(unix)] +async fn connect_unix_stream(socket_path: &str) -> std::io::Result { + if let Some(abstract_name) = socket_path.strip_prefix('\0') { + return connect_abstract_unix_stream(abstract_name); + } + + tokio::net::UnixStream::connect(socket_path).await +} + +#[cfg(all(unix, any(target_os = "linux", target_os = "android")))] +fn connect_abstract_unix_stream(name: &str) -> std::io::Result { + use std::os::unix::net::{SocketAddr, UnixStream}; + + #[cfg(target_os = "android")] + use std::os::android::net::SocketAddrExt as _; + #[cfg(target_os = "linux")] + use std::os::linux::net::SocketAddrExt as _; + + let addr = SocketAddr::from_abstract_name(name.as_bytes())?; + let stream = UnixStream::connect_addr(&addr)?; + stream.set_nonblocking(true)?; + tokio::net::UnixStream::from_std(stream) +} + +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))] +fn connect_abstract_unix_stream(_name: &str) -> std::io::Result { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "abstract Unix sockets are only available on Linux/Android", + )) +} + +#[cfg(not(unix))] +pub async fn connect_unix_and_request( + _socket_path: &str, + _rpc_key: &[u8], + _request: &RpcRequest, + _timeout: std::time::Duration, +) -> Result { + Err(RpcError::Io(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "Unix shared-instance RPC is not supported on this platform", + ))) +} + +async fn request_over_stream( + mut stream: &mut S, + rpc_key: &[u8], + request: &RpcRequest, + timeout: std::time::Duration, +) -> Result +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + let challenge_frame = tokio::time::timeout(timeout, read_mp_frame(&mut stream, 256)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "challenge read timeout", + )) + })??; + if !challenge_frame.starts_with(MP_CHALLENGE) { + return Err(RpcError::AuthFailed); + } + let challenge = &challenge_frame[MP_CHALLENGE.len()..]; + + let response = compute_python_auth_response(rpc_key, challenge); + tokio::time::timeout(timeout, write_mp_frame(&mut stream, &response)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "hmac write timeout", + )) + })??; + + let welcome = tokio::time::timeout(timeout, read_mp_frame(&mut stream, 256)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "welcome read timeout", + )) + })??; + if welcome != MP_WELCOME { + return Err(RpcError::AuthFailed); + } + + let client_challenge = new_python_challenge(); + let mut client_challenge_frame = + Vec::with_capacity(MP_CHALLENGE.len() + client_challenge.len()); + client_challenge_frame.extend_from_slice(MP_CHALLENGE); + client_challenge_frame.extend_from_slice(&client_challenge); + tokio::time::timeout( + timeout, + write_mp_frame(&mut stream, &client_challenge_frame), + ) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "client challenge write timeout", + )) + })??; + + let server_response = tokio::time::timeout(timeout, read_mp_frame(&mut stream, 256)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "server auth response read timeout", + )) + })??; + if verify_python_auth_response(rpc_key, &client_challenge, &server_response) { + tokio::time::timeout(timeout, write_mp_frame(&mut stream, MP_WELCOME)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "client welcome write timeout", + )) + })??; + } else { + let _ = write_mp_frame(&mut stream, MP_FAILURE).await; + return Err(RpcError::AuthFailed); + } + + let req_bytes = encode_request(request)?; + tokio::time::timeout(timeout, write_mp_frame(&mut stream, &req_bytes)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "request write timeout", + )) + })??; + + let resp_buf = tokio::time::timeout(timeout, read_mp_frame(&mut stream, MAX_MP_FRAME_SIZE)) + .await + .map_err(|_| { + RpcError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "response read timeout", + )) + })??; + + decode_response_for_request(&resp_buf, request) +} + +#[derive(Debug, thiserror::Error)] +pub enum RpcError { + #[error("serialization error: {0}")] + Serialize(String), + #[error("deserialization error: {0}")] + Deserialize(String), + #[error("authentication failed")] + AuthFailed, + #[error("connection error: {0}")] + Connection(String), + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_request_roundtrip() { + let req = RpcRequest::GetPathTable { max_hops: Some(8) }; + let encoded = encode_request(&req).unwrap(); + let decoded = decode_request(&encoded).unwrap(); + match decoded { + RpcRequest::GetPathTable { max_hops } => assert_eq!(max_hops, Some(8)), + _ => panic!("wrong variant"), + } + } + + #[test] + fn test_response_roundtrip() { + let resp = RpcResponse::IntResult(42); + let encoded = encode_response(&resp).unwrap(); + let decoded = decode_response(&encoded).unwrap(); + match decoded { + RpcResponse::IntResult(n) => assert_eq!(n, 42), + _ => panic!("wrong variant"), + } + } + + #[test] + fn test_path_table_response() { + let entry = PathTableEntry { + hash: vec![0xAA; 16], + timestamp: 1234567890.0, + via: Some(vec![0xBB; 16]), + hops: 3, + expires: 1234567890.0 + 604800.0, + interface: "TCPInterface[test]".to_string(), + }; + let resp = RpcResponse::PathTable(vec![entry]); + let encoded = encode_response(&resp).unwrap(); + let decoded = decode_response(&encoded).unwrap(); + match decoded { + RpcResponse::PathTable(entries) => { + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].hops, 3); + } + _ => panic!("wrong variant"), + } + } + + #[test] + fn test_python_blackhole_dict_response_shape() { + let identity_hash = vec![0x42; 16]; + let value = PyValue::Dict(vec![( + PyDictKey::Bytes(identity_hash.clone()), + py_dict(vec![ + ("until", PyValue::Float(1234.0)), + ("reason", PyValue::String("parity".to_string())), + ("source", PyValue::Bytes(vec![0xAA; 16])), + ]), + )]); + let encoded = encode_python_pickle(&value).unwrap(); + match decode_response_for_request(&encoded, &RpcRequest::GetBlackholedIdentities).unwrap() { + RpcResponse::BlackholeList(entries) => { + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].identity_hash, identity_hash); + assert_eq!(entries[0].source.as_deref(), Some(&[0xAA; 16][..])); + assert_eq!(entries[0].until, Some(1234.0)); + assert_eq!(entries[0].reason.as_deref(), Some("parity")); + } + other => panic!("wrong blackhole response variant: {other:?}"), + } + } + + #[test] + fn test_auth_hmac() { + let key = b"test_rpc_key"; + let challenge = b"random_challenge_bytes_32_bytes!"; + let hmac = compute_auth_hmac(key, challenge); + assert!(verify_auth_hmac(key, challenge, &hmac)); + } + + #[test] + fn test_auth_hmac_wrong_key() { + let key = b"correct_key"; + let wrong_key = b"wrong_key_!"; + let challenge = b"random_challenge_bytes_32_bytes!"; + let hmac = compute_auth_hmac(key, challenge); + assert!(!verify_auth_hmac(wrong_key, challenge, &hmac)); + } + + #[test] + fn test_derive_rpc_key() { + let private_key = [0x42u8; 64]; + let key1 = derive_rpc_key(&private_key); + let key2 = derive_rpc_key(&private_key); + assert_eq!(key1, key2); + assert_ne!(key1, [0u8; 32]); + } + + #[test] + fn test_all_request_variants() { + let requests = vec![ + RpcRequest::GetPathTable { max_hops: None }, + RpcRequest::GetInterfaceStats, + RpcRequest::GetRateTable, + RpcRequest::GetNextHopIfName { + destination_hash: vec![0; 16], + }, + RpcRequest::GetLinkCount, + RpcRequest::DropPath { + destination_hash: vec![0; 16], + }, + RpcRequest::DropAnnounceQueues, + RpcRequest::BlackholeIdentity { + identity_hash: vec![0; 16], + until: Some(99999.0), + reason: Some("test".to_string()), + }, + RpcRequest::UnblackholeIdentity { + identity_hash: vec![0; 16], + }, + RpcRequest::UseDestination { + destination_hash: vec![0; 16], + }, + RpcRequest::RetainDestination { + destination_hash: vec![0; 16], + }, + RpcRequest::UnretainDestination { + destination_hash: vec![0; 16], + }, + ]; + + for req in &requests { + let encoded = encode_request(req).unwrap(); + let _ = decode_request(&encoded).unwrap(); + } + } +} diff --git a/crates/rns-runtime/src/rpc_server.rs b/crates/rns-runtime/src/rpc_server.rs new file mode 100644 index 0000000..78c96cd --- /dev/null +++ b/crates/rns-runtime/src/rpc_server.rs @@ -0,0 +1,917 @@ +//! Local control port for CLI tools (rnstatus, rnpath). Default 37429. +//! Wire-compatible with Python `multiprocessing.connection`. + +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; + +use rns_transport::messages::TransportMessage; + +use crate::lifecycle::ShutdownSignal; +use crate::rpc::{self, RpcError, RpcRequest, RpcResponse}; + +const MAX_REQUEST_SIZE: usize = 1_048_576; + +pub async fn run_rpc_server( + port: u16, + rpc_key: Vec, + _transport_tx: mpsc::Sender, + shutdown: ShutdownSignal, +) -> Result<(), RpcError> { + let listener = TcpListener::bind(format!("127.0.0.1:{}", port)) + .await + .map_err(RpcError::Io)?; + run_rpc_server_with_listener(listener, rpc_key, _transport_tx, shutdown).await +} + +#[cfg(unix)] +pub async fn run_unix_rpc_server( + socket_path: &str, + rpc_key: Vec, + transport_tx: mpsc::Sender, + shutdown: ShutdownSignal, +) -> Result<(), RpcError> { + let listener = bind_unix_rpc_listener(socket_path).map_err(RpcError::Io)?; + run_unix_rpc_server_with_listener( + listener, + display_socket_path(socket_path), + rpc_key, + transport_tx, + shutdown, + ) + .await +} + +#[cfg(not(unix))] +pub async fn run_unix_rpc_server( + _socket_path: &str, + _rpc_key: Vec, + _transport_tx: mpsc::Sender, + _shutdown: ShutdownSignal, +) -> Result<(), RpcError> { + Err(RpcError::Io(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "Unix shared-instance RPC is not supported on this platform", + ))) +} + +async fn run_rpc_server_with_listener( + listener: TcpListener, + rpc_key: Vec, + _transport_tx: mpsc::Sender, + shutdown: ShutdownSignal, +) -> Result<(), RpcError> { + let port = listener.local_addr().map_err(RpcError::Io)?.port(); + tracing::info!("RPC server listening on 127.0.0.1:{}", port); + + loop { + tokio::select! { + accept_result = listener.accept() => { + match accept_result { + Ok((stream, addr)) => { + tracing::debug!("RPC connection from {}", addr); + let key = rpc_key.clone(); + let tx = _transport_tx.clone(); + tokio::spawn(async move { + if let Err(e) = handle_rpc_client(stream, &key, tx).await { + tracing::debug!("RPC client error: {}", e); + } + }); + } + Err(e) => { + tracing::warn!("RPC accept error: {}", e); + } + } + } + _ = shutdown.wait() => { + tracing::info!("RPC server shutting down"); + break; + } + } + } + + Ok(()) +} + +#[cfg(unix)] +async fn run_unix_rpc_server_with_listener( + listener: tokio::net::UnixListener, + display_path: String, + rpc_key: Vec, + transport_tx: mpsc::Sender, + shutdown: ShutdownSignal, +) -> Result<(), RpcError> { + tracing::info!("RPC server listening on {}", display_path); + + loop { + tokio::select! { + accept_result = listener.accept() => { + match accept_result { + Ok((stream, _addr)) => { + tracing::debug!("Unix RPC connection accepted"); + let key = rpc_key.clone(); + let tx = transport_tx.clone(); + tokio::spawn(async move { + if let Err(e) = handle_rpc_client(stream, &key, tx).await { + tracing::debug!("Unix RPC client error: {}", e); + } + }); + } + Err(e) => { + tracing::warn!("Unix RPC accept error: {}", e); + } + } + } + _ = shutdown.wait() => { + tracing::info!("Unix RPC server shutting down"); + break; + } + } + } + + Ok(()) +} + +#[cfg(unix)] +fn bind_unix_rpc_listener(socket_path: &str) -> std::io::Result { + if let Some(abstract_name) = socket_path.strip_prefix('\0') { + return bind_abstract_unix_listener(abstract_name); + } + + let _ = std::fs::remove_file(socket_path); + tokio::net::UnixListener::bind(socket_path) +} + +#[cfg(all(unix, any(target_os = "linux", target_os = "android")))] +fn bind_abstract_unix_listener(name: &str) -> std::io::Result { + use std::os::unix::net::{SocketAddr, UnixListener}; + + #[cfg(target_os = "android")] + use std::os::android::net::SocketAddrExt as _; + #[cfg(target_os = "linux")] + use std::os::linux::net::SocketAddrExt as _; + + let addr = SocketAddr::from_abstract_name(name.as_bytes())?; + let listener = UnixListener::bind_addr(&addr)?; + listener.set_nonblocking(true)?; + tokio::net::UnixListener::from_std(listener) +} + +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))] +fn bind_abstract_unix_listener(_name: &str) -> std::io::Result { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "abstract Unix sockets are only available on Linux/Android", + )) +} + +fn display_socket_path(path: &str) -> String { + if let Some(rest) = path.strip_prefix('\0') { + format!("\\0{rest}") + } else { + path.to_string() + } +} + +async fn handle_rpc_client( + mut stream: impl AsyncRead + AsyncWrite + Unpin, + rpc_key: &[u8], + transport_tx: mpsc::Sender, +) -> Result<(), RpcError> { + let challenge = rpc::new_python_challenge(); + let mut challenge_frame = Vec::with_capacity(rpc::MP_CHALLENGE.len() + challenge.len()); + challenge_frame.extend_from_slice(rpc::MP_CHALLENGE); + challenge_frame.extend_from_slice(&challenge); + rpc::write_mp_frame(&mut stream, &challenge_frame).await?; + + let response = rpc::read_mp_frame(&mut stream, 256).await?; + + if !rpc::verify_python_auth_response(rpc_key, &challenge, &response) { + let _ = rpc::write_mp_frame(&mut stream, rpc::MP_FAILURE).await; + return Err(RpcError::AuthFailed); + } + + rpc::write_mp_frame(&mut stream, rpc::MP_WELCOME).await?; + + let client_challenge_frame = rpc::read_mp_frame(&mut stream, 256).await?; + if !client_challenge_frame.starts_with(rpc::MP_CHALLENGE) { + return Err(RpcError::AuthFailed); + } + let client_challenge = &client_challenge_frame[rpc::MP_CHALLENGE.len()..]; + let client_response = rpc::compute_python_auth_response(rpc_key, client_challenge); + rpc::write_mp_frame(&mut stream, &client_response).await?; + let client_welcome = rpc::read_mp_frame(&mut stream, 256).await?; + if client_welcome != rpc::MP_WELCOME { + return Err(RpcError::AuthFailed); + } + + let req_buf = rpc::read_mp_frame(&mut stream, MAX_REQUEST_SIZE).await?; + let request = rpc::decode_request(&req_buf)?; + + let response = process_rpc_request(request, &transport_tx).await; + let resp_data = rpc::encode_response(&response)?; + + rpc::write_mp_frame(&mut stream, &resp_data).await?; + + Ok(()) +} + +/// 5 s cap so a wedged actor can't hold a client open indefinitely. +async fn query_transport( + transport_tx: &mpsc::Sender, + query: rns_transport::messages::TransportQuery, +) -> Option { + let (tx, rx) = tokio::sync::oneshot::channel(); + if transport_tx + .send(TransportMessage::Rpc { + query, + response_tx: tx, + }) + .await + .is_err() + { + return None; + } + tokio::time::timeout(std::time::Duration::from_secs(5), rx) + .await + .ok() + .and_then(|r| r.ok()) +} + +async fn process_rpc_request( + request: RpcRequest, + transport_tx: &mpsc::Sender, +) -> RpcResponse { + use rns_transport::messages::{TransportQuery, TransportQueryResponse}; + + match request { + RpcRequest::GetPathTable { max_hops } => { + match query_transport(transport_tx, TransportQuery::GetPathTable).await { + Some(TransportQueryResponse::PathTable(entries)) => { + let rpc_entries = entries + .into_iter() + .filter(|e| max_hops.is_none_or(|max| e.hops <= max)) + .map(|e| rpc::PathTableEntry { + hash: e.hash.to_vec(), + timestamp: e.timestamp, + via: e.via.map(|v| v.to_vec()), + hops: e.hops, + expires: e.expires, + interface: e.interface, + }) + .collect(); + RpcResponse::PathTable(rpc_entries) + } + _ => RpcResponse::PathTable(Vec::new()), + } + } + RpcRequest::GetInterfaceStats => { + match query_transport(transport_tx, TransportQuery::GetInterfaceStats).await { + Some(TransportQueryResponse::InterfaceStats(entries)) => { + let rpc_entries = entries + .into_iter() + .map(|e| rpc::InterfaceStatEntry { + id: e.id, + name: e.name, + rx_bytes: e.rx_bytes, + tx_bytes: e.tx_bytes, + rx_rate: e.rx_rate, + tx_rate: e.tx_rate, + online: e.online, + bitrate: e.bitrate, + mtu: e.mtu, + mode: e.mode, + role: e.role, + announce_queue: e.announce_queue, + held_announces: e.held_announces, + incoming_announce_frequency: e.incoming_announce_frequency, + outgoing_announce_frequency: e.outgoing_announce_frequency, + clients: e.clients, + announce_rate_target: e.announce_rate_target, + announce_rate_grace: e.announce_rate_grace, + announce_rate_penalty: e.announce_rate_penalty, + announce_cap: e.announce_cap, + ifac_size: e.ifac_size, + tx_drops: e.tx_drops, + }) + .collect(); + RpcResponse::InterfaceStats(rpc_entries) + } + _ => RpcResponse::InterfaceStats(Vec::new()), + } + } + RpcRequest::GetRateTable => { + match query_transport(transport_tx, TransportQuery::GetRateTable).await { + Some(TransportQueryResponse::RateTable(entries)) => { + let rpc_entries = entries + .into_iter() + .map(|e| rpc::RateTableEntry { + hash: e.hash.to_vec(), + rate: e.rate, + last: e.last, + rate_violations: e.rate_violations, + blocked_until: e.blocked_until, + timestamps: e.timestamps, + }) + .collect(); + RpcResponse::RateTable(rpc_entries) + } + _ => RpcResponse::RateTable(Vec::new()), + } + } + RpcRequest::GetLinkCount => { + match query_transport(transport_tx, TransportQuery::GetLinkCount).await { + Some(TransportQueryResponse::IntResult(n)) => RpcResponse::IntResult(n), + _ => RpcResponse::IntResult(0), + } + } + RpcRequest::GetNextHopIfName { destination_hash } => { + let dest = hash_to_array(&destination_hash); + match dest { + Some(d) => { + match query_transport( + transport_tx, + TransportQuery::GetNextHopIfName { dest: d }, + ) + .await + { + Some(TransportQueryResponse::StringResult(s)) => { + RpcResponse::StringResult(s) + } + _ => RpcResponse::StringResult(None), + } + } + None => RpcResponse::StringResult(None), + } + } + RpcRequest::GetNextHop { destination_hash } => { + let dest = hash_to_array(&destination_hash); + match dest { + Some(d) => { + match query_transport(transport_tx, TransportQuery::GetNextHop { dest: d }) + .await + { + Some(TransportQueryResponse::HashResult(h)) => { + RpcResponse::HashResult(h.map(|a| a.to_vec())) + } + _ => RpcResponse::HashResult(None), + } + } + None => RpcResponse::HashResult(None), + } + } + RpcRequest::DropPath { destination_hash } => { + let dest = hash_to_array(&destination_hash); + if let Some(d) = dest { + let _ = query_transport(transport_tx, TransportQuery::DropPath { dest: d }).await; + } + RpcResponse::Ok + } + RpcRequest::DropAnnounceQueues => { + let _ = query_transport(transport_tx, TransportQuery::DropAnnounceQueues).await; + RpcResponse::Ok + } + RpcRequest::GetBlackholedIdentities => { + match query_transport(transport_tx, TransportQuery::GetBlackholedIdentities).await { + Some(TransportQueryResponse::BlackholeList(entries)) => { + let rpc_entries = entries + .into_iter() + .map(|e| rpc::BlackholeEntry { + identity_hash: e.identity_hash.to_vec(), + source: e.source.map(|source| source.to_vec()), + // Wire compat: `until` is absolute expiry (created + ttl); + // permanent entries report `None`. + until: e.ttl.map(|t| e.created + t), + reason: Some( + e.reason_label + .unwrap_or_else(|| e.reason.as_str().to_string()), + ), + }) + .collect(); + RpcResponse::BlackholeList(rpc_entries) + } + _ => RpcResponse::BlackholeList(Vec::new()), + } + } + RpcRequest::BlackholeIdentity { + identity_hash, + until, + reason, + } => { + if let Some(h) = hash_to_array(&identity_hash) { + // `until` (absolute unix ts) → relative TTL; past timestamps + // clamp to ~0 so the entry expires on the next maintenance tick. + let ttl = until.map(|u| { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + (u - now).max(0.001) + }); + let reason_enum = reason + .as_deref() + .map(rns_transport::blackhole::BlackholeReason::parse) + .unwrap_or_default(); + let _ = query_transport( + transport_tx, + TransportQuery::BlackholeIdentity { + hash: h, + ttl, + reason: reason_enum, + reason_label: reason, + }, + ) + .await; + } + RpcResponse::Ok + } + RpcRequest::UnblackholeIdentity { identity_hash } => { + if let Some(h) = hash_to_array(&identity_hash) { + let _ = query_transport( + transport_tx, + TransportQuery::UnblackholeIdentity { hash: h }, + ) + .await; + } + RpcResponse::Ok + } + RpcRequest::GetFirstHopTimeout { destination_hash } => { + let dest = hash_to_array(&destination_hash); + match dest { + Some(d) => { + match query_transport(transport_tx, TransportQuery::FirstHopTimeout { dest: d }) + .await + { + Some(TransportQueryResponse::FloatResult(v)) => RpcResponse::FloatResult(v), + _ => RpcResponse::FloatResult(None), + } + } + None => RpcResponse::FloatResult(None), + } + } + RpcRequest::GetPacketRssi { packet_hash } => { + if let Some(hash) = packet_hash_to_array(&packet_hash) + && let Some(TransportQueryResponse::FloatResult(v)) = query_transport( + transport_tx, + TransportQuery::GetPacketRssi { packet_hash: hash }, + ) + .await + { + RpcResponse::FloatResult(v) + } else { + RpcResponse::FloatResult(None) + } + } + RpcRequest::GetPacketSnr { packet_hash } => { + if let Some(hash) = packet_hash_to_array(&packet_hash) + && let Some(TransportQueryResponse::FloatResult(v)) = query_transport( + transport_tx, + TransportQuery::GetPacketSnr { packet_hash: hash }, + ) + .await + { + RpcResponse::FloatResult(v) + } else { + RpcResponse::FloatResult(None) + } + } + RpcRequest::GetPacketQ { packet_hash } => { + if let Some(hash) = packet_hash_to_array(&packet_hash) + && let Some(TransportQueryResponse::FloatResult(v)) = query_transport( + transport_tx, + TransportQuery::GetPacketQ { packet_hash: hash }, + ) + .await + { + RpcResponse::FloatResult(v) + } else { + RpcResponse::FloatResult(None) + } + } + RpcRequest::DropAllVia { transport_hash } => { + if let Some(next_hop) = hash_to_array(&transport_hash) + && let Some(TransportQueryResponse::IntResult(n)) = + query_transport(transport_tx, TransportQuery::DropAllVia { next_hop }).await + { + return RpcResponse::IntResult(n); + } + RpcResponse::IntResult(0) + } + RpcRequest::UseDestination { destination_hash } => { + if let Some(dest) = hash_to_array(&destination_hash) + && let Some(TransportQueryResponse::BoolResult(v)) = + query_transport(transport_tx, TransportQuery::UseDestination { dest }).await + { + return RpcResponse::BoolResult(v); + } + RpcResponse::BoolResult(false) + } + RpcRequest::RetainDestination { destination_hash } => { + if let Some(dest) = hash_to_array(&destination_hash) + && let Some(TransportQueryResponse::BoolResult(v)) = + query_transport(transport_tx, TransportQuery::RetainDestination { dest }).await + { + return RpcResponse::BoolResult(v); + } + RpcResponse::BoolResult(false) + } + RpcRequest::UnretainDestination { destination_hash } => { + if let Some(dest) = hash_to_array(&destination_hash) + && let Some(TransportQueryResponse::BoolResult(v)) = + query_transport(transport_tx, TransportQuery::UnretainDestination { dest }) + .await + { + return RpcResponse::BoolResult(v); + } + RpcResponse::BoolResult(false) + } + } +} + +fn hash_to_array(hash: &[u8]) -> Option<[u8; 16]> { + if hash.len() >= 16 { + let mut arr = [0u8; 16]; + arr.copy_from_slice(&hash[..16]); + Some(arr) + } else { + None + } +} + +fn packet_hash_to_array(hash: &[u8]) -> Option<[u8; 32]> { + if hash.len() >= 32 { + let mut arr = [0u8; 32]; + arr.copy_from_slice(&hash[..32]); + Some(arr) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_rpc_server_bind_and_shutdown() { + let shutdown = ShutdownSignal::new(); + let (tx, _rx) = mpsc::channel(16); + let rpc_key = vec![0x42u8; 32]; + + let shutdown_clone = shutdown.clone(); + let handle = tokio::spawn(async move { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + run_rpc_server_with_listener(listener, rpc_key, tx, shutdown_clone).await + }); + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + shutdown.trigger(); + + let result = tokio::time::timeout(std::time::Duration::from_secs(2), handle).await; + assert!(result.is_ok(), "server should shut down promptly"); + assert!(result.unwrap().unwrap().is_ok()); + } + + #[tokio::test] + async fn test_rpc_server_auth_and_query() { + let shutdown = ShutdownSignal::new(); + let (actor, tx) = rns_transport::actor::TransportActor::new(); + tokio::spawn(actor.run()); + let rpc_key = b"test_rpc_key_for_auth".to_vec(); + + let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await; + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let response = rpc_client_request(port, &rpc_key, RpcRequest::GetLinkCount).await; + match response { + RpcResponse::IntResult(n) => assert_eq!(n, 0), + other => panic!("expected IntResult(0), got {other:?}"), + } + + shutdown.trigger(); + } + + #[tokio::test] + async fn test_rpc_server_auth_failure() { + let shutdown = ShutdownSignal::new(); + let (tx, _rx) = mpsc::channel(16); + let rpc_key = b"correct_key".to_vec(); + + let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await; + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let mut stream = connect_retry(port).await; + + let challenge_frame = rpc::read_mp_frame(&mut stream, 256).await.unwrap(); + assert!(challenge_frame.starts_with(rpc::MP_CHALLENGE)); + let challenge = &challenge_frame[rpc::MP_CHALLENGE.len()..]; + + let bad_hmac = rpc::compute_python_auth_response(b"wrong_key", challenge); + rpc::write_mp_frame(&mut stream, &bad_hmac).await.unwrap(); + + let result = rpc::read_mp_frame(&mut stream, 256).await.unwrap(); + assert_eq!(result, rpc::MP_FAILURE); + + shutdown.trigger(); + } + + #[tokio::test] + async fn test_rpc_server_multiple_request_types() { + let shutdown = ShutdownSignal::new(); + let (actor, tx) = rns_transport::actor::TransportActor::new(); + tokio::spawn(actor.run()); + let rpc_key = b"multi_test_key".to_vec(); + + let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await; + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let response = + rpc_client_request(port, &rpc_key, RpcRequest::GetPathTable { max_hops: None }).await; + assert!(matches!(response, RpcResponse::PathTable(ref v) if v.is_empty())); + + let response = rpc_client_request(port, &rpc_key, RpcRequest::GetInterfaceStats).await; + assert!(matches!(response, RpcResponse::InterfaceStats(ref v) if v.is_empty())); + + let response = rpc_client_request(port, &rpc_key, RpcRequest::DropAnnounceQueues).await; + assert!(matches!(response, RpcResponse::Ok)); + + let response = rpc_client_request( + port, + &rpc_key, + RpcRequest::GetNextHopIfName { + destination_hash: vec![0; 16], + }, + ) + .await; + assert!(matches!(response, RpcResponse::StringResult(None))); + + shutdown.trigger(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_rpc_server_accepts_python_multiprocessing_client() { + if std::process::Command::new("python3") + .arg("-c") + .arg("import multiprocessing.connection") + .status() + .is_err() + { + return; + } + + let shutdown = ShutdownSignal::new(); + let (actor, tx) = rns_transport::actor::TransportActor::new(); + tokio::spawn(actor.run()); + let rpc_key = b"python_multiprocessing_key".to_vec(); + + let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await; + + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let script = r#" +import multiprocessing.connection +import sys + +port = int(sys.argv[1]) +authkey = bytes.fromhex(sys.argv[2]) +conn = multiprocessing.connection.Client(("127.0.0.1", port), authkey=authkey) +conn.send({"get": "link_count"}) +resp = conn.recv() +conn.close() +if resp != 0: + raise SystemExit(f"unexpected response: {resp!r}") +conn = multiprocessing.connection.Client(("127.0.0.1", port), authkey=authkey) +conn.send({"get": "interface_stats"}) +resp = conn.recv() +conn.close() +if not isinstance(resp, dict) or "interfaces" not in resp: + raise SystemExit(f"unexpected interface_stats response: {resp!r}") +"#; + let output = std::process::Command::new("python3") + .arg("-c") + .arg(script) + .arg(port.to_string()) + .arg(hex::encode(&rpc_key)) + .output() + .expect("python3 should run"); + + shutdown.trigger(); + + assert!( + output.status.success(), + "python client failed\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_rust_client_accepts_python_multiprocessing_listener() { + if std::process::Command::new("python3") + .arg("-c") + .arg("import multiprocessing.connection") + .status() + .is_err() + { + return; + } + + let port = portpicker_ephemeral(); + let rpc_key = b"python_listener_key".to_vec(); + let script = r#" +import multiprocessing.connection +import sys + +port = int(sys.argv[1]) +authkey = bytes.fromhex(sys.argv[2]) +listener = multiprocessing.connection.Listener(("127.0.0.1", port), authkey=authkey) +print("READY", flush=True) +conn = listener.accept() +call = conn.recv() +if call != {"get": "link_count"}: + raise SystemExit(f"unexpected call: {call!r}") +conn.send(7) +conn.close() +listener.close() +"#; + let mut child = std::process::Command::new("python3") + .arg("-c") + .arg(script) + .arg(port.to_string()) + .arg(hex::encode(&rpc_key)) + .stdout(std::process::Stdio::piped()) + .spawn() + .expect("python3 should start"); + + let stdout = child.stdout.take().expect("python listener stdout"); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + use std::io::BufRead as _; + let mut line = String::new(); + let result = std::io::BufReader::new(stdout) + .read_line(&mut line) + .map(|_| line); + let _ = ready_tx.send(result); + }); + match ready_rx.recv_timeout(std::time::Duration::from_secs(5)) { + Ok(Ok(line)) if line.trim() == "READY" => {} + Ok(Ok(line)) => { + let _ = child.kill(); + panic!("unexpected Python listener readiness line: {line:?}"); + } + Ok(Err(e)) => { + let _ = child.kill(); + panic!("failed to read Python listener readiness: {e}"); + } + Err(e) => { + let _ = child.kill(); + panic!("timed out waiting for Python listener readiness: {e}"); + } + } + + match rpc::connect_and_request( + port, + &rpc_key, + &RpcRequest::GetLinkCount, + std::time::Duration::from_secs(5), + ) + .await + { + Ok(RpcResponse::IntResult(7)) => { + let status = child.wait().expect("python listener should exit"); + assert!(status.success(), "python listener exited with {status}"); + } + Ok(other) => { + let _ = child.kill(); + panic!("unexpected Python listener response: {other:?}"); + } + Err(e) => { + let _ = child.kill(); + panic!("Rust client could not connect to Python multiprocessing listener: {e}"); + } + } + } + + #[tokio::test] + async fn test_process_rpc_request_all_variants() { + let (actor, tx) = rns_transport::actor::TransportActor::new(); + tokio::spawn(actor.run()); + + let requests = vec![ + RpcRequest::GetPathTable { max_hops: Some(5) }, + RpcRequest::GetInterfaceStats, + RpcRequest::GetRateTable, + RpcRequest::GetNextHopIfName { + destination_hash: vec![0; 16], + }, + RpcRequest::GetNextHop { + destination_hash: vec![0; 16], + }, + RpcRequest::GetFirstHopTimeout { + destination_hash: vec![0; 16], + }, + RpcRequest::GetLinkCount, + RpcRequest::GetPacketRssi { + packet_hash: vec![0; 32], + }, + RpcRequest::GetPacketSnr { + packet_hash: vec![0; 32], + }, + RpcRequest::GetPacketQ { + packet_hash: vec![0; 32], + }, + RpcRequest::GetBlackholedIdentities, + RpcRequest::DropPath { + destination_hash: vec![0; 16], + }, + RpcRequest::DropAllVia { + transport_hash: vec![0; 16], + }, + RpcRequest::DropAnnounceQueues, + RpcRequest::BlackholeIdentity { + identity_hash: vec![0; 16], + until: Some(99999.0), + reason: Some("test".to_string()), + }, + RpcRequest::UnblackholeIdentity { + identity_hash: vec![0; 16], + }, + RpcRequest::UseDestination { + destination_hash: vec![0; 16], + }, + RpcRequest::RetainDestination { + destination_hash: vec![0; 16], + }, + RpcRequest::UnretainDestination { + destination_hash: vec![0; 16], + }, + ]; + + for req in requests { + let resp = process_rpc_request(req, &tx).await; + assert!( + !matches!(resp, RpcResponse::Error(_)), + "unexpected Error response" + ); + } + + let _ = tx.send(TransportMessage::Shutdown).await; + } + + fn portpicker_ephemeral() -> u16 { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() + } + + async fn rpc_client_request(port: u16, rpc_key: &[u8], request: RpcRequest) -> RpcResponse { + let mut last_err = None; + for _ in 0..20 { + match rpc::connect_and_request( + port, + rpc_key, + &request, + std::time::Duration::from_secs(2), + ) + .await + { + Ok(response) => return response, + Err(e) => { + last_err = Some(e.to_string()); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + } + } + panic!("RPC client request failed: {last_err:?}"); + } + + async fn spawn_test_rpc_server( + rpc_key: Vec, + tx: mpsc::Sender, + shutdown: ShutdownSignal, + ) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let _ = run_rpc_server_with_listener(listener, rpc_key, tx, shutdown).await; + }); + port + } + + async fn connect_retry(port: u16) -> tokio::net::TcpStream { + let addr = format!("127.0.0.1:{port}"); + let mut last_err = None; + for _ in 0..20 { + match tokio::net::TcpStream::connect(&addr).await { + Ok(stream) => return stream, + Err(e) => { + last_err = Some(e); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + } + } + panic!("failed to connect to RPC server on {addr}: {last_err:?}"); + } +} diff --git a/crates/rns-tools/Cargo.toml b/crates/rns-tools/Cargo.toml new file mode 100644 index 0000000..f7c443e --- /dev/null +++ b/crates/rns-tools/Cargo.toml @@ -0,0 +1,65 @@ +[package] +name = "rns-tools" +description = "Rust CLI utilities for Reticulum (rnsd-rs, rnstatus-rs, etc.)" +version.workspace = true +edition.workspace = true +license.workspace = true +autobins = false + +[features] +default = [] +hardware = ["dep:rns-ratkey"] + +[dependencies] +rns-runtime = { workspace = true, features = ["serial"] } +rns-interface = { workspace = true } +rns-identity = { workspace = true } +rns-transport = { workspace = true } +rns-crypto = { workspace = true, features = ["std"] } +rns-wire = { workspace = true, features = ["std"] } +rns-ratkey = { workspace = true, optional = true, features = ["hardware"] } +clap = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +hex = { workspace = true } +rmp-serde = { workspace = true } +rmpv = { workspace = true, features = ["with-serde"] } +base64 = { workspace = true } +serialport = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +nix = { workspace = true } +bytes = { workspace = true } + +[[bin]] +name = "rnsd-rs" +path = "src/bin/rnsd-rs.rs" + +[[bin]] +name = "rnstatus-rs" +path = "src/bin/rnstatus-rs.rs" + +[[bin]] +name = "rnpath-rs" +path = "src/bin/rnpath-rs.rs" + +[[bin]] +name = "rnid-rs" +path = "src/bin/rnid-rs.rs" + +[[bin]] +name = "rnprobe-rs" +path = "src/bin/rnprobe-rs.rs" + +[[bin]] +name = "rncp-rs" +path = "src/bin/rncp-rs.rs" + +[[bin]] +name = "rnodeconf-rs" +path = "src/bin/rnodeconf-rs.rs" + +[[bin]] +name = "rnsh-rs" +path = "src/bin/rnsh-rs.rs" diff --git a/crates/rns-tools/src/bin/rncp-rs.rs b/crates/rns-tools/src/bin/rncp-rs.rs new file mode 100644 index 0000000..b176d9b --- /dev/null +++ b/crates/rns-tools/src/bin/rncp-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rncp.rs"] +mod rncp; + +fn main() { + rncp::main() +} diff --git a/crates/rns-tools/src/bin/rnid-rs.rs b/crates/rns-tools/src/bin/rnid-rs.rs new file mode 100644 index 0000000..47f594d --- /dev/null +++ b/crates/rns-tools/src/bin/rnid-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rnid/main.rs"] +mod rnid; + +fn main() -> std::process::ExitCode { + rnid::main() +} diff --git a/crates/rns-tools/src/bin/rnodeconf-rs.rs b/crates/rns-tools/src/bin/rnodeconf-rs.rs new file mode 100644 index 0000000..db0b83f --- /dev/null +++ b/crates/rns-tools/src/bin/rnodeconf-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rnodeconf.rs"] +mod rnodeconf; + +fn main() -> std::process::ExitCode { + rnodeconf::main() +} diff --git a/crates/rns-tools/src/bin/rnpath-rs.rs b/crates/rns-tools/src/bin/rnpath-rs.rs new file mode 100644 index 0000000..2fa2d98 --- /dev/null +++ b/crates/rns-tools/src/bin/rnpath-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rnpath.rs"] +mod rnpath; + +fn main() -> std::process::ExitCode { + rnpath::main() +} diff --git a/crates/rns-tools/src/bin/rnprobe-rs.rs b/crates/rns-tools/src/bin/rnprobe-rs.rs new file mode 100644 index 0000000..dcfd51a --- /dev/null +++ b/crates/rns-tools/src/bin/rnprobe-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rnprobe.rs"] +mod rnprobe; + +fn main() { + rnprobe::main() +} diff --git a/crates/rns-tools/src/bin/rnsd-rs.rs b/crates/rns-tools/src/bin/rnsd-rs.rs new file mode 100644 index 0000000..afb4532 --- /dev/null +++ b/crates/rns-tools/src/bin/rnsd-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rnsd.rs"] +mod rnsd; + +fn main() { + rnsd::main() +} diff --git a/crates/rns-tools/src/bin/rnsh-rs.rs b/crates/rns-tools/src/bin/rnsh-rs.rs new file mode 100644 index 0000000..3da1e10 --- /dev/null +++ b/crates/rns-tools/src/bin/rnsh-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rnsh.rs"] +mod rnsh; + +fn main() -> std::process::ExitCode { + rnsh::main() +} diff --git a/crates/rns-tools/src/bin/rnstatus-rs.rs b/crates/rns-tools/src/bin/rnstatus-rs.rs new file mode 100644 index 0000000..53620d0 --- /dev/null +++ b/crates/rns-tools/src/bin/rnstatus-rs.rs @@ -0,0 +1,6 @@ +#[path = "../commands/rnstatus.rs"] +mod rnstatus; + +fn main() -> std::process::ExitCode { + rnstatus::main() +} diff --git a/crates/rns-tools/src/commands/rncp.rs b/crates/rns-tools/src/commands/rncp.rs new file mode 100644 index 0000000..c7e63a3 --- /dev/null +++ b/crates/rns-tools/src/commands/rncp.rs @@ -0,0 +1,816 @@ +//! rncp-rs — file transfer (send, listen, fetch). +//! +//! Modes: +//! * `rncp-rs ` — send +//! * `rncp-rs -l [-s ] [-a ] [-F [-j ]]` — listen (optionally serving fetch) +//! * `rncp-rs -f [-s ]` — fetch +//! +//! Exit codes: 0 success, 1 generic failure, 2 identity unreadable, +//! 3 output dir missing, 4 output dir not writable. +//! +//! Security: listener mode follows Python rncp auth semantics. By default it +//! accepts only identities from `-a` or the standard rncp allow-list files. +//! `-n` / `--no-auth` explicitly accepts anyone. Use `-j ` with `-F` +//! unless you intentionally want upstream-compatible unrestricted fetch paths. + +use std::path::PathBuf; +use std::process; +use std::time::Duration; + +use bytes::Bytes; +use clap::Parser; +use rns_identity::destination::{DestType, Destination, Direction}; +use rns_transport::messages::{OutboundRequest, TransportMessage}; +use tokio::io::AsyncWriteExt; + +fn expand_tilde(p: &str) -> PathBuf { + if let Some(rest) = p.strip_prefix("~/") + && let Some(home) = std::env::var_os("HOME") + { + return PathBuf::from(home).join(rest); + } + PathBuf::from(p) +} + +use rns_identity::identity::Identity; +use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers}; +use rns_runtime::platform::StoragePaths; +use rns_runtime::rncp::{ + DEFAULT_RNCP_APP_NAME, RncpError, RncpEvent, RncpFetchOutcome, RncpFetchRequest, + RncpListenerConfig, RncpOutcome, RncpSendRequest, default_rncp_app_name, rncp_fetch_file, + rncp_send_file, spawn_rncp_listener, +}; + +const DEFAULT_TIMEOUT_SECS: f64 = 15.0; +const RETICULUM_COMPAT_VERSION: &str = "1.2.2"; + +#[derive(Parser)] +#[command( + name = "rncp-rs", + about = "Reticulum File Transfer Utility", + disable_version_flag = true +)] +struct Args { + /// Path to alternative Reticulum config directory + #[arg(long, value_name = "path")] + config: Option, + + /// Increase verbosity + #[arg(short = 'v', long, action = clap::ArgAction::Count)] + verbose: u8, + + /// Decrease verbosity + #[arg(short = 'q', long, action = clap::ArgAction::Count)] + quiet: u8, + + /// Disable transfer progress output + #[arg(short = 'S', long)] + silent: bool, + + /// Listen for incoming transfer requests + #[arg(short = 'l', long)] + listen: bool, + + /// Disable automatic compression + #[arg(short = 'C', long)] + no_compress: bool, + + /// Allow clients to fetch files from this listener (use -a or -n; -j is recommended) + #[arg(short = 'F', long)] + allow_fetch: bool, + + /// Fetch file from remote listener instead of sending. Positional args + /// become ` `. + #[arg(short = 'f', long)] + fetch: bool, + + /// Restrict fetch requests to the specified directory (absolute path). + /// Used with -F on listener side, or with -f on fetch client side. + #[arg(short = 'j', long, value_name = "path")] + jail: Option, + + /// Save received files in specified path (listen mode) + #[arg(short = 's', long, value_name = "path")] + save: Option, + + /// Allow overwriting received files instead of adding a numeric postfix + #[arg(short = 'O', long)] + overwrite: bool, + + /// Listen-mode announce interval in seconds; -1 disables, 0 announces once at startup + #[arg(short = 'b', value_name = "seconds", default_value_t = -1)] + announce_interval: i64, + + /// Allowed sender identity hash (repeat for multiple). 32 hex chars each. + #[arg(short = 'a', value_name = "hash", action = clap::ArgAction::Append)] + allowed: Vec, + + /// Accept requests from anyone. + #[arg(short = 'n', long = "no-auth")] + no_auth: bool, + + /// Print identity and destination hash, then exit (listen mode) + #[arg(short = 'p', long)] + print_identity: bool, + + /// Path to identity file to use (default: `/identities/rncp`) + #[arg(short = 'i', value_name = "identity")] + identity_path: Option, + + /// Timeout before giving up (seconds) + #[arg(short = 'w', value_name = "seconds", default_value_t = DEFAULT_TIMEOUT_SECS)] + timeout: f64, + + /// Display physical layer transfer rates. + #[arg(short = 'P', long = "phy-rates")] + phy_rates: bool, + + /// Print version and exit. + #[arg(long)] + version: bool, + + /// File to be transferred (send mode) + file: Option, + + /// Hexadecimal hash of the receiver (send mode, 32 hex chars) + destination: Option, +} + +fn parse_dest_hash(hex_str: &str) -> Result<[u8; 16], String> { + if hex_str.len() != 32 { + return Err( + "Destination length is invalid, must be 32 hexadecimal characters (16 bytes)." + .to_string(), + ); + } + let bytes = hex::decode(hex_str) + .map_err(|_| "Invalid destination entered. Check your input.".to_string())?; + <[u8; 16]>::try_from(bytes.as_slice()) + .map_err(|_| "Invalid destination entered. Check your input.".to_string()) +} + +// Default path: `/identities/rncp`; `-i` overrides. +fn load_or_create_identity( + identity_path: Option<&str>, + default_dir: &std::path::Path, +) -> Result { + let path = match identity_path { + Some(p) => expand_tilde(p), + None => default_dir.join("rncp"), + }; + + if path.is_file() { + match Identity::from_file(&path) { + Ok(id) => Ok(id), + Err(e) => Err(( + 2, + format!( + "Could not load identity for rncp. The identity file at \"{}\" may be corrupt or unreadable: {e}", + path.display() + ), + )), + } + } else { + if let Some(parent) = path.parent() + && let Err(e) = std::fs::create_dir_all(parent) + { + return Err(( + 2, + format!( + "Could not create identity directory \"{}\": {e}", + parent.display() + ), + )); + } + let id = Identity::new(); + if let Err(e) = id.to_file(&path) { + return Err(( + 2, + format!("Could not persist identity to \"{}\": {e}", path.display()), + )); + } + Ok(id) + } +} + +#[tokio::main] +pub(crate) async fn main() { + let args = Args::parse(); + if args.version { + println!("rncp-rs {RETICULUM_COMPAT_VERSION}"); + return; + } + if args.phy_rates { + eprintln!( + "rncp-rs: -P/--phy-rates is not implemented yet; the Rust resource layer currently exposes logical transfer progress only." + ); + process::exit(2); + } + + let level = match (args.verbose as i32) - (args.quiet as i32) { + n if n >= 2 => tracing::Level::DEBUG, + 1 => tracing::Level::INFO, + 0 => tracing::Level::WARN, + _ => tracing::Level::ERROR, + }; + tracing_subscriber::fmt() + .with_max_level(level) + .with_writer(std::io::stderr) + .init(); + + if args.fetch { + run_fetch(args).await; + } else if args.listen { + run_listen(args).await; + } else { + run_send(args).await; + } +} + +async fn run_fetch(args: Args) -> ! { + // In fetch mode the positionals are ` `. + let (Some(dest_arg), Some(path_arg)) = (args.file.as_ref(), args.destination.as_ref()) else { + eprintln!("rncp-rs: fetch mode requires "); + process::exit(1); + }; + + let dest_hash = match parse_dest_hash(dest_arg) { + Ok(h) => h, + Err(e) => { + eprintln!("{e}"); + process::exit(1); + } + }; + + let save_dir = match args.save.as_deref() { + Some(p) => { + let path = expand_tilde(p); + if !path.is_dir() { + eprintln!("Output directory not found"); + process::exit(3); + } + let probe = path.join(".rncp_write_test"); + match std::fs::File::create(&probe) { + Ok(_) => { + let _ = std::fs::remove_file(&probe); + } + Err(_) => { + eprintln!("Output directory not writable"); + process::exit(4); + } + } + path + } + None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), + }; + + let handle = start_reticulum(args.config.as_deref()).await; + let paths = StoragePaths::from_config_dir(&handle.config_dir); + let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir) + { + Ok(id) => id, + Err((code, msg)) => { + eprintln!("{msg}"); + process::exit(code); + } + }; + + if !args.silent { + println!("Fetching \"{path_arg}\" from <{}>", hex::encode(dest_hash)); + } + + let timeout = Duration::from_secs_f64(args.timeout.max(1.0)); + let path_wait = timeout; + + let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel::(32); + let silent = args.silent; + let progress_task = tokio::spawn(async move { + let mut last = -1.0_f32; + while let Some(p) = progress_rx.recv().await { + if silent { + continue; + } + if (p - last).abs() < 0.01 && p < 1.0 { + continue; + } + last = p; + let pct = (p * 100.0).clamp(0.0, 100.0); + let mut stderr = tokio::io::stderr(); + let _ = stderr + .write_all(format!("\rfetch: {pct:5.1}% ").as_bytes()) + .await; + let _ = stderr.flush().await; + } + if !silent { + let _ = tokio::io::stderr().write_all(b"\n").await; + } + }); + + let result = rncp_fetch_file(RncpFetchRequest { + transport_tx: handle.transport_tx.clone(), + identity, + dest_hash, + remote_path: path_arg, + save_dir: &save_dir, + overwrite: args.overwrite, + overall_timeout: timeout, + path_wait, + progress_tx: Some(progress_tx), + }) + .await; + + let _ = progress_task.await; + + match result { + Ok(outcome) => { + if !args.silent { + print_fetch_summary(&outcome); + } + process::exit(0); + } + Err(RncpError::PathTimeout) => { + eprintln!("Path not found"); + process::exit(1); + } + Err(RncpError::NoIdentity) => { + eprintln!("Destination's identity is not known."); + process::exit(1); + } + Err(RncpError::Timeout(what)) => { + eprintln!("Timed out waiting for {what}"); + process::exit(1); + } + Err(RncpError::Denied) => { + eprintln!("Remote denied the fetch (not in allow-list or outside jail)."); + process::exit(1); + } + Err(RncpError::ResourceFailed(reason)) => { + eprintln!("Fetch failed: {reason}"); + process::exit(1); + } + Err(e) => { + eprintln!("rncp-rs: fetch failed: {e}"); + process::exit(1); + } + } +} + +fn print_fetch_summary(outcome: &RncpFetchOutcome) { + let elapsed = outcome.duration.as_secs_f64().max(1e-6); + let throughput_bps = (outcome.bytes as f64) * 8.0 / elapsed; + let (t_value, t_unit) = human_rate(throughput_bps); + println!( + "Fetched \"{}\" ({} bytes) in {:.2}s ({:.2} {}) → {}", + outcome.file_name, + outcome.bytes, + elapsed, + t_value, + t_unit, + outcome.saved_path.display() + ); +} + +async fn run_send(args: Args) -> ! { + let (Some(file_arg), Some(dest_arg)) = (args.file.as_ref(), args.destination.as_ref()) else { + // Bare `rncp` prints help and exits 0. + let mut cmd = ::command(); + cmd.print_help().ok(); + println!(); + process::exit(0); + }; + + let dest_hash = match parse_dest_hash(dest_arg) { + Ok(h) => h, + Err(e) => { + eprintln!("{e}"); + process::exit(1); + } + }; + + let file_path = expand_tilde(file_arg); + if !file_path.is_file() { + eprintln!("File not found"); + process::exit(1); + } + + let file_name = file_path + .file_name() + .and_then(|s| s.to_str()) + .map(|s| s.to_string()) + .unwrap_or_else(|| "file".to_string()); + + let data = match tokio::fs::read(&file_path).await { + Ok(d) => d, + Err(e) => { + eprintln!("Failed to read \"{}\": {e}", file_path.display()); + process::exit(1); + } + }; + + let handle = start_reticulum(args.config.as_deref()).await; + + let paths = StoragePaths::from_config_dir(&handle.config_dir); + let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir) + { + Ok(id) => id, + Err((code, msg)) => { + eprintln!("{msg}"); + process::exit(code); + } + }; + + if !args.silent { + println!("Sending \"{file_name}\" to <{}>", hex::encode(dest_hash)); + } + + let timeout = Duration::from_secs_f64(args.timeout.max(1.0)); + let path_wait = timeout; + let auto_compress = !args.no_compress; + let bytes_total = data.len(); + + let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel::(32); + let silent = args.silent; + let progress_task = tokio::spawn(async move { + let mut last = -1.0_f32; + while let Some(p) = progress_rx.recv().await { + if silent { + continue; + } + if (p - last).abs() < 0.01 && p < 1.0 { + continue; + } + last = p; + let pct = (p * 100.0).clamp(0.0, 100.0); + let mut stderr = tokio::io::stderr(); + let _ = stderr + .write_all(format!("\rtransfer: {pct:5.1}% ").as_bytes()) + .await; + let _ = stderr.flush().await; + } + if !silent { + let _ = tokio::io::stderr().write_all(b"\n").await; + } + }); + + let result = rncp_send_file(RncpSendRequest { + transport_tx: handle.transport_tx.clone(), + identity, + dest_hash, + file_name: &file_name, + data, + auto_compress, + overall_timeout: timeout, + path_wait, + progress_tx: Some(progress_tx), + }) + .await; + + let _ = progress_task.await; + + match result { + Ok(outcome) => { + if !args.silent { + print_send_summary(&outcome, bytes_total); + } + process::exit(0); + } + Err(RncpError::PathTimeout) => { + eprintln!("Path not found"); + process::exit(1); + } + Err(RncpError::NoIdentity) => { + eprintln!( + "Destination's identity is not known — wait for an announce or use rnstatus to verify the destination has been seen." + ); + process::exit(1); + } + Err(RncpError::Timeout(what)) => { + eprintln!("Timed out waiting for {what}"); + process::exit(1); + } + Err(RncpError::ResourceFailed(reason)) => { + eprintln!( + "File was not accepted by <{}>: {reason}", + hex::encode(dest_hash) + ); + process::exit(1); + } + Err(e) => { + eprintln!("rncp-rs: transfer failed: {e}"); + process::exit(1); + } + } +} + +fn print_send_summary(outcome: &RncpOutcome, bytes: usize) { + let elapsed = outcome.duration.as_secs_f64().max(1e-6); + let throughput_bps = (bytes as f64) * 8.0 / elapsed; + let (t_value, t_unit) = human_rate(throughput_bps); + println!( + "Transferred {} bytes in {:.2}s ({:.2} {})", + bytes, elapsed, t_value, t_unit + ); +} + +fn human_rate(bps: f64) -> (f64, &'static str) { + if bps >= 1_000_000_000.0 { + (bps / 1_000_000_000.0, "Gbps") + } else if bps >= 1_000_000.0 { + (bps / 1_000_000.0, "Mbps") + } else if bps >= 1_000.0 { + (bps / 1_000.0, "kbps") + } else { + (bps, "bps") + } +} + +async fn run_listen(args: Args) -> ! { + let save_dir = match args.save.as_deref() { + Some(p) => { + let path = expand_tilde(p); + if !path.exists() { + eprintln!("Output directory not found"); + process::exit(3); + } + if !path.is_dir() { + eprintln!("Output directory not found"); + process::exit(3); + } + // Probe-file write test (no portable W_OK check on all platforms). + let probe = path.join(".rncp_write_test"); + match std::fs::File::create(&probe) { + Ok(_) => { + let _ = std::fs::remove_file(&probe); + } + Err(_) => { + eprintln!("Output directory not writable"); + process::exit(4); + } + } + path + } + None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), + }; + + let allowed: Vec<[u8; 16]> = { + let mut v = Vec::with_capacity(args.allowed.len()); + for a in &args.allowed { + match parse_dest_hash(a) { + Ok(h) => v.push(h), + Err(e) => { + eprintln!("{e}"); + process::exit(1); + } + } + } + extend_allowed_from_files(&mut v); + v + }; + let allow_all = args.no_auth; + if allowed.is_empty() && !allow_all && !args.print_identity { + eprintln!("Warning: No allowed identities configured, rncp will not accept any files!"); + } + + let handle = start_reticulum(args.config.as_deref()).await; + let paths = StoragePaths::from_config_dir(&handle.config_dir); + let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir) + { + Ok(id) => id, + Err((code, msg)) => { + eprintln!("{msg}"); + process::exit(code); + } + }; + let announce_identity = identity + .get_private_key() + .and_then(|key| Identity::from_private_key(&*key).ok()); + + if args.print_identity { + let dest = match rns_identity::destination::Destination::new( + Some(&identity), + rns_identity::destination::Direction::In, + rns_identity::destination::DestType::Single, + DEFAULT_RNCP_APP_NAME, + ) { + Ok(d) => d, + Err(e) => { + eprintln!("Failed to derive destination: {e:?}"); + process::exit(2); + } + }; + println!("Identity : {}", hex::encode(identity.hash)); + println!("Listening on : {}", hex::encode(dest.hash)); + process::exit(0); + } + + let fetch_jail = args.jail.as_deref().map(expand_tilde); + if let Some(ref jail) = fetch_jail + && !jail.is_dir() + { + eprintln!("Fetch jail directory not found: {}", jail.display()); + process::exit(3); + } + + let (event_tx, mut event_rx) = tokio::sync::mpsc::channel::(64); + let cfg = RncpListenerConfig { + identity, + app_name: default_rncp_app_name().to_string(), + save_dir, + allow_all, + allowed, + overwrite: args.overwrite, + allow_fetch: args.allow_fetch, + fetch_jail, + fetch_auto_compress: !args.no_compress, + }; + let listener = match spawn_rncp_listener(handle.transport_tx.clone(), cfg, event_tx).await { + Ok(h) => h, + Err(e) => { + eprintln!("rncp-rs: failed to start listener: {e}"); + process::exit(1); + } + }; + let announce_task = spawn_listen_announcer( + handle.transport_tx.clone(), + announce_identity, + listener.destination_hash(), + args.announce_interval, + ); + + if !args.silent { + println!( + "rncp-rs listening on <{}> — waiting for transfers. Ctrl-C to stop.", + hex::encode(listener.destination_hash()) + ); + } + + loop { + tokio::select! { + ev = event_rx.recv() => { + let Some(ev) = ev else { break }; + match ev { + RncpEvent::LinkEstablished { link_id } => { + if !args.silent { + println!("link established: <{}>", hex::encode(link_id)); + } + } + RncpEvent::SenderIdentified { link_id, identity_hash } => { + if !args.silent { + println!( + "sender identified on <{}>: <{}>", + hex::encode(link_id), + hex::encode(identity_hash) + ); + } + } + RncpEvent::SenderDenied { link_id, identity_hash } => { + eprintln!( + "denied sender <{}> on <{}> (not in allow-list)", + hex::encode(identity_hash), + hex::encode(link_id) + ); + } + RncpEvent::Completed { file_name, saved_path, bytes, .. } => { + println!( + "received \"{file_name}\" ({bytes} bytes) → {}", + saved_path.display() + ); + } + RncpEvent::WriteFailed { file_name, reason, .. } => { + eprintln!("write failed for \"{file_name}\": {reason}"); + } + RncpEvent::FetchServing { link_id, file_name, bytes } => { + if !args.silent { + println!( + "serving fetch \"{file_name}\" ({bytes} bytes) on <{}>", + hex::encode(link_id) + ); + } + } + RncpEvent::FetchDenied { link_id, reason } => { + eprintln!( + "denied fetch on <{}>: {reason}", + hex::encode(link_id) + ); + } + } + } + } + } + + if let Some(task) = announce_task { + task.abort(); + let _ = task.await; + } + + process::exit(0); +} + +fn spawn_listen_announcer( + transport_tx: tokio::sync::mpsc::Sender, + identity: Option, + destination_hash: [u8; 16], + interval_seconds: i64, +) -> Option> { + if interval_seconds < 0 { + return None; + } + let Some(identity) = identity else { + tracing::warn!("rncp-rs: listener identity has no private key; announce disabled"); + return None; + }; + + Some(tokio::spawn(async move { + let mut destination = match Destination::new( + Some(&identity), + Direction::In, + DestType::Single, + default_rncp_app_name(), + ) { + Ok(destination) => destination, + Err(e) => { + tracing::warn!(error = ?e, "rncp-rs: could not build announce destination"); + return; + } + }; + + loop { + send_rncp_announce(&transport_tx, &mut destination, &identity, destination_hash).await; + if interval_seconds == 0 { + break; + } + tokio::time::sleep(Duration::from_secs(interval_seconds as u64)).await; + } + })) +} + +async fn send_rncp_announce( + transport_tx: &tokio::sync::mpsc::Sender, + destination: &mut Destination, + identity: &Identity, + destination_hash: [u8; 16], +) { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0); + let raw = match destination.announce_packet(identity, None, None, false, None, now) { + Ok(raw) => raw, + Err(e) => { + tracing::warn!(error = %e, "rncp-rs: could not build announce packet"); + return; + } + }; + + if transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash, + })) + .await + .is_err() + { + tracing::warn!("rncp-rs: transport stopped before announce could be sent"); + } +} + +fn extend_allowed_from_files(allowed: &mut Vec<[u8; 16]>) { + for path in rncp_allowed_identity_file_candidates() { + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + for line in text.lines() { + let value = line.trim(); + if value.len() != 32 { + continue; + } + if let Ok(hash) = parse_dest_hash(value) { + allowed.push(hash); + } + } + break; + } +} + +fn rncp_allowed_identity_file_candidates() -> Vec { + let mut paths = vec![PathBuf::from("/etc/rncp/allowed_identities")]; + if let Some(home) = std::env::var_os("HOME") { + let home = PathBuf::from(home); + paths.push(home.join(".config/rncp/allowed_identities")); + paths.push(home.join(".rncp/allowed_identities")); + } + paths +} + +async fn start_reticulum(config_dir: Option<&str>) -> rns_runtime::reticulum::ReticulumHandle { + let shutdown = ShutdownSignal::new(); + let _signal_rx = install_signal_handlers(shutdown.clone()); + let is_foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + match rns_runtime::reticulum::init(config_dir, None, shutdown.clone(), is_foreground).await { + Ok(h) => h, + Err(e) => { + eprintln!("failed to start reticulum: {e}"); + process::exit(1); + } + } +} diff --git a/crates/rns-tools/src/commands/rnid/hw_commands.rs b/crates/rns-tools/src/commands/rnid/hw_commands.rs new file mode 100644 index 0000000..2f8e50e --- /dev/null +++ b/crates/rns-tools/src/commands/rnid/hw_commands.rs @@ -0,0 +1,377 @@ +use super::HwCommands; +use std::path::PathBuf; + +pub fn run(cmd: HwCommands) { + match cmd { + HwCommands::Detect => cmd_detect(), + HwCommands::Provision { + pin, + nickname, + output, + } => { + cmd_provision(pin, nickname, output); + } + HwCommands::List { dir } => cmd_list(dir), + HwCommands::Info { hwid } => cmd_info(hwid), + HwCommands::Verify { hwid } => cmd_verify(hwid), + HwCommands::Test { hwid } => cmd_test(hwid), + } +} + +fn cmd_detect() { + println!("Scanning for hardware tokens...\n"); + + match rns_ratkey::detect::detect_devices() { + Ok(devices) => { + if devices.is_empty() { + println!("No compatible hardware tokens found."); + println!("\nSupported devices:"); + println!(" - YubiKey 5 (firmware 5.7.0+)"); + println!(" - Nitrokey 3"); + println!("\nOn Linux, ensure pcscd is running: sudo systemctl start pcscd"); + } else { + println!("Found {} device(s):\n", devices.len()); + for (i, dev) in devices.iter().enumerate() { + println!(" {}. {} ({})", i + 1, dev.device_type, dev.reader_name); + if let Some(serial) = dev.serial { + println!(" Serial: {serial}"); + } + if let Some(ref fw) = dev.firmware { + println!(" Firmware: {fw}"); + } + println!( + " Slot 9A (signing): {}", + if dev.has_signing_key { + "occupied" + } else { + "empty" + } + ); + println!( + " Slot 9D (encryption): {}", + if dev.has_encryption_key { + "occupied" + } else { + "empty" + } + ); + println!(); + } + } + } + Err(e) => { + eprintln!("Error detecting devices: {e}"); + std::process::exit(1); + } + } +} + +fn cmd_provision(pin: Option, nickname: Option, output: Option) { + let pin = match pin { + Some(p) => p, + None => { + eprintln!("Error: --pin is required for provisioning"); + eprintln!("Usage: rnid-rs hw provision --pin [--nickname ]"); + std::process::exit(1); + } + }; + + if pin.len() < 6 || pin.len() > 8 { + eprintln!("Error: PIN must be 6-8 characters"); + std::process::exit(1); + } + + let mut session = match rns_ratkey::session::PivSession::connect() { + Ok(s) => s, + Err(e) => { + eprintln!("Error connecting to hardware token: {e}"); + eprintln!("\nRun `rnid-rs hw detect` to check for connected devices."); + std::process::exit(1); + } + }; + + if let Err(e) = session.verify_pin(&pin) { + eprintln!("PIN verification failed: {e}"); + std::process::exit(1); + } + + // Slot 9A (PIV authentication), touch-always: prevents silent sign while PIN cache valid. + println!("Generating Ed25519 key in slot 9A..."); + let ed_pub = match session.generate_ed25519( + rns_ratkey::apdu::SLOT_AUTHENTICATION, + Some(rns_ratkey::apdu::PIN_POLICY_ONCE), + Some(rns_ratkey::apdu::TOUCH_POLICY_ALWAYS), + ) { + Ok(pub_key) => pub_key, + Err(e) => { + eprintln!("Error generating Ed25519 key: {e}"); + std::process::exit(1); + } + }; + + // Slot 9D (PIV key management), touch-cached: one tap unlocks ECDH for a window (else every packet prompts). + println!("Generating X25519 key in slot 9D..."); + let x_pub = match session.generate_x25519( + rns_ratkey::apdu::SLOT_KEY_MANAGEMENT, + Some(rns_ratkey::apdu::PIN_POLICY_ONCE), + Some(rns_ratkey::apdu::TOUCH_POLICY_CACHED), + ) { + Ok(pub_key) => pub_key, + Err(e) => { + eprintln!("Error generating X25519 key: {e}"); + std::process::exit(1); + } + }; + + let identity_hash = rns_ratkey::provision::compute_identity_hash(&ed_pub, &x_pub); + let hash_hex = hex::encode(identity_hash); + + println!("\nHardware identity provisioned:"); + println!(" Identity hash: {hash_hex}"); + println!(" Ed25519 public: {}", hex::encode(ed_pub)); + println!(" X25519 public: {}", hex::encode(x_pub)); + println!(" Device: {}", session.device_type().as_str()); + + if let Some(dir) = output { + let identity_dir = dir.join(&hash_hex); + if let Err(e) = std::fs::create_dir_all(&identity_dir) { + eprintln!("Error creating directory: {e}"); + std::process::exit(1); + } + let path = identity_dir.join("identity.hwid"); + + let config = rns_ratkey::hwid::HwidConfig { + identity: rns_ratkey::hwid::HwidIdentity { + hash: hash_hex.clone(), + nickname: nickname.unwrap_or_default(), + created_at: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + }, + device: rns_ratkey::hwid::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: rns_ratkey::hwid::HwidKeys { + ed25519_pub: hex::encode(ed_pub), + x25519_pub: hex::encode(x_pub), + }, + slots: rns_ratkey::hwid::HwidSlots { + signing: "9A".to_string(), + encryption: "9D".to_string(), + }, + policy: rns_ratkey::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(), + }; + + match config.to_file(&path) { + Ok(()) => println!(" Saved to: {}", path.display()), + Err(e) => eprintln!(" Warning: failed to write .hwid file: {e}"), + } + } + + println!("\nWARNING: No backup exists. If you lose this device, this identity"); + println!("is gone forever. Run `rnid-rs hw backup` to create a backup."); +} + +fn cmd_list(dir: Option) { + let dir = dir.unwrap_or_else(|| { + eprintln!("Error: --dir is required (directory containing identity folders)"); + std::process::exit(1); + }); + + if !dir.exists() { + eprintln!("Directory does not exist: {}", dir.display()); + std::process::exit(1); + } + + let mut found = 0; + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten() { + let hwid_path = entry.path().join("identity.hwid"); + if hwid_path.exists() { + match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) { + Ok(config) => { + found += 1; + println!( + " {} ({}, {})", + config.identity.hash, + config.device.device_type, + if config.identity.nickname.is_empty() { + "unnamed" + } else { + &config.identity.nickname + } + ); + } + Err(e) => { + eprintln!(" Error reading {}: {e}", hwid_path.display()); + } + } + } + } + } + + if found == 0 { + println!("No hardware identities found in {}", dir.display()); + } else { + println!("\n{found} hardware identity(s) found."); + } +} + +fn cmd_info(hwid_path: PathBuf) { + let config = match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) { + Ok(c) => c, + Err(e) => { + eprintln!("Error reading .hwid file: {e}"); + std::process::exit(1); + } + }; + + println!("Hardware Identity Information:"); + println!(" Hash: {}", config.identity.hash); + println!( + " Nickname: {}", + if config.identity.nickname.is_empty() { + "(none)" + } else { + &config.identity.nickname + } + ); + println!( + " Created: {} (Unix timestamp)", + config.identity.created_at + ); + println!(); + println!("Device:"); + println!(" Type: {}", config.device.device_type); + println!(" Serial: {}", config.device.serial); + println!(" Firmware: {}", config.device.firmware); + println!(); + println!("Keys:"); + println!(" Ed25519 public: {}", config.keys.ed25519_pub); + println!(" X25519 public: {}", config.keys.x25519_pub); + println!(); + println!("Slots:"); + println!(" Signing: {}", config.slots.signing); + println!(" Encryption: {}", config.slots.encryption); + println!(); + println!("Policy:"); + println!(" PIN cache: {}s", config.policy.pin_cache_timeout); + println!(" Touch (sign): {}", config.policy.touch_signing); + println!(" Touch (encrypt): {}", config.policy.touch_encryption); + println!(); + println!("Backup:"); + println!(" Tier: {}", config.backup.tier); + if !config.attestation.ed25519_cert.is_empty() { + println!( + " Attestation: chain_verified={}", + config.attestation.verified + ); + } else { + println!(" Attestation: (none)"); + } +} + +fn cmd_verify(hwid_path: PathBuf) { + let config = match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) { + Ok(c) => c, + Err(e) => { + eprintln!("Error reading .hwid file: {e}"); + std::process::exit(1); + } + }; + + println!("Verifying hardware identity {}...", config.identity.hash); + + let session = match rns_ratkey::session::PivSession::connect() { + Ok(s) => s, + Err(e) => { + eprintln!("Error: cannot connect to hardware token: {e}"); + std::process::exit(1); + } + }; + + let metadata = match session.read_metadata(rns_ratkey::apdu::SLOT_AUTHENTICATION) { + Ok(m) => m, + Err(e) => { + eprintln!("Error reading slot 9A: {e}"); + std::process::exit(1); + } + }; + + println!(" Slot 9A metadata: {} bytes", metadata.len()); + println!(" Verification requires comparing public keys from device with .hwid file."); + println!(" (Full verification implemented when hardware is available for testing)"); +} + +fn cmd_test(hwid_path: PathBuf) { + let config = match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) { + Ok(c) => c, + Err(e) => { + eprintln!("Error reading .hwid file: {e}"); + std::process::exit(1); + } + }; + + println!("Testing hardware identity {}...\n", config.identity.hash); + + let session = match rns_ratkey::session::PivSession::connect() { + Ok(s) => s, + Err(e) => { + eprintln!("Error: cannot connect to hardware token: {e}"); + std::process::exit(1); + } + }; + + println!("1. Testing Ed25519 signing in slot 9A..."); + let test_msg = b"RATKEY hardware identity test message"; + match session.sign_ed25519(rns_ratkey::apdu::SLOT_AUTHENTICATION, test_msg) { + Ok(sig) => { + let ed_pub = config.ed25519_pub_bytes().unwrap(); + let pub_key = rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&ed_pub).unwrap(); + if pub_key.verify(test_msg, &sig).is_ok() { + println!(" PASS: signature verified"); + } else { + println!(" FAIL: signature verification failed"); + std::process::exit(1); + } + } + Err(e) => { + println!(" FAIL: {e}"); + std::process::exit(1); + } + } + + println!("2. Testing X25519 ECDH in slot 9D..."); + let peer_prv = rns_crypto::x25519::X25519PrivateKey::generate(); + let peer_pub = peer_prv.public_key().to_bytes(); + match session.ecdh_x25519(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT, &peer_pub) { + Ok(shared) => { + println!(" PASS: ECDH returned {} bytes", shared.len()); + let hw_pub_bytes = config.x25519_pub_bytes().unwrap(); + let hw_pub = rns_crypto::x25519::X25519PublicKey::from_bytes(&hw_pub_bytes); + let peer_shared = peer_prv.exchange(&hw_pub); + if shared == peer_shared { + println!(" PASS: ECDH is symmetric"); + } else { + println!(" FAIL: ECDH shared secrets do not match"); + std::process::exit(1); + } + } + Err(e) => { + println!(" FAIL: {e}"); + std::process::exit(1); + } + } + + println!("\nAll tests passed."); +} diff --git a/crates/rns-tools/src/commands/rnid/main.rs b/crates/rns-tools/src/commands/rnid/main.rs new file mode 100644 index 0000000..330d6a1 --- /dev/null +++ b/crates/rns-tools/src/commands/rnid/main.rs @@ -0,0 +1,1033 @@ +//! rnid-rs - identity create/inspect/sign/verify/encrypt/decrypt. +//! +//! Python reference: `RNS/Utilities/rnid.py` from Reticulum 1.2.2. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE; +#[cfg(feature = "hardware")] +use clap::Subcommand; +use clap::{CommandFactory, Parser}; +use rns_identity::destination::{DestType, Destination, Direction}; +use rns_identity::identity::Identity; +use rns_transport::messages::{ + OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse, +}; + +#[cfg(feature = "hardware")] +mod hw_commands; + +const RETICULUM_COMPAT_VERSION: &str = "1.2.2"; +const SIG_EXT: &str = "rsg"; +const ENCRYPT_EXT: &str = "rfe"; +const CHUNK_SIZE: usize = 16 * 1024 * 1024; +const BLOCK_SIZE: usize = 16; +// Python rnid decrypts fixed 16 MiB ciphertext chunks. Cap plaintext so each +// full encrypted token lands on that boundary after identity overhead + padding. +const PYTHON_COMPAT_PLAINTEXT_CHUNK_SIZE: usize = + CHUNK_SIZE - rns_identity::identity::IDENTITY_OVERHEAD - BLOCK_SIZE; +const FULL_CHUNK_TOKEN_SIZE: usize = + CHUNK_SIZE + rns_identity::identity::IDENTITY_OVERHEAD + BLOCK_SIZE; + +#[derive(Parser)] +#[command( + name = "rnid-rs", + about = "Reticulum Identity & Encryption Utility", + disable_version_flag = true +)] +struct Args { + /// Path to alternative Reticulum config directory. + #[arg(long)] + config: Option, + + /// Hexadecimal identity/destination hash, or path to an Identity file. + #[arg(short = 'i', long)] + identity: Option, + + /// Generate a new Identity and write it to this file. + #[arg(short = 'g', long)] + generate: Option, + + /// Import private Identity data in hex, base32 or base64 format. + #[arg(short = 'm', long = "import", value_name = "identity_data")] + import_str: Option, + + /// Export private Identity data in hex, base32 or base64 format. + #[arg(short = 'x', long)] + export: bool, + + /// Increase verbosity. + #[arg(short = 'v', long, action = clap::ArgAction::Count)] + verbose: u8, + + /// Decrease verbosity. + #[arg(short = 'q', long, action = clap::ArgAction::Count)] + quiet: u8, + + /// Announce a destination based on this Identity. + #[arg(short = 'a', long)] + announce: Option, + + /// Show destination hash for aspects based on this Identity. + #[arg(short = 'H', long = "hash")] + hash: Option, + + /// Encrypt file. + #[arg(short = 'e', long)] + encrypt: Option, + + /// Decrypt file. + #[arg(short = 'd', long)] + decrypt: Option, + + /// Sign file. + #[arg(short = 's', long)] + sign: Option, + + /// Validate signature. + #[arg(short = 'V', long = "validate")] + validate: Option, + + /// Input file path. + #[arg(short = 'r', long)] + read: Option, + + /// Output file path. + #[arg(short = 'w', long)] + write: Option, + + /// Write output even if it overwrites existing files. + #[arg(short = 'f', long)] + force: bool, + + /// Request unknown Identities from the network. + #[arg(short = 'R', long = "request")] + request: bool, + + /// Identity request timeout before giving up. + #[arg(short = 't', value_name = "seconds", default_value_t = rns_transport::constants::PATH_REQUEST_TIMEOUT)] + timeout: f64, + + /// Print identity info and exit. + #[arg(short = 'p', long = "print-identity")] + print_identity: bool, + + /// Allow displaying private keys. + #[arg(short = 'P', long = "print-private")] + print_private: bool, + + /// Use base64-encoded input and output. + #[arg(short = 'b', long)] + base64: bool, + + /// Use base32-encoded input and output. + #[arg(short = 'B', long)] + base32: bool, + + /// Print version and exit. + #[arg(long)] + version: bool, + + /// Parsed for Python CLI parity; Reticulum 1.2.2 does not implement it. + #[arg(short = 'I', long = "stdin", hide = true)] + stdin: bool, + + /// Parsed for Python CLI parity; Reticulum 1.2.2 does not implement it. + #[arg(short = 'O', long = "stdout", hide = true)] + stdout: bool, +} + +#[cfg(feature = "hardware")] +#[derive(Subcommand)] +enum HwCommands { + Detect, + Provision { + #[arg(long)] + pin: Option, + #[arg(short, long)] + nickname: Option, + #[arg(short, long)] + output: Option, + }, + List { + #[arg(short, long)] + dir: Option, + }, + Info { + hwid: PathBuf, + }, + Verify { + hwid: PathBuf, + }, + Test { + hwid: PathBuf, + }, +} + +#[cfg(feature = "hardware")] +#[derive(Parser)] +#[command(name = "rnid-rs hw")] +struct HwArgs { + #[command(subcommand)] + command: HwCommands, +} + +#[tokio::main(flavor = "multi_thread", worker_threads = 2)] +pub(crate) async fn main() -> ExitCode { + #[cfg(feature = "hardware")] + { + let mut raw = std::env::args_os(); + let _program = raw.next(); + if raw.next().as_deref() == Some(std::ffi::OsStr::new("hw")) { + let hw_args = HwArgs::parse_from(std::iter::once("rnid-rs hw".into()).chain(raw)); + hw_commands::run(hw_args.command); + return ExitCode::SUCCESS; + } + } + + let args = Args::parse(); + run(args).await +} + +async fn run(mut args: Args) -> ExitCode { + if args.version { + println!("rnid-rs {RETICULUM_COMPAT_VERSION}"); + return ExitCode::SUCCESS; + } + + let target_loglevel = 4 + args.verbose as i32 - args.quiet as i32; + let level = match target_loglevel { + i32::MIN..=1 => tracing::Level::ERROR, + 2..=3 => tracing::Level::WARN, + 4 => tracing::Level::INFO, + 5 => tracing::Level::DEBUG, + _ => tracing::Level::TRACE, + }; + let _ = tracing_subscriber::fmt() + .with_max_level(level) + .with_writer(std::io::stderr) + .try_init(); + + let op_count = [ + args.encrypt.is_some(), + args.decrypt.is_some(), + args.validate.is_some(), + args.sign.is_some(), + ] + .into_iter() + .filter(|op| *op) + .count(); + if op_count > 1 { + eprintln!( + "This utility currently only supports one of the encrypt, decrypt, sign or verify operations per invocation" + ); + return ExitCode::from(1); + } + + if args.read.is_none() { + args.read = args + .encrypt + .clone() + .or_else(|| args.decrypt.clone()) + .or_else(|| args.sign.clone()); + } + + if let Some(import_str) = args.import_str.as_deref() { + return import_identity(&args, import_str); + } + + if let Some(path) = args.generate.as_ref() { + return generate_identity(path, args.force); + } + + let Some(identity_arg) = args.identity.as_deref() else { + println!("\nNo identity provided, cannot continue\n"); + let mut cmd = Args::command(); + let _ = cmd.print_help(); + println!("\n"); + return ExitCode::from(2); + }; + + let identity = match resolve_identity(identity_arg, &args).await { + Ok(identity) => identity, + Err((code, msg)) => { + eprintln!("{msg}"); + return ExitCode::from(code); + } + }; + + if let Some(aspects) = args.hash.as_deref() { + return hash_destination(&identity, aspects); + } + + if let Some(aspects) = args.announce.as_deref() { + return announce_destination(&identity, aspects, &args).await; + } + + if args.print_identity { + print_identity(&identity, &args); + return ExitCode::SUCCESS; + } + + if args.export { + return export_identity(&identity, &args); + } + + if args.validate.is_some() { + return validate_signature(&identity, &args); + } + + if args.sign.is_some() { + return sign_file(&identity, &args); + } + + if args.encrypt.is_some() { + return encrypt_file(&identity, &args); + } + + if args.decrypt.is_some() { + return decrypt_file(&identity, &args); + } + + ExitCode::SUCCESS +} + +fn generate_identity(path: &Path, force: bool) -> ExitCode { + if let Err(e) = ensure_output_allowed(path, force) { + eprintln!("{e}"); + return ExitCode::from(3); + } + let identity = Identity::new(); + match identity.to_file(path) { + Ok(()) => { + println!( + "New identity {} written to {}", + hex::encode(identity.hash), + path.display() + ); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("An error occurred while saving the generated Identity: {e}"); + ExitCode::from(4) + } + } +} + +fn import_identity(args: &Args, import_str: &str) -> ExitCode { + let identity_bytes = match decode_key_text(import_str, args) { + Ok(bytes) => bytes, + Err(e) => { + eprintln!("Invalid identity data specified for import: {e}"); + return ExitCode::from(41); + } + }; + let identity = match Identity::from_private_key(&identity_bytes) { + Ok(identity) => identity, + Err(e) => { + eprintln!("Could not create Reticulum identity from specified data: {e}"); + return ExitCode::from(42); + } + }; + + println!("Identity imported"); + print_identity(&identity, args); + + if let Some(path) = args.write.as_ref() { + if path.is_file() && !args.force { + eprintln!("File {} already exists, not overwriting", path.display()); + return ExitCode::from(43); + } + if let Err(e) = identity.to_file(path) { + eprintln!("Error while saving identity to {}", path.display()); + eprintln!("The contained exception was: {e}"); + } + println!("Wrote imported identity to {}", path.display()); + } + + ExitCode::SUCCESS +} + +async fn resolve_identity(identity_arg: &str, args: &Args) -> Result { + let path = Path::new(identity_arg); + if path.is_file() { + // Python rnid calls `RNS.Identity.from_file()`, which returns None + // for malformed files. The CLI does not check that None before + // falling through with exit 0, so preserve that compatibility quirk. + return load_identity_file(path).map_err(|e| (0, e)); + } + + if identity_arg.len() == 32 { + let hash = parse_hash16(identity_arg) + .ok_or((7, "Invalid hexadecimal hash provided".to_string()))?; + match recall_identity_from_python_known_destinations(hash, args) { + Ok(Some(identity)) => { + println!("Recalled Identity {}", hex::encode(identity.hash)); + return Ok(identity); + } + Ok(None) => {} + Err(msg) => return Err((7, msg)), + } + if !args.request { + return Err(( + 5, + format!( + "Could not recall Identity for {}. You can query the network for unknown Identities with the -R option.", + hex::encode(hash) + ), + )); + } + return request_identity(hash, args).await; + } + + Err((8, "Specified Identity file not found".to_string())) +} + +fn load_identity_file(path: &Path) -> Result { + match Identity::from_file(path) { + Ok(identity) => Ok(identity), + Err(private_err) => { + let data = std::fs::read(path).map_err(|_| { + format!("Could not decode Identity from specified file: {private_err}") + })?; + Identity::from_public_key(&data).map_err(|public_err| { + format!( + "Could not decode Identity from specified file: {private_err}; public key: {public_err}" + ) + }) + } + } +} + +async fn request_identity(hash: [u8; 16], args: &Args) -> Result { + let shutdown = rns_runtime::lifecycle::ShutdownSignal::new(); + let foreground = Arc::new(AtomicBool::new(true)); + let handle = + rns_runtime::reticulum::init(args.config.as_deref(), None, shutdown.clone(), foreground) + .await + .map_err(|e| (1, format!("Failed to initialize Reticulum runtime: {e}")))?; + + handle + .transport_tx + .send(TransportMessage::RequestPath { + destination_hash: hash, + }) + .await + .map_err(|_| (1, "Transport closed while requesting path".to_string()))?; + + let timeout = Duration::from_secs_f64(args.timeout.max(0.0)); + let _ = handle.await_path(hash, timeout).await; + + let identity = query_recent_announces_for_hash(&handle, hash).await; + shutdown.trigger(); + identity.ok_or((6, "Identity request timed out".to_string())) +} + +async fn query_recent_announces_for_hash( + handle: &rns_runtime::reticulum::ReticulumHandle, + hash: [u8; 16], +) -> Option { + let response = handle + .query_transport(TransportQuery::GetRecentAnnounces) + .await?; + let TransportQueryResponse::Announces(announces) = response else { + return None; + }; + + for announce in announces { + let public_key = announce.public_key?; + if announce.dest_hash == hash { + return Identity::from_public_key(&public_key).ok(); + } + let identity_hash = rns_crypto::sha::truncated_hash(&public_key); + if identity_hash == hash { + return Identity::from_public_key(&public_key).ok(); + } + } + None +} + +fn recall_identity_from_python_known_destinations( + hash: [u8; 16], + args: &Args, +) -> Result, String> { + let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref()); + let path = config_dir.join("storage/known_destinations"); + let data = match std::fs::read(path) { + Ok(data) => data, + Err(_) => return Ok(None), + }; + let mut cursor = std::io::Cursor::new(data); + let value = match rmpv::decode::read_value(&mut cursor) { + Ok(value) => value, + Err(_) => return Ok(None), + }; + let rmpv::Value::Map(entries) = value else { + return Ok(None); + }; + + for (key, value) in entries { + let dest_hash = value_bytes(&key).and_then(hash16_from_slice); + let Some(items) = value.as_array() else { + continue; + }; + if items.len() < 3 { + continue; + } + let Some(public_key_vec) = value_bytes(&items[2]) else { + continue; + }; + let identity = match Identity::from_public_key(&public_key_vec) { + Ok(identity) => identity, + Err(e) if dest_hash == Some(hash) => { + return Err(format!("Invalid hexadecimal hash provided: {e}")); + } + Err(_) => continue, + }; + if dest_hash == Some(hash) || identity.hash == hash { + return Ok(Some(identity)); + } + } + Ok(None) +} + +fn value_bytes(value: &rmpv::Value) -> Option> { + match value { + rmpv::Value::Binary(bytes) => Some(bytes.clone()), + rmpv::Value::String(s) => s.as_str().map(|s| s.as_bytes().to_vec()), + _ => None, + } +} + +fn hash16_from_slice(bytes: Vec) -> Option<[u8; 16]> { + if bytes.len() != 16 { + return None; + } + let mut out = [0u8; 16]; + out.copy_from_slice(&bytes); + Some(out) +} + +fn hash_destination(identity: &Identity, aspects: &str) -> ExitCode { + if aspects.trim().is_empty() { + eprintln!("Invalid destination aspects specified"); + return ExitCode::from(32); + } + let hash = Destination::hash_from_name_and_identity(aspects, Some(&identity.hash)); + println!( + "The {aspects} destination for this Identity is {}", + pretty_hash(&hash) + ); + println!( + "The full destination specifier is {}.{}", + aspects, + hex::encode(identity.hash) + ); + ExitCode::SUCCESS +} + +async fn announce_destination(identity: &Identity, aspects: &str, args: &Args) -> ExitCode { + if aspects.split('.').count() <= 1 { + eprintln!("Invalid destination aspects specified"); + return ExitCode::from(32); + } + if !identity.has_private_key() { + let hash = Destination::hash_from_name_and_identity(aspects, Some(&identity.hash)); + println!( + "The {aspects} destination for this Identity is {}", + pretty_hash(&hash) + ); + println!( + "The full destination specifier is {}.{}", + aspects, + hex::encode(identity.hash) + ); + println!("Cannot announce this destination, since the private key is not held"); + return ExitCode::from(33); + } + + let shutdown = rns_runtime::lifecycle::ShutdownSignal::new(); + let foreground = Arc::new(AtomicBool::new(true)); + let handle = match rns_runtime::reticulum::init( + args.config.as_deref(), + None, + shutdown.clone(), + foreground, + ) + .await + { + Ok(handle) => handle, + Err(e) => { + eprintln!("Failed to initialize Reticulum runtime: {e}"); + return ExitCode::from(1); + } + }; + + let mut destination = + match Destination::new(Some(identity), Direction::In, DestType::Single, aspects) { + Ok(destination) => destination, + Err(e) => { + eprintln!("Could not create destination: {e}"); + shutdown.trigger(); + return ExitCode::from(1); + } + }; + println!("Created destination {aspects}"); + println!("Announcing destination {}", pretty_hash(&destination.hash)); + + let raw = match destination.announce_packet(identity, None, None, false, None, now_epoch()) { + Ok(raw) => raw, + Err(e) => { + eprintln!("An error occurred while attempting to send the announce: {e}"); + shutdown.trigger(); + return ExitCode::from(1); + } + }; + let dest_hash = destination.hash; + let _ = handle + .transport_tx + .send(TransportMessage::Outbound(OutboundRequest { + raw: raw.into(), + destination_hash: dest_hash, + })) + .await; + tokio::time::sleep(Duration::from_millis(250)).await; + shutdown.trigger(); + ExitCode::SUCCESS +} + +fn print_identity(identity: &Identity, args: &Args) { + println!( + "Public Key : {}", + encode_key_text(&identity.get_public_key(), args) + ); + if let Some(private_key) = identity.get_private_key() { + if args.print_private { + println!("Private Key : {}", encode_key_text(&*private_key, args)); + } else { + println!("Private Key : Hidden"); + } + } +} + +fn export_identity(identity: &Identity, args: &Args) -> ExitCode { + let Some(private_key) = identity.get_private_key() else { + eprintln!("Identity doesn't hold a private key, cannot export"); + return ExitCode::from(50); + }; + println!( + "Exported Identity : {}", + encode_key_text(&*private_key, args) + ); + ExitCode::SUCCESS +} + +fn sign_file(identity: &Identity, args: &Args) -> ExitCode { + if !identity.has_private_key() { + eprintln!("Specified Identity does not hold a private key. Cannot sign."); + return ExitCode::from(14); + } + let Some(input_path) = args.read.as_ref() else { + eprintln!("Signing requested, but no input data specified"); + return ExitCode::from(17); + }; + let data = match read_input(input_path, args.stdin) { + Ok(data) => data, + Err(e) => { + eprintln!("{e}"); + return ExitCode::from(12); + } + }; + let Some(output_path) = args + .write + .clone() + .or_else(|| (!args.stdout).then(|| append_extension(input_path, SIG_EXT))) + else { + if !args.stdout { + eprintln!("Signing requested, but no output specified"); + } + return ExitCode::from(18); + }; + if let Err(e) = ensure_output_allowed(&output_path, args.force) { + eprintln!("{e}"); + return ExitCode::from(15); + } + + let Some(signature) = identity.sign(&data) else { + eprintln!("Specified Identity does not hold a private key. Cannot sign."); + return ExitCode::from(16); + }; + if let Err(e) = write_output(&output_path, &signature, args.stdout) { + eprintln!("{e}"); + return ExitCode::from(18); + } + + if !args.stdout { + println!( + "File {} signed with {} to {}", + input_path.display(), + hex::encode(identity.hash), + output_path.display() + ); + } + ExitCode::SUCCESS +} + +fn validate_signature(identity: &Identity, args: &Args) -> ExitCode { + let Some(sig_path) = args.validate.as_ref() else { + return ExitCode::from(20); + }; + let input_path = args.read.clone().unwrap_or_else(|| { + let s = sig_path.to_string_lossy(); + if let Some(stripped) = s.strip_suffix(&format!(".{SIG_EXT}")) { + PathBuf::from(stripped) + } else { + sig_path.clone() + } + }); + + let sig_bytes = match std::fs::read(sig_path) { + Ok(data) => data, + Err(e) => { + eprintln!( + "An error occurred while opening {}: {e}", + sig_path.display() + ); + return ExitCode::from(10); + } + }; + let data = match read_input(&input_path, args.stdin) { + Ok(data) => data, + Err(e) => { + eprintln!("{e}"); + return ExitCode::from(11); + } + }; + if sig_bytes.len() != 64 { + eprintln!("Signature file {} is invalid", sig_path.display()); + return ExitCode::from(22); + } + let mut signature = [0u8; 64]; + signature.copy_from_slice(&sig_bytes); + if identity.verify(&data, &signature) { + println!( + "Signature {} for file {} made by Identity {} is valid", + sig_path.display(), + input_path.display(), + hex::encode(identity.hash) + ); + ExitCode::SUCCESS + } else { + eprintln!( + "Signature {} for file {} is invalid", + sig_path.display(), + input_path.display() + ); + ExitCode::from(22) + } +} + +fn encrypt_file(identity: &Identity, args: &Args) -> ExitCode { + let Some(input_path) = args.read.as_ref() else { + eprintln!("Encryption requested, but no input data specified"); + return ExitCode::from(24); + }; + let mut input: Box = match std::fs::File::open(input_path) { + Ok(file) => Box::new(file), + Err(e) => { + eprintln!("Input file {} not found: {e}", input_path.display()); + return ExitCode::from(12); + } + }; + let Some(output_path) = args + .write + .clone() + .or_else(|| (!args.stdout).then(|| append_extension(input_path, ENCRYPT_EXT))) + else { + if !args.stdout { + eprintln!("Encryption requested, but no output specified"); + } + return ExitCode::from(25); + }; + if let Err(e) = ensure_output_allowed(&output_path, args.force) { + eprintln!("{e}"); + return ExitCode::from(15); + }; + let mut output = match create_output(&output_path, args.stdout) { + Ok(file) => file, + Err(e) => { + eprintln!("{e}"); + return ExitCode::from(25); + } + }; + + let mut buffer = vec![0u8; PYTHON_COMPAT_PLAINTEXT_CHUNK_SIZE]; + loop { + let n = match input.read(&mut buffer) { + Ok(n) => n, + Err(e) => { + eprintln!("Could not read input file: {e}"); + return ExitCode::from(24); + } + }; + if n == 0 { + break; + } + let ciphertext = match identity.encrypt(&buffer[..n], None) { + Ok(ciphertext) => ciphertext, + Err(e) => { + eprintln!("An error occurred while encrypting data: {e}"); + return ExitCode::from(26); + } + }; + if let Err(e) = output.write_all(&ciphertext) { + eprintln!("Could not write encrypted output: {e}"); + return ExitCode::from(25); + } + } + + if !args.stdout { + println!( + "File {} encrypted for {} to {}", + input_path.display(), + hex::encode(identity.hash), + output_path.display() + ); + } + ExitCode::SUCCESS +} + +fn decrypt_file(identity: &Identity, args: &Args) -> ExitCode { + if !identity.has_private_key() { + eprintln!("Specified Identity does not hold a private key. Cannot decrypt."); + return ExitCode::from(27); + } + let Some(input_path) = args.read.as_ref() else { + eprintln!("Decryption requested, but no input data specified"); + return ExitCode::from(28); + }; + let ciphertext = match read_input(input_path, args.stdin) { + Ok(data) => data, + Err(e) => { + eprintln!("{e}"); + return ExitCode::from(28); + } + }; + let Some(output_path) = args.write.clone().or_else(|| { + if args.stdout { + None + } else { + default_decrypt_output_path(input_path) + } + }) else { + if !args.stdout { + eprintln!("Decryption requested, but no output specified"); + } + return ExitCode::from(29); + }; + if let Err(e) = ensure_output_allowed(&output_path, args.force) { + eprintln!("{e}"); + return ExitCode::from(15); + } + + let plaintext = match decrypt_ciphertext(identity, &ciphertext) { + Ok(plaintext) => plaintext, + Err(()) => { + eprintln!("Data could not be decrypted with the specified Identity"); + return ExitCode::from(30); + } + }; + + if let Err(e) = write_output(&output_path, &plaintext, args.stdout) { + eprintln!("{e}"); + return ExitCode::from(29); + } + if !args.stdout { + println!( + "File {} decrypted with {} to {}", + input_path.display(), + hex::encode(identity.hash), + output_path.display() + ); + } + ExitCode::SUCCESS +} + +fn decrypt_ciphertext(identity: &Identity, ciphertext: &[u8]) -> Result, ()> { + if ciphertext.is_empty() { + return Ok(Vec::new()); + } + + if let Ok(plaintext) = identity.decrypt(ciphertext, None, false) { + return Ok(plaintext); + } + + if ciphertext.len() > CHUNK_SIZE { + if let Ok(plaintext) = + decrypt_ciphertext_chunks(identity, ciphertext, FULL_CHUNK_TOKEN_SIZE) + { + return Ok(plaintext); + } + if let Ok(plaintext) = decrypt_ciphertext_chunks(identity, ciphertext, CHUNK_SIZE) { + return Ok(plaintext); + } + } + + Err(()) +} + +fn decrypt_ciphertext_chunks( + identity: &Identity, + ciphertext: &[u8], + chunk_size: usize, +) -> Result, ()> { + let mut plaintext = Vec::new(); + let mut pos = 0usize; + while pos < ciphertext.len() { + let end = (pos + chunk_size).min(ciphertext.len()); + let chunk = identity + .decrypt(&ciphertext[pos..end], None, false) + .map_err(|_| ())?; + plaintext.extend_from_slice(&chunk); + pos = end; + } + Ok(plaintext) +} + +fn read_input(path: &Path, _use_stdin: bool) -> Result, String> { + std::fs::read(path).map_err(|e| format!("Input file {} not found: {e}", path.display())) +} + +fn create_output(path: &Path, _use_stdout: bool) -> Result, String> { + let file = std::fs::File::create(path).map_err(|e| { + format!( + "Could not open output file {} for writing: {e}", + path.display() + ) + })?; + Ok(Box::new(file)) +} + +fn write_output(path: &Path, data: &[u8], use_stdout: bool) -> Result<(), String> { + let mut output = create_output(path, use_stdout)?; + output + .write_all(data) + .map_err(|e| format!("Could not write output: {e}")) +} + +fn ensure_output_allowed(path: &Path, force: bool) -> Result<(), String> { + if path.exists() && !force { + return Err(format!( + "Output file {} already exists. Not overwriting.", + path.display() + )); + } + Ok(()) +} + +fn append_extension(path: &Path, ext: &str) -> PathBuf { + PathBuf::from(format!("{}.{}", path.to_string_lossy(), ext)) +} + +fn default_decrypt_output_path(path: &Path) -> Option { + let s = path.to_string_lossy(); + if s.to_lowercase().ends_with(&format!(".{ENCRYPT_EXT}")) { + Some(PathBuf::from(s.replace(&format!(".{ENCRYPT_EXT}"), ""))) + } else { + None + } +} + +fn parse_hash16(s: &str) -> Option<[u8; 16]> { + if s.len() != 32 { + return None; + } + let bytes = hex::decode(s).ok()?; + hash16_from_slice(bytes) +} + +fn decode_key_text(input: &str, args: &Args) -> Result, String> { + if args.base64 { + URL_SAFE.decode(input).map_err(|e| e.to_string()) + } else if args.base32 { + decode_base32(input) + } else { + hex::decode(input).map_err(|e| e.to_string()) + } +} + +fn encode_key_text(bytes: &[u8], args: &Args) -> String { + if args.base64 { + URL_SAFE.encode(bytes) + } else if args.base32 { + encode_base32(bytes) + } else { + hex::encode(bytes) + } +} + +fn encode_base32(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + let mut out = String::new(); + let mut buffer = 0u16; + let mut bits = 0u8; + for byte in bytes { + buffer = (buffer << 8) | (*byte as u16); + bits += 8; + while bits >= 5 { + let index = ((buffer >> (bits - 5)) & 0x1f) as usize; + out.push(ALPHABET[index] as char); + bits -= 5; + } + } + if bits > 0 { + let index = ((buffer << (5 - bits)) & 0x1f) as usize; + out.push(ALPHABET[index] as char); + } + while !out.len().is_multiple_of(8) { + out.push('='); + } + out +} + +fn decode_base32(input: &str) -> Result, String> { + let mut out = Vec::new(); + let mut buffer = 0u32; + let mut bits = 0u8; + for ch in input.chars() { + if ch == '=' { + break; + } + let val = match ch { + 'A'..='Z' => ch as u8 - b'A', + 'a'..='z' => ch as u8 - b'a', + '2'..='7' => ch as u8 - b'2' + 26, + c if c.is_whitespace() => continue, + _ => return Err(format!("invalid base32 character {ch:?}")), + }; + buffer = (buffer << 5) | u32::from(val); + bits += 5; + while bits >= 8 { + out.push(((buffer >> (bits - 8)) & 0xff) as u8); + bits -= 8; + } + } + Ok(out) +} + +fn pretty_hash(hash: &[u8; 16]) -> String { + format!("<{}>", hex::encode(hash)) +} + +fn now_epoch() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0) +} diff --git a/crates/rns-tools/src/commands/rnodeconf.rs b/crates/rns-tools/src/commands/rnodeconf.rs new file mode 100644 index 0000000..9e44b45 --- /dev/null +++ b/crates/rns-tools/src/commands/rnodeconf.rs @@ -0,0 +1,1061 @@ +//! rnodeconf-rs - RNode configuration and firmware utility. +//! +//! The safe inspection/configuration paths are implemented first. Firmware +//! flashing, ROM bootstrap, and full signing-key management remain +//! hardware-gated work. + +use std::fs; +use std::io::Write; +use std::net::Ipv4Addr; +use std::path::PathBuf; +use std::process::ExitCode; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use clap::{CommandFactory, Parser}; +use rns_interface::{kiss, rnode, rnode_admin}; + +// rnodeconf support is staged: safe inspection/config modules are compiled now, +// while hardware-gated flashing/signing paths are wired in behind explicit CLI flows. +#[allow(dead_code)] +#[path = "rnodeconf/eeprom.rs"] +mod eeprom; +#[allow(dead_code)] +#[path = "rnodeconf/firmware.rs"] +mod firmware; +#[allow(dead_code)] +#[path = "rnodeconf/flash.rs"] +mod flash; +#[allow(dead_code)] +#[path = "rnodeconf/model.rs"] +mod model; +#[allow(dead_code)] +#[path = "rnodeconf/trust.rs"] +mod trust; + +const RNODECONF_VERSION: &str = "2.5.0"; + +#[derive(Parser, Debug)] +#[command( + name = "rnodeconf-rs", + about = "RNode Configuration and firmware utility", + disable_version_flag = true +)] +struct Args { + #[arg(short = 'i', long)] + info: bool, + #[arg(short = 'a', long)] + autoinstall: bool, + #[arg(short = 'u', long)] + update: bool, + #[arg(short = 'U', long = "force-update")] + force_update: bool, + #[arg(long = "fw-version")] + fw_version: Option, + #[arg(long = "fw-url")] + fw_url: Option, + #[arg(long)] + nocheck: bool, + #[arg(short = 'e', long)] + extract: bool, + #[arg(short = 'E', long = "use-extracted")] + use_extracted: bool, + #[arg(short = 'C', long = "clear-cache")] + clear_cache: bool, + #[arg(long = "baud-flash", default_value = "921600")] + baud_flash: String, + + #[arg(short = 'N', long)] + normal: bool, + #[arg(short = 'T', long)] + tnc: bool, + + #[arg(short = 'b', long = "bluetooth-on")] + bluetooth_on: bool, + #[arg(short = 'B', long = "bluetooth-off")] + bluetooth_off: bool, + #[arg(short = 'p', long = "bluetooth-pair")] + bluetooth_pair: bool, + + #[arg(short = 'w', long = "wifi")] + wifi: Option, + #[arg(long)] + channel: Option, + #[arg(long)] + ssid: Option, + #[arg(long)] + psk: Option, + #[arg(long = "show-psk")] + show_psk: bool, + #[arg(long)] + ip: Option, + #[arg(long)] + nm: Option, + + #[arg(short = 'D', long = "display")] + display: Option, + #[arg(short = 't', long = "timeout")] + timeout: Option, + #[arg(short = 'R', long = "rotation")] + rotation: Option, + #[arg(long = "display-addr")] + display_addr: Option, + #[arg(long = "recondition-display")] + recondition_display: bool, + #[arg(long = "np")] + neopixel: Option, + + #[arg(long = "freq")] + freq: Option, + #[arg(long = "bw")] + bandwidth: Option, + #[arg(long = "txp")] + tx_power: Option, + #[arg(long = "sf")] + spreading_factor: Option, + #[arg(long = "cr")] + coding_rate: Option, + + #[arg(short = 'x', long = "ia-enable")] + ia_enable: bool, + #[arg(short = 'X', long = "ia-disable")] + ia_disable: bool, + + #[arg(short = 'c', long = "config")] + config: bool, + #[arg(long = "eeprom-backup")] + eeprom_backup: bool, + #[arg(long = "eeprom-dump")] + eeprom_dump: bool, + #[arg(long = "eeprom-wipe")] + eeprom_wipe: bool, + + #[arg(short = 'P', long = "public")] + public: bool, + #[arg(long = "trust-key")] + trust_key: Option, + + #[arg(long)] + version: bool, + #[arg(short = 'f', long)] + flash: bool, + #[arg(short = 'r', long)] + rom: bool, + #[arg(short = 'k', long)] + key: bool, + #[arg(short = 'S', long)] + sign: bool, + #[arg(short = 'H', long = "firmware-hash")] + firmware_hash: Option, + #[arg(short = 'K', long = "get-target-firmware-hash", hide = true)] + get_target_firmware_hash: bool, + #[arg(short = 'L', long = "get-firmware-hash", hide = true)] + get_firmware_hash: bool, + #[arg(long)] + platform: Option, + #[arg(long)] + product: Option, + #[arg(long)] + model: Option, + #[arg(long)] + hwrev: Option, + + /// Serial port where RNode is attached. + port: Option, +} + +pub(crate) fn main() -> ExitCode { + let args = Args::parse(); + if args.version { + println!("rnodeconf-rs {RNODECONF_VERSION}"); + return ExitCode::SUCCESS; + } + if let Some(trust_key) = args.trust_key.as_deref() { + let paths = match rnodeconf_cache_paths() { + Ok(paths) => paths, + Err(e) => { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(2); + } + }; + match store_trusted_key(trust_key, &paths) { + Ok(path) => { + println!("Trusted key written to: {}", path.display()); + return ExitCode::SUCCESS; + } + Err(e) => { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(2); + } + } + } + if args.key || args.sign || args.public { + eprintln!("rnodeconf-rs: signing key management is not fully implemented yet"); + return ExitCode::from(2); + } + if args.flash || args.rom || args.autoinstall || args.update || args.force_update { + eprintln!("rnodeconf-rs: firmware flashing is not implemented yet"); + return ExitCode::from(2); + } + if args.extract + || args.use_extracted + || args.fw_version.is_some() + || args.fw_url.is_some() + || args.nocheck + || args.platform.is_some() + || args.product.is_some() + || args.model.is_some() + || args.hwrev.is_some() + || args.baud_flash != "921600" + { + eprintln!( + "rnodeconf-rs: firmware planning/cache options are not implemented yet; flashing and update flows remain disabled" + ); + return ExitCode::from(2); + } + if args.eeprom_wipe { + eprintln!( + "rnodeconf-rs: --eeprom-wipe is destructive and is disabled until the full provisioning flow is implemented" + ); + return ExitCode::from(2); + } + if let Some(hash) = args.firmware_hash.as_deref() { + if let Err(e) = firmware::parse_sha256_hex(hash) { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(2); + } + eprintln!( + "rnodeconf-rs: --firmware-hash writes device trust state and is disabled until signing/provisioning is implemented" + ); + return ExitCode::from(2); + } + if args.clear_cache { + let paths = match rnodeconf_cache_paths() { + Ok(paths) => paths, + Err(e) => { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(2); + } + }; + if let Err(e) = clear_firmware_cache(&paths) { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(1); + } + println!("Firmware cache cleared."); + return ExitCode::SUCCESS; + } + + let actions = match build_actions(&args) { + Ok(actions) => actions, + Err(e) => { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(2); + } + }; + if actions.is_empty() { + let mut cmd = Args::command(); + let _ = cmd.print_help(); + println!(); + return ExitCode::SUCCESS; + } + + let cache_paths = if args.eeprom_backup { + match rnodeconf_cache_paths() { + Ok(paths) => Some(paths), + Err(e) => { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(2); + } + } + } else { + None + }; + + let Some(port_path) = args.port.as_ref() else { + eprintln!("rnodeconf-rs: serial port is required for device operations"); + return ExitCode::from(2); + }; + + let mut port = match serialport::new(port_path.to_string_lossy(), 115200) + .timeout(Duration::from_millis(250)) + .open() + { + Ok(port) => port, + Err(e) => { + eprintln!("rnodeconf-rs: could not open {}: {e}", port_path.display()); + return ExitCode::from(1); + } + }; + + for frame in actions { + let raw = rnode_admin::encode_frame(frame.command, &frame.payload); + if let Err(e) = port.write_all(&raw).and_then(|_| port.flush()) { + eprintln!("rnodeconf-rs: serial write failed: {e}"); + return ExitCode::from(1); + } + } + + let responses = read_responses(&mut *port, Duration::from_millis(750)); + if let Err(e) = print_responses(&responses, &args, cache_paths.as_ref()) { + eprintln!("rnodeconf-rs: {e}"); + return ExitCode::from(1); + } + ExitCode::SUCCESS +} + +fn build_actions(args: &Args) -> Result, String> { + let mut actions = Vec::new(); + + if args.info { + actions.extend(rnode_admin::detect_sequence()); + actions.push(rnode_admin::eeprom_read_frame()); + } + if args.normal { + actions.push(frame(rnode::CMD_CONF_DELETE, &[0])); + } + if args.tnc { + actions.push(frame(rnode::CMD_CONF_SAVE, &[0])); + } + if args.bluetooth_on { + actions.push(frame(rnode::CMD_BT_CTRL, &[1])); + } + if args.bluetooth_off { + actions.push(frame(rnode::CMD_BT_CTRL, &[0])); + } + if args.bluetooth_pair { + actions.push(frame(rnode::CMD_BT_CTRL, &[2])); + } + + if let Some(mode) = args.wifi.as_deref() { + let mode = match mode.to_ascii_lowercase().as_str() { + "off" | "none" => rnode_admin::WifiMode::Off, + "station" | "sta" => rnode_admin::WifiMode::Station, + "ap" | "accesspoint" | "access_point" => rnode_admin::WifiMode::AccessPoint, + _ => return Err("WiFi mode must be OFF, AP or STATION".to_string()), + }; + actions.push(frame(rnode::CMD_WIFI_MODE, &mode.payload())); + } + if let Some(channel) = args.channel { + actions.push(frame(rnode::CMD_WIFI_CHN, &[channel])); + } + if let Some(ssid) = args.ssid.as_deref() { + actions.push(frame( + rnode::CMD_WIFI_SSID, + &rnode_admin::nullable_string_payload(non_none_value(ssid)), + )); + } + if let Some(psk) = args.psk.as_deref() { + actions.push(frame( + rnode::CMD_WIFI_PSK, + &rnode_admin::nullable_string_payload(non_none_value(psk)), + )); + } + if args.show_psk { + actions.push(frame(rnode::CMD_WIFI_PSK, &[0xFF])); + } + if let Some(ip) = args.ip.as_deref() { + let payload = optional_ipv4_payload(ip)?; + actions.push(frame(rnode::CMD_WIFI_IP, &payload)); + } + if let Some(nm) = args.nm.as_deref() { + let payload = optional_ipv4_payload(nm)?; + actions.push(frame(rnode::CMD_WIFI_NM, &payload)); + } + + if let Some(intensity) = args.display { + actions.push(frame(rnode::CMD_DISP_INT, &[clamp_u8(intensity, 255)])); + } + if let Some(timeout) = args.timeout { + actions.push(frame(rnode::CMD_DISP_BLNK, &[clamp_u8(timeout, 255)])); + } + if let Some(rotation) = args.rotation { + actions.push(frame(rnode::CMD_DISP_ROT, &[clamp_u8(rotation, 3)])); + } + if let Some(addr) = args.display_addr.as_deref() { + let addr = u8::from_str_radix(addr.trim_start_matches("0x"), 16) + .map_err(|e| format!("invalid display address: {e}"))?; + actions.push(frame(rnode::CMD_DISP_ADR, &[addr])); + } + if args.recondition_display { + actions.push(frame(rnode::CMD_DISP_RCND, &[1])); + } + if let Some(intensity) = args.neopixel { + actions.push(frame(rnode::CMD_NP_INT, &[clamp_u8(intensity, 255)])); + } + + if let Some(freq) = args.freq { + actions.push(frame(rnode::CMD_FREQUENCY, &freq.to_be_bytes())); + } + if let Some(bw) = args.bandwidth { + actions.push(frame(rnode::CMD_BANDWIDTH, &bw.to_be_bytes())); + } + if let Some(txp) = args.tx_power { + actions.push(frame(rnode::CMD_TXPOWER, &[txp])); + } + if let Some(sf) = args.spreading_factor { + actions.push(frame(rnode::CMD_SF, &[sf])); + } + if let Some(cr) = args.coding_rate { + actions.push(frame(rnode::CMD_CR, &[cr])); + } + if args.ia_enable { + actions.push(frame(rnode::CMD_DIS_IA, &[0])); + } + if args.ia_disable { + actions.push(frame(rnode::CMD_DIS_IA, &[1])); + } + + if args.config { + actions.push(frame(rnode::CMD_CFG_READ, &[0])); + } + if args.eeprom_dump || args.eeprom_backup { + actions.push(rnode_admin::eeprom_read_frame()); + } + if args.eeprom_wipe { + actions.push(rnode_admin::eeprom_wipe_frame()); + } + if let Some(hash) = args.firmware_hash.as_deref() { + let hash = firmware::parse_sha256_hex(hash)?; + actions.push(trust::firmware_hash_frame(&hash)); + } + if args.get_target_firmware_hash { + actions.push(frame(rnode::CMD_HASHES, &[1])); + } + if args.get_firmware_hash { + actions.push(frame(rnode::CMD_HASHES, &[2])); + } + + Ok(actions) +} + +fn frame(command: u8, payload: &[u8]) -> rnode_admin::AdminFrame { + rnode_admin::AdminFrame { + command, + payload: payload.to_vec(), + } +} + +fn non_none_value(value: &str) -> Option<&str> { + (!value.eq_ignore_ascii_case("none")).then_some(value) +} + +fn optional_ipv4_payload(value: &str) -> Result, String> { + if value.eq_ignore_ascii_case("none") { + return Ok(vec![0, 0, 0, 0]); + } + let addr: Ipv4Addr = value + .parse() + .map_err(|e| format!("invalid IPv4 address {value}: {e}"))?; + Ok(rnode_admin::ipv4_payload(addr).to_vec()) +} + +fn clamp_u8(value: i32, max: u8) -> u8 { + value.clamp(0, i32::from(max)) as u8 +} + +fn read_responses( + port: &mut dyn serialport::SerialPort, + total_timeout: Duration, +) -> Vec { + let mut frames = Vec::new(); + let mut deframer = kiss::RawKissDeframer::new(); + let mut buf = [0u8; 512]; + let deadline = Instant::now() + total_timeout; + while Instant::now() < deadline { + match port.read(&mut buf) { + Ok(n) if n > 0 => frames.extend( + deframer + .feed(&buf[..n]) + .into_iter() + .map(|(command, payload)| rnode_admin::AdminFrame { command, payload }), + ), + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {} + Err(_) => break, + } + } + frames +} + +fn print_responses( + frames: &[rnode_admin::AdminFrame], + args: &Args, + cache_paths: Option<&firmware::CachePaths>, +) -> Result<(), String> { + for frame in frames { + match frame.command { + rnode::CMD_BT_PIN => { + if let Some(pin) = rnode_admin::parse_bt_pin(frame) { + println!("Bluetooth pairing PIN: {pin:06}"); + } + } + rnode::CMD_FW_VERSION if frame.payload.len() >= 2 => { + println!( + "Firmware version: {}.{}", + frame.payload[0], frame.payload[1] + ); + } + rnode::CMD_PLATFORM => println!("Platform: {}", hex::encode(&frame.payload)), + rnode::CMD_MCU => println!("MCU: {}", hex::encode(&frame.payload)), + rnode::CMD_BOARD => println!("Board: {}", hex::encode(&frame.payload)), + rnode::CMD_DEV_HASH => println!("Device hash: {}", hex::encode(&frame.payload)), + rnode::CMD_HASHES => println!("Firmware hash: {}", hex::encode(&frame.payload)), + rnode::CMD_CFG_READ => { + println!("Config sector: {}", hex::encode(&frame.payload)); + } + rnode::CMD_ROM_READ => { + if args.eeprom_dump { + println!("EEPROM contents: {}", hex::encode(&frame.payload)); + } + match eeprom::EepromImage::new(frame.payload.clone()) { + Ok(image) => { + for line in eeprom_summary_lines(&image) { + println!("{line}"); + } + } + Err(e) => println!("EEPROM: {e}"), + } + if args.eeprom_backup { + let Some(paths) = cache_paths else { + return Err("EEPROM backup requested without cache paths".to_string()); + }; + let path = write_eeprom_backup(paths, &frame.payload)?; + println!("EEPROM backup written to: {}", path.display()); + } + } + _ => println!("0x{:02x}: {}", frame.command, hex::encode(&frame.payload)), + } + } + Ok(()) +} + +fn eeprom_summary_lines(image: &eeprom::EepromImage) -> Vec { + if !image.info_locked() { + return vec!["EEPROM: not provisioned or info lock missing".to_string()]; + } + + let identity = image.identity(); + let product = model::product_name(identity.product).unwrap_or("Unknown product"); + let model_info = model::model_info(identity.model); + let model_label = model_info + .map(|info| info.band_label) + .unwrap_or("unknown band"); + let radio_label = model_info.map(|info| info.radio).unwrap_or("unknown radio"); + let checksum_status = if image.checksum_valid() { + "valid" + } else { + "invalid" + }; + + let mut lines = vec![ + "EEPROM: provisioned".to_string(), + format!(" Product: {product} (0x{:02x})", identity.product), + format!( + " Model: 0x{:02x} ({model_label}, {radio_label})", + identity.model + ), + format!(" Hardware revision: {}", identity.hw_rev), + format!(" Serial: {}", hex::encode(identity.serial.to_be_bytes())), + format!(" Manufactured: {}", identity.made), + format!(" Identity checksum: {checksum_status}"), + ]; + + if let Some(radio) = image.radio_config() { + let bitrate = + rnode::calculate_bitrate(radio.spreading_factor, radio.coding_rate, radio.bandwidth); + lines.extend([ + " Startup mode: TNC".to_string(), + format!(" Frequency: {} Hz", radio.frequency), + format!(" Bandwidth: {} Hz", radio.bandwidth), + format!(" TX power: {} dBm", radio.tx_power), + format!(" Spreading factor: {}", radio.spreading_factor), + format!(" Coding rate: {}", radio.coding_rate), + format!(" On-air bitrate: {bitrate} bps"), + ]); + } else { + lines.push(" Startup mode: Normal (host-controlled)".to_string()); + } + + lines +} + +fn rnodeconf_cache_paths() -> Result { + Ok(firmware::CachePaths::new(rnodeconf_root()?)) +} + +fn rnodeconf_root() -> Result { + if cfg!(windows) { + std::env::var_os("APPDATA") + .map(PathBuf::from) + .map(|path| path.join("rnodeconf")) + .ok_or_else(|| "APPDATA is not set; cannot locate rnodeconf data directory".to_string()) + } else { + std::env::var_os("HOME") + .map(PathBuf::from) + .map(|path| path.join(".config").join("rnodeconf")) + .ok_or_else(|| "HOME is not set; cannot locate rnodeconf data directory".to_string()) + } +} + +fn store_trusted_key(trust_key_hex: &str, paths: &firmware::CachePaths) -> Result { + let public_key = + hex::decode(trust_key_hex).map_err(|e| format!("invalid trust key hex: {e}"))?; + if public_key.is_empty() { + return Err("trusted public key cannot be empty".to_string()); + } + trust::write_trusted_key(&paths.root, &public_key) + .map_err(|e| format!("could not write trusted key: {e}")) +} + +fn clear_firmware_cache(paths: &firmware::CachePaths) -> Result<(), String> { + for dir in [&paths.update, &paths.extracted] { + match fs::remove_dir_all(dir) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("could not clear {}: {e}", dir.display())), + } + fs::create_dir_all(dir) + .map_err(|e| format!("could not recreate {}: {e}", dir.display()))?; + } + Ok(()) +} + +fn write_eeprom_backup(paths: &firmware::CachePaths, bytes: &[u8]) -> Result { + fs::create_dir_all(&paths.eeprom) + .map_err(|e| format!("could not create {}: {e}", paths.eeprom.display()))?; + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|e| format!("system clock before Unix epoch: {e}"))? + .as_secs(); + let path = paths.eeprom.join(format!("{timestamp}.eeprom")); + fs::write(&path, bytes).map_err(|e| format!("could not write {}: {e}", path.display()))?; + Ok(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct FakeRNode { + eeprom: Vec, + config_dump: Vec, + device_hash: [u8; 32], + target_firmware_hash: [u8; 32], + firmware_hash: [u8; 32], + accepted_firmware_hash: Option<[u8; 32]>, + accepted_device_signature: Option<[u8; 64]>, + } + + impl FakeRNode { + fn new() -> Self { + Self { + eeprom: (0..eeprom::EEPROM_SIZE).map(|i| i as u8).collect(), + config_dump: vec![0x73, 0x01, 0x02, 0x03], + device_hash: [0xA5; 32], + target_firmware_hash: [0x11; 32], + firmware_hash: [0x22; 32], + accepted_firmware_hash: None, + accepted_device_signature: None, + } + } + + fn transact( + &mut self, + raw: &[u8], + ) -> (Vec, Vec) { + let requests = rnode_admin::decode_frames(raw); + let responses = requests + .iter() + .filter_map(|request| self.apply(request)) + .collect(); + (requests, responses) + } + + fn apply(&mut self, request: &rnode_admin::AdminFrame) -> Option { + match request.command { + rnode::CMD_DETECT if request.payload == [rnode::DETECT_REQ] => { + Some(frame(rnode::CMD_DETECT, &[rnode::DETECT_RESP])) + } + rnode::CMD_FW_VERSION => Some(frame(rnode::CMD_FW_VERSION, &[1, 74])), + rnode::CMD_PLATFORM => Some(frame(rnode::CMD_PLATFORM, &[model::PLATFORM_ESP32])), + rnode::CMD_MCU => Some(frame(rnode::CMD_MCU, &[model::MCU_ESP32])), + rnode::CMD_BOARD => Some(frame(rnode::CMD_BOARD, &[0x01])), + rnode::CMD_DEV_HASH => Some(frame(rnode::CMD_DEV_HASH, &self.device_hash)), + rnode::CMD_HASHES => match request.payload.first().copied() { + Some(1) => Some(frame(rnode::CMD_HASHES, &self.target_firmware_hash)), + Some(2) => Some(frame(rnode::CMD_HASHES, &self.firmware_hash)), + _ => Some(frame(rnode::CMD_HASHES, &[0x00])), + }, + rnode::CMD_CFG_READ => Some(frame(rnode::CMD_CFG_READ, &self.config_dump)), + rnode::CMD_ROM_READ => Some(frame(rnode::CMD_ROM_READ, &self.eeprom)), + rnode::CMD_ROM_WRITE if request.payload.len() == 2 => { + let address = request.payload[0] as usize; + if let Some(cell) = self.eeprom.get_mut(address) { + *cell = request.payload[1]; + } + Some(frame(rnode::CMD_ROM_WRITE, &request.payload)) + } + rnode::CMD_ROM_WIPE => { + self.eeprom.fill(0xFF); + Some(frame(rnode::CMD_ROM_WIPE, &[0xF8])) + } + rnode::CMD_BT_CTRL if request.payload == [2] => { + Some(frame(rnode::CMD_BT_PIN, &123456u32.to_be_bytes())) + } + rnode::CMD_FW_HASH if request.payload.len() == 32 => { + let mut hash = [0u8; 32]; + hash.copy_from_slice(&request.payload); + self.accepted_firmware_hash = Some(hash); + Some(frame(rnode::CMD_FW_HASH, &request.payload)) + } + rnode::CMD_DEV_SIG if request.payload.len() == 64 => { + let mut signature = [0u8; 64]; + signature.copy_from_slice(&request.payload); + self.accepted_device_signature = Some(signature); + Some(frame(rnode::CMD_DEV_SIG, &request.payload)) + } + _ => Some(frame(request.command, &request.payload)), + } + } + } + + fn commands(args: &[&str]) -> Vec { + let args = Args::parse_from(std::iter::once("rnodeconf").chain(args.iter().copied())); + build_actions(&args) + .unwrap() + .into_iter() + .map(|f| f.command) + .collect() + } + + fn actions(args: &[&str]) -> Vec { + let args = Args::parse_from(std::iter::once("rnodeconf").chain(args.iter().copied())); + build_actions(&args).unwrap() + } + + fn encode_actions(actions: &[rnode_admin::AdminFrame]) -> Vec { + let mut raw = Vec::new(); + for action in actions { + raw.extend_from_slice(&rnode_admin::encode_frame(action.command, &action.payload)); + } + raw + } + + fn assert_has_frame(frames: &[rnode_admin::AdminFrame], command: u8, payload: &[u8]) { + assert!( + frames + .iter() + .any(|frame| frame.command == command && frame.payload == payload), + "missing command 0x{command:02x} with payload {} in {frames:?}", + hex::encode(payload) + ); + } + + #[test] + fn info_sequence_matches_upstream_probe_order() { + assert_eq!( + commands(&["--info", "fake"]), + vec![ + rnode::CMD_DETECT, + rnode::CMD_FW_VERSION, + rnode::CMD_PLATFORM, + rnode::CMD_MCU, + rnode::CMD_BOARD, + rnode::CMD_DEV_HASH, + rnode::CMD_HASHES, + rnode::CMD_HASHES, + rnode::CMD_ROM_READ, + ] + ); + } + + #[test] + fn wifi_and_bluetooth_actions_use_extended_commands() { + let args = Args::parse_from([ + "rnodeconf", + "--bluetooth-pair", + "--wifi", + "AP", + "--ssid", + "RNode", + "--psk", + "secret", + "--ip", + "192.168.1.10", + "--nm", + "255.255.255.0", + "fake", + ]); + let frames = build_actions(&args).unwrap(); + assert_eq!(frames[0].command, rnode::CMD_BT_CTRL); + assert_eq!(frames[0].payload, vec![2]); + assert!(frames.iter().any(|f| f.command == rnode::CMD_WIFI_IP)); + assert!(frames.iter().any(|f| f.command == rnode::CMD_WIFI_NM)); + } + + #[test] + fn info_sequence_round_trips_against_fake_rnode() { + let actions = actions(&["--info", "fake"]); + let mut fake = FakeRNode::new(); + let (requests, responses) = fake.transact(&encode_actions(&actions)); + + assert_eq!(requests, actions); + assert_eq!( + responses + .iter() + .map(|frame| frame.command) + .collect::>(), + vec![ + rnode::CMD_DETECT, + rnode::CMD_FW_VERSION, + rnode::CMD_PLATFORM, + rnode::CMD_MCU, + rnode::CMD_BOARD, + rnode::CMD_DEV_HASH, + rnode::CMD_HASHES, + rnode::CMD_HASHES, + rnode::CMD_ROM_READ, + ] + ); + assert_has_frame(&responses, rnode::CMD_DETECT, &[rnode::DETECT_RESP]); + assert_has_frame(&responses, rnode::CMD_FW_VERSION, &[1, 74]); + assert_has_frame(&responses, rnode::CMD_PLATFORM, &[model::PLATFORM_ESP32]); + assert_has_frame(&responses, rnode::CMD_MCU, &[model::MCU_ESP32]); + assert_has_frame(&responses, rnode::CMD_ROM_READ, &FakeRNode::new().eeprom); + } + + #[test] + fn config_dump_and_eeprom_read_wipe_round_trip_against_fake_rnode() { + let actions = actions(&["--config", "--eeprom-dump", "--eeprom-wipe", "fake"]); + let original_eeprom = FakeRNode::new().eeprom; + let mut fake = FakeRNode::new(); + let (requests, responses) = fake.transact(&encode_actions(&actions)); + + assert_eq!( + requests + .iter() + .map(|frame| frame.command) + .collect::>(), + vec![ + rnode::CMD_CFG_READ, + rnode::CMD_ROM_READ, + rnode::CMD_ROM_WIPE + ] + ); + assert_has_frame(&responses, rnode::CMD_CFG_READ, &[0x73, 0x01, 0x02, 0x03]); + assert_has_frame(&responses, rnode::CMD_ROM_READ, &original_eeprom); + assert_has_frame(&responses, rnode::CMD_ROM_WIPE, &[0xF8]); + assert!(fake.eeprom.iter().all(|byte| *byte == 0xFF)); + } + + #[test] + fn eeprom_write_frames_mutate_fake_rnode_memory() { + let info = eeprom::IdentityInfo { + product: model::PRODUCT_RNODE, + model: model::MODEL_B4_TCXO, + hw_rev: 3, + serial: 0x01020304, + made: 0x6553F100, + }; + let mut writes = eeprom::identity_write_frames(&info); + writes.extend(eeprom::radio_config_write_frames(&eeprom::RadioConfig { + spreading_factor: 7, + coding_rate: 5, + tx_power: 14, + bandwidth: 125000, + frequency: 868000000, + })); + + let mut fake = FakeRNode::new(); + let (requests, responses) = fake.transact(&encode_actions(&writes)); + + assert_eq!(requests, writes); + assert_eq!(responses.len(), writes.len()); + assert_eq!(fake.eeprom[eeprom::ADDR_PRODUCT], model::PRODUCT_RNODE); + assert_eq!(fake.eeprom[eeprom::ADDR_MODEL], 0xB4); + assert_eq!(fake.eeprom[eeprom::ADDR_HW_REV], 3); + assert_eq!( + &fake.eeprom[eeprom::ADDR_SERIAL..eeprom::ADDR_SERIAL + 4], + &0x01020304u32.to_be_bytes() + ); + assert_eq!(fake.eeprom[eeprom::ADDR_INFO_LOCK], eeprom::INFO_LOCK_BYTE); + assert_eq!(fake.eeprom[eeprom::ADDR_CONF_SF], 7); + assert_eq!( + &fake.eeprom[eeprom::ADDR_CONF_FREQ..eeprom::ADDR_CONF_FREQ + 4], + &868000000u32.to_be_bytes() + ); + assert_eq!(fake.eeprom[eeprom::ADDR_CONF_OK], eeprom::CONF_OK_BYTE); + } + + #[test] + fn device_control_actions_emit_expected_admin_frames() { + let frames = actions(&[ + "--bluetooth-on", + "--bluetooth-pair", + "--wifi", + "AP", + "--channel", + "6", + "--ssid", + "RNode", + "--psk", + "none", + "--show-psk", + "--ip", + "none", + "--nm", + "255.255.255.0", + "--display", + "192", + "--timeout", + "30", + "--rotation", + "2", + "--display-addr", + "0x3c", + "--recondition-display", + "--np", + "16", + "--freq", + "868000000", + "--bw", + "125000", + "--txp", + "14", + "--sf", + "7", + "--cr", + "5", + "--ia-enable", + "--ia-disable", + "fake", + ]); + + assert_has_frame(&frames, rnode::CMD_BT_CTRL, &[1]); + assert_has_frame(&frames, rnode::CMD_BT_CTRL, &[2]); + assert_has_frame( + &frames, + rnode::CMD_WIFI_MODE, + &[rnode_admin::WifiMode::AccessPoint as u8], + ); + assert_has_frame(&frames, rnode::CMD_WIFI_CHN, &[6]); + assert_has_frame(&frames, rnode::CMD_WIFI_SSID, b"RNode\0"); + assert_has_frame(&frames, rnode::CMD_WIFI_PSK, &[0]); + assert_has_frame(&frames, rnode::CMD_WIFI_PSK, &[0xFF]); + assert_has_frame(&frames, rnode::CMD_WIFI_IP, &[0, 0, 0, 0]); + assert_has_frame(&frames, rnode::CMD_WIFI_NM, &[255, 255, 255, 0]); + assert_has_frame(&frames, rnode::CMD_DISP_INT, &[192]); + assert_has_frame(&frames, rnode::CMD_DISP_BLNK, &[30]); + assert_has_frame(&frames, rnode::CMD_DISP_ROT, &[2]); + assert_has_frame(&frames, rnode::CMD_DISP_ADR, &[0x3C]); + assert_has_frame(&frames, rnode::CMD_DISP_RCND, &[1]); + assert_has_frame(&frames, rnode::CMD_NP_INT, &[16]); + assert_has_frame(&frames, rnode::CMD_FREQUENCY, &868000000u32.to_be_bytes()); + assert_has_frame(&frames, rnode::CMD_BANDWIDTH, &125000u32.to_be_bytes()); + assert_has_frame(&frames, rnode::CMD_TXPOWER, &[14]); + assert_has_frame(&frames, rnode::CMD_SF, &[7]); + assert_has_frame(&frames, rnode::CMD_CR, &[5]); + assert_has_frame(&frames, rnode::CMD_DIS_IA, &[0]); + assert_has_frame(&frames, rnode::CMD_DIS_IA, &[1]); + + let mut fake = FakeRNode::new(); + let (_, responses) = fake.transact(&encode_actions(&frames)); + assert_has_frame(&responses, rnode::CMD_BT_PIN, &123456u32.to_be_bytes()); + } + + #[test] + fn firmware_hash_and_device_signature_frames_round_trip_against_fake_rnode() { + let hash = [0xAB; 32]; + let signature = [0xCD; 64]; + let hash_hex = hex::encode(hash); + let mut frames = actions(&["--firmware-hash", &hash_hex, "fake"]); + frames.push(trust::device_signature_frame(&signature)); + + let mut fake = FakeRNode::new(); + let (requests, responses) = fake.transact(&encode_actions(&frames)); + + assert_eq!(requests, frames); + assert_eq!(fake.accepted_firmware_hash, Some(hash)); + assert_eq!(fake.accepted_device_signature, Some(signature)); + assert_has_frame(&responses, rnode::CMD_FW_HASH, &hash); + assert_has_frame(&responses, rnode::CMD_DEV_SIG, &signature); + } + + #[test] + fn display_and_neopixel_values_clamp_like_upstream_cli() { + let frames = actions(&[ + "--display=-5", + "--timeout", + "300", + "--rotation", + "8", + "--np", + "512", + "fake", + ]); + + assert_has_frame(&frames, rnode::CMD_DISP_INT, &[0]); + assert_has_frame(&frames, rnode::CMD_DISP_BLNK, &[255]); + assert_has_frame(&frames, rnode::CMD_DISP_ROT, &[3]); + assert_has_frame(&frames, rnode::CMD_NP_INT, &[255]); + } + + #[test] + fn eeprom_summary_reports_identity_and_radio_config() { + let info = eeprom::IdentityInfo { + product: model::PRODUCT_RNODE, + model: 0xB4, + hw_rev: 2, + serial: 0x01020304, + made: 0x6553F100, + }; + let radio = eeprom::RadioConfig { + spreading_factor: 7, + coding_rate: 5, + tx_power: 14, + bandwidth: 125000, + frequency: 868000000, + }; + let mut bytes = vec![0xFF; eeprom::EEPROM_SIZE]; + for frame in eeprom::identity_write_frames(&info) + .into_iter() + .chain(eeprom::radio_config_write_frames(&radio)) + { + let address = frame.payload[0] as usize; + bytes[address] = frame.payload[1]; + } + let image = eeprom::EepromImage::new(bytes).unwrap(); + let lines = eeprom_summary_lines(&image); + assert!(lines.iter().any(|line| line == "EEPROM: provisioned")); + assert!( + lines + .iter() + .any(|line| line.contains("Product: RNode (0x03)")) + ); + assert!(lines.iter().any(|line| line.contains("Startup mode: TNC"))); + assert!( + lines + .iter() + .any(|line| line.contains("Frequency: 868000000 Hz")) + ); + } + + #[test] + fn trusted_key_storage_uses_upstream_directory_shape() { + let root = std::env::temp_dir().join(format!( + "rnodeconf-trust-test-{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let paths = firmware::CachePaths::new(&root); + let trusted = store_trusted_key("aabbcc", &paths).unwrap(); + assert_eq!( + trusted, + root.join("trusted_keys") + .join(trust::trusted_key_filename(&[0xAA, 0xBB, 0xCC])) + ); + assert_eq!(fs::read(&trusted).unwrap(), vec![0xAA, 0xBB, 0xCC]); + let _ = fs::remove_dir_all(root); + } +} diff --git a/crates/rns-tools/src/commands/rnodeconf/eeprom.rs b/crates/rns-tools/src/commands/rnodeconf/eeprom.rs new file mode 100644 index 0000000..f10815f --- /dev/null +++ b/crates/rns-tools/src/commands/rnodeconf/eeprom.rs @@ -0,0 +1,352 @@ +//! RNode EEPROM layout helpers. + +use rns_interface::rnode_admin::{self, AdminFrame}; + +use super::model; + +pub const EEPROM_SIZE: usize = 296; +pub const ADDR_PRODUCT: usize = 0x00; +pub const ADDR_MODEL: usize = 0x01; +pub const ADDR_HW_REV: usize = 0x02; +pub const ADDR_SERIAL: usize = 0x03; +pub const ADDR_MADE: usize = 0x07; +pub const ADDR_CHKSUM: usize = 0x0B; +pub const ADDR_SIGNATURE: usize = 0x1B; +pub const ADDR_INFO_LOCK: usize = 0x9B; +pub const ADDR_CONF_SF: usize = 0x9C; +pub const ADDR_CONF_CR: usize = 0x9D; +pub const ADDR_CONF_TXP: usize = 0x9E; +pub const ADDR_CONF_BW: usize = 0x9F; +pub const ADDR_CONF_FREQ: usize = 0xA3; +pub const ADDR_CONF_OK: usize = 0xA7; + +pub const ADDR_CONF_BT: usize = 0xB0; +pub const ADDR_CONF_DSET: usize = 0xB1; +pub const ADDR_CONF_DINT: usize = 0xB2; +pub const ADDR_CONF_DADR: usize = 0xB3; +pub const ADDR_CONF_DBLK: usize = 0xB4; +pub const ADDR_CONF_PSET: usize = 0xB5; +pub const ADDR_CONF_PINT: usize = 0xB6; +pub const ADDR_CONF_BSET: usize = 0xB7; +pub const ADDR_CONF_DROT: usize = 0xB8; +pub const ADDR_CONF_DIA: usize = 0xB9; +pub const ADDR_CONF_WIFI: usize = 0xBA; +pub const ADDR_CONF_WCHN: usize = 0xBB; + +pub const ADDR_CONF_SSID: usize = 0x00; +pub const ADDR_CONF_PSK: usize = 0x21; +pub const ADDR_CONF_IP: usize = 0x42; +pub const ADDR_CONF_NM: usize = 0x46; + +pub const INFO_LOCK_BYTE: u8 = 0x73; +pub const CONF_OK_BYTE: u8 = 0x73; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityInfo { + pub product: u8, + pub model: u8, + pub hw_rev: u8, + pub serial: u32, + pub made: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RadioConfig { + pub spreading_factor: u8, + pub coding_rate: u8, + pub tx_power: u8, + pub bandwidth: u32, + pub frequency: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EepromImage { + bytes: Vec, +} + +impl EepromImage { + pub fn new(bytes: Vec) -> Result { + if bytes.len() < ADDR_CONF_OK + 1 { + return Err(format!("EEPROM image too short: {} bytes", bytes.len())); + } + Ok(Self { bytes }) + } + + pub fn bytes(&self) -> &[u8] { + &self.bytes + } + + pub fn identity(&self) -> IdentityInfo { + IdentityInfo { + product: self.bytes[ADDR_PRODUCT], + model: self.bytes[ADDR_MODEL], + hw_rev: self.bytes[ADDR_HW_REV], + serial: read_be_u32(&self.bytes, ADDR_SERIAL), + made: read_be_u32(&self.bytes, ADDR_MADE), + } + } + + pub fn stored_checksum(&self) -> [u8; 16] { + let mut out = [0u8; 16]; + out.copy_from_slice(&self.bytes[ADDR_CHKSUM..ADDR_CHKSUM + 16]); + out + } + + pub fn calculated_checksum(&self) -> [u8; 16] { + identity_checksum(&self.identity()) + } + + pub fn checksum_valid(&self) -> bool { + self.stored_checksum() == self.calculated_checksum() + } + + pub fn info_locked(&self) -> bool { + self.bytes[ADDR_INFO_LOCK] == INFO_LOCK_BYTE + } + + pub fn radio_config(&self) -> Option { + (self.bytes[ADDR_CONF_OK] == CONF_OK_BYTE).then(|| RadioConfig { + spreading_factor: self.bytes[ADDR_CONF_SF], + coding_rate: self.bytes[ADDR_CONF_CR], + tx_power: self.bytes[ADDR_CONF_TXP], + bandwidth: read_be_u32(&self.bytes, ADDR_CONF_BW), + frequency: read_be_u32(&self.bytes, ADDR_CONF_FREQ), + }) + } +} + +pub fn identity_checksum(info: &IdentityInfo) -> [u8; 16] { + md5_digest(&identity_checksum_input(info)) +} + +pub fn identity_checksum_input(info: &IdentityInfo) -> [u8; 11] { + let mut input = [0u8; 11]; + input[0] = info.product; + input[1] = model::normalize_eeprom_model(info.model); + input[2] = info.hw_rev; + input[3..7].copy_from_slice(&info.serial.to_be_bytes()); + input[7..11].copy_from_slice(&info.made.to_be_bytes()); + input +} + +pub fn identity_write_frames(info: &IdentityInfo) -> Vec { + let model = model::normalize_eeprom_model(info.model); + let checksum = identity_checksum(info); + let mut writes = Vec::new(); + writes.push(write(ADDR_PRODUCT, info.product)); + writes.push(write(ADDR_MODEL, model)); + writes.push(write(ADDR_HW_REV, info.hw_rev)); + writes.extend(write_bytes(ADDR_SERIAL, &info.serial.to_be_bytes())); + writes.extend(write_bytes(ADDR_MADE, &info.made.to_be_bytes())); + writes.extend(write_bytes(ADDR_CHKSUM, &checksum)); + writes.push(write(ADDR_INFO_LOCK, INFO_LOCK_BYTE)); + writes +} + +pub fn radio_config_write_frames(config: &RadioConfig) -> Vec { + let mut writes = vec![ + write(ADDR_CONF_SF, config.spreading_factor), + write(ADDR_CONF_CR, config.coding_rate), + write(ADDR_CONF_TXP, config.tx_power), + ]; + writes.extend(write_bytes(ADDR_CONF_BW, &config.bandwidth.to_be_bytes())); + writes.extend(write_bytes(ADDR_CONF_FREQ, &config.frequency.to_be_bytes())); + writes.push(write(ADDR_CONF_OK, CONF_OK_BYTE)); + writes +} + +pub fn write(address: usize, value: u8) -> AdminFrame { + let address = u8::try_from(address).expect("RNode EEPROM write address must fit in one byte"); + rnode_admin::eeprom_write_frame(address, value) +} + +pub fn write_bytes(start: usize, bytes: &[u8]) -> Vec { + bytes + .iter() + .enumerate() + .map(|(offset, value)| write(start + offset, *value)) + .collect() +} + +fn read_be_u32(bytes: &[u8], start: usize) -> u32 { + u32::from_be_bytes( + bytes[start..start + 4] + .try_into() + .expect("slice length checked"), + ) +} + +fn md5_digest(input: &[u8]) -> [u8; 16] { + const S: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, + 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, + 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + ]; + const K: [u32; 64] = [ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, + 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, + 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, + 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, + 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, + 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, + 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, + 0xeb86d391, + ]; + + let bit_len = (input.len() as u64) * 8; + let mut msg = input.to_vec(); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend_from_slice(&bit_len.to_le_bytes()); + + let mut a0 = 0x67452301u32; + let mut b0 = 0xefcdab89u32; + let mut c0 = 0x98badcfeu32; + let mut d0 = 0x10325476u32; + + for chunk in msg.chunks_exact(64) { + let mut m = [0u32; 16]; + for (i, word) in chunk.chunks_exact(4).enumerate() { + m[i] = u32::from_le_bytes(word.try_into().unwrap()); + } + + let mut a = a0; + let mut b = b0; + let mut c = c0; + let mut d = d0; + + for i in 0..64 { + let (f, g) = if i < 16 { + ((b & c) | ((!b) & d), i) + } else if i < 32 { + ((d & b) | ((!d) & c), (5 * i + 1) % 16) + } else if i < 48 { + (b ^ c ^ d, (3 * i + 5) % 16) + } else { + (c ^ (b | (!d)), (7 * i) % 16) + }; + let next = b.wrapping_add( + a.wrapping_add(f) + .wrapping_add(K[i]) + .wrapping_add(m[g]) + .rotate_left(S[i]), + ); + a = d; + d = c; + c = b; + b = next; + } + + a0 = a0.wrapping_add(a); + b0 = b0.wrapping_add(b); + c0 = c0.wrapping_add(c); + d0 = d0.wrapping_add(d); + } + + let mut out = [0u8; 16]; + out[0..4].copy_from_slice(&a0.to_le_bytes()); + out[4..8].copy_from_slice(&b0.to_le_bytes()); + out[8..12].copy_from_slice(&c0.to_le_bytes()); + out[12..16].copy_from_slice(&d0.to_le_bytes()); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn md5_vectors_match_reference() { + assert_eq!( + hex::encode(md5_digest(b"")), + "d41d8cd98f00b204e9800998ecf8427e" + ); + assert_eq!( + hex::encode(md5_digest(b"abc")), + "900150983cd24fb0d6963f7d28e17f72" + ); + } + + #[test] + fn identity_checksum_matches_python_hashlib_vector() { + let info = IdentityInfo { + product: model::PRODUCT_RNODE, + model: 0xA4, + hw_rev: 1, + serial: 0x01020304, + made: 0x6553F100, + }; + assert_eq!( + hex::encode(identity_checksum(&info)), + "e5ee1a1964bfd72e7da9147942b6f9af" + ); + } + + #[test] + fn eeprom_image_parses_identity_and_radio_config() { + let info = IdentityInfo { + product: model::PRODUCT_RAK4631, + model: 0x11, + hw_rev: 2, + serial: 0x12345678, + made: 0x5F3759DF, + }; + let mut bytes = vec![0u8; EEPROM_SIZE]; + bytes[ADDR_PRODUCT] = info.product; + bytes[ADDR_MODEL] = info.model; + bytes[ADDR_HW_REV] = info.hw_rev; + bytes[ADDR_SERIAL..ADDR_SERIAL + 4].copy_from_slice(&info.serial.to_be_bytes()); + bytes[ADDR_MADE..ADDR_MADE + 4].copy_from_slice(&info.made.to_be_bytes()); + bytes[ADDR_CHKSUM..ADDR_CHKSUM + 16].copy_from_slice(&identity_checksum(&info)); + bytes[ADDR_INFO_LOCK] = INFO_LOCK_BYTE; + bytes[ADDR_CONF_SF] = 7; + bytes[ADDR_CONF_CR] = 5; + bytes[ADDR_CONF_TXP] = 14; + bytes[ADDR_CONF_BW..ADDR_CONF_BW + 4].copy_from_slice(&125000u32.to_be_bytes()); + bytes[ADDR_CONF_FREQ..ADDR_CONF_FREQ + 4].copy_from_slice(&868000000u32.to_be_bytes()); + bytes[ADDR_CONF_OK] = CONF_OK_BYTE; + + let image = EepromImage::new(bytes).unwrap(); + assert_eq!(image.identity(), info); + assert!(image.checksum_valid()); + assert!(image.info_locked()); + assert_eq!( + image.radio_config(), + Some(RadioConfig { + spreading_factor: 7, + coding_rate: 5, + tx_power: 14, + bandwidth: 125000, + frequency: 868000000, + }) + ); + } + + #[test] + fn identity_write_frames_match_upstream_rom_write_shape() { + let info = IdentityInfo { + product: model::PRODUCT_RNODE, + model: model::MODEL_B4_TCXO, + hw_rev: 1, + serial: 0x01020304, + made: 0x6553F100, + }; + let frames = identity_write_frames(&info); + assert_eq!( + frames[0], + rnode_admin::eeprom_write_frame(ADDR_PRODUCT as u8, 0x03) + ); + assert_eq!( + frames[1], + rnode_admin::eeprom_write_frame(ADDR_MODEL as u8, 0xB4) + ); + assert_eq!( + frames.last().unwrap().payload, + vec![ADDR_INFO_LOCK as u8, INFO_LOCK_BYTE] + ); + } +} diff --git a/crates/rns-tools/src/commands/rnodeconf/firmware.rs b/crates/rns-tools/src/commands/rnodeconf/firmware.rs new file mode 100644 index 0000000..7d04c3a --- /dev/null +++ b/crates/rns-tools/src/commands/rnodeconf/firmware.rs @@ -0,0 +1,170 @@ +//! Firmware manifest, cache and hash helpers. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use serde::Deserialize; + +use super::model; + +pub const DEFAULT_FIRMWARE_VERSION_URL: &str = + "https://github.com/markqvist/rnode_firmware/releases/latest/download/release.json"; +pub const FIRMWARE_UPDATE_URL: &str = + "https://github.com/markqvist/RNode_Firmware/releases/download/"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FirmwareRelease { + pub filename: String, + pub version: String, + pub hash: [u8; 32], +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CachePaths { + pub root: PathBuf, + pub update: PathBuf, + pub firmware: PathBuf, + pub extracted: PathBuf, + pub trusted_keys: PathBuf, + pub eeprom: PathBuf, +} + +impl CachePaths { + pub fn new(root: impl Into) -> Self { + let root = root.into(); + Self { + update: root.join("update"), + firmware: root.join("firmware"), + extracted: root.join("extracted"), + trusted_keys: root.join("trusted_keys"), + eeprom: root.join("eeprom"), + root, + } + } + + pub fn update_version_file(&self, version: &str, filename: &str) -> PathBuf { + self.update + .join(version) + .join(format!("{filename}.version")) + } +} + +#[derive(Debug, Deserialize)] +struct ManifestEntry { + version: String, + hash: String, +} + +pub fn parse_release_manifest(json: &str) -> Result, String> { + let entries: BTreeMap = + serde_json::from_str(json).map_err(|e| format!("invalid release manifest: {e}"))?; + entries + .into_iter() + .map(|(filename, entry)| { + let hash = parse_sha256_hex(&entry.hash)?; + Ok(FirmwareRelease { + filename, + version: entry.version, + hash, + }) + }) + .collect() +} + +pub fn selected_release<'a>( + releases: &'a [FirmwareRelease], + filename: &str, +) -> Option<&'a FirmwareRelease> { + releases.iter().find(|release| release.filename == filename) +} + +pub fn cache_version_record(version: &str, hash: &[u8; 32]) -> String { + format!("{version} {}", hex::encode(hash)) +} + +pub fn verify_package_hash(data: &[u8], expected: &[u8; 32]) -> bool { + &rns_crypto::sha::sha256(data) == expected +} + +pub fn partition_hash(platform: u8, firmware_data: &[u8]) -> Option<[u8; 32]> { + match platform { + model::PLATFORM_AVR | model::PLATFORM_ESP32 => { + let payload = firmware_data.get(..firmware_data.len().checked_sub(32)?)?; + let embedded: [u8; 32] = firmware_data[firmware_data.len() - 32..].try_into().ok()?; + (rns_crypto::sha::sha256(payload) == embedded).then_some(embedded) + } + model::PLATFORM_NRF52 => Some(rns_crypto::sha::sha256(firmware_data)), + _ => None, + } +} + +pub fn extracted_required_files(root: &Path) -> [PathBuf; 5] { + [ + root.join("extracted_rnode_firmware.bin"), + root.join("extracted_rnode_firmware.boot_app0"), + root.join("extracted_rnode_firmware.bootloader"), + root.join("extracted_rnode_firmware.partitions"), + root.join("extracted_console_image.bin"), + ] +} + +pub fn parse_sha256_hex(hex_value: &str) -> Result<[u8; 32], String> { + let bytes = hex::decode(hex_value).map_err(|e| format!("invalid SHA-256 hex: {e}"))?; + bytes + .try_into() + .map_err(|bytes: Vec| format!("expected 32-byte SHA-256, got {} bytes", bytes.len())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn release_manifest_parses_hashes_by_filename() { + let json = r#"{ + "rnode_firmware.hex": { + "version": "1.73", + "hash": "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff" + }, + "rnode_firmware_t3s3.zip": { + "version": "1.74", + "hash": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + } + }"#; + let releases = parse_release_manifest(json).unwrap(); + assert_eq!(releases.len(), 2); + let release = selected_release(&releases, "rnode_firmware.hex").unwrap(); + assert_eq!(release.version, "1.73"); + assert_eq!(release.hash[0], 0x00); + assert_eq!(release.hash[31], 0xFF); + } + + #[test] + fn cache_paths_match_upstream_layout() { + let paths = CachePaths::new("/tmp/rnodeconf"); + assert_eq!(paths.update, PathBuf::from("/tmp/rnodeconf/update")); + assert_eq!(paths.firmware, PathBuf::from("/tmp/rnodeconf/firmware")); + assert_eq!( + paths.update_version_file("1.73", "rnode_firmware.hex"), + PathBuf::from("/tmp/rnodeconf/update/1.73/rnode_firmware.hex.version") + ); + } + + #[test] + fn partition_hash_matches_upstream_platform_rules() { + let payload = b"firmware-image"; + let hash = rns_crypto::sha::sha256(payload); + let mut esp32 = payload.to_vec(); + esp32.extend_from_slice(&hash); + assert_eq!(partition_hash(model::PLATFORM_ESP32, &esp32), Some(hash)); + + let nrf_hash = rns_crypto::sha::sha256(&esp32); + assert_eq!( + partition_hash(model::PLATFORM_NRF52, &esp32), + Some(nrf_hash) + ); + + esp32[0] ^= 1; + assert_eq!(partition_hash(model::PLATFORM_ESP32, &esp32), None); + } +} diff --git a/crates/rns-tools/src/commands/rnodeconf/flash.rs b/crates/rns-tools/src/commands/rnodeconf/flash.rs new file mode 100644 index 0000000..9d15a54 --- /dev/null +++ b/crates/rns-tools/src/commands/rnodeconf/flash.rs @@ -0,0 +1,351 @@ +//! Firmware flasher command planning. + +use std::path::{Path, PathBuf}; + +use super::model; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FlashContext { + pub python: String, + pub port: String, + pub baud_flash: String, + pub update_dir: PathBuf, + pub extracted_dir: PathBuf, + pub selected_version: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FlashPlan { + pub program: String, + pub args: Vec, +} + +impl FlashPlan { + pub fn argv(&self) -> Vec { + let mut argv = Vec::with_capacity(self.args.len() + 1); + argv.push(self.program.clone()); + argv.extend(self.args.clone()); + argv + } +} + +pub fn plan_unzip(update_dir: &Path, version: &str, fw_filename: &str) -> FlashPlan { + let archive = update_dir.join(version).join(fw_filename); + FlashPlan { + program: "unzip".to_string(), + args: vec![ + "-o".to_string(), + path_string(&archive), + "-d".to_string(), + path_string(&update_dir.join(version)), + ], + } +} + +pub fn plan_flasher(platform: u8, fw_filename: &str, ctx: &FlashContext) -> Option { + match platform { + model::PLATFORM_AVR => plan_avr(fw_filename, ctx), + model::PLATFORM_ESP32 => plan_esp32(fw_filename, ctx), + model::PLATFORM_NRF52 => Some(plan_nrf52(fw_filename, ctx)), + _ => None, + } +} + +fn plan_avr(fw_filename: &str, ctx: &FlashContext) -> Option { + let mut args = vec!["-P".to_string(), ctx.port.clone()]; + match fw_filename { + "rnode_firmware.hex" => { + args.extend([ + "-p".to_string(), + "m1284p".to_string(), + "-c".to_string(), + "arduino".to_string(), + "-b".to_string(), + "115200".to_string(), + "-U".to_string(), + format!( + "flash:w:{}:i", + path_string(&ctx.update_dir.join(&ctx.selected_version).join(fw_filename)) + ), + ]); + } + "rnode_firmware_m2560.hex" => { + args.extend([ + "-p".to_string(), + "atmega2560".to_string(), + "-c".to_string(), + "wiring".to_string(), + "-D".to_string(), + "-b".to_string(), + "115200".to_string(), + "-U".to_string(), + format!( + "flash:w:{}", + path_string(&ctx.update_dir.join(&ctx.selected_version).join(fw_filename)) + ), + ]); + } + _ => return None, + } + Some(FlashPlan { + program: "avrdude".to_string(), + args, + }) +} + +fn plan_nrf52(fw_filename: &str, ctx: &FlashContext) -> FlashPlan { + FlashPlan { + program: "adafruit-nrfutil".to_string(), + args: vec![ + "dfu".to_string(), + "serial".to_string(), + "--package".to_string(), + path_string(&ctx.update_dir.join(&ctx.selected_version).join(fw_filename)), + "-p".to_string(), + ctx.port.clone(), + "-b".to_string(), + "115200".to_string(), + "-t".to_string(), + "1200".to_string(), + ], + } +} + +fn plan_esp32(fw_filename: &str, ctx: &FlashContext) -> Option { + if fw_filename == "extracted_rnode_firmware.zip" { + return Some(FlashPlan { + program: ctx.python.clone(), + args: esp32_args( + &ctx.update_dir + .join(&ctx.selected_version) + .join("esptool.py"), + "esp32", + &ctx.port, + &ctx.baud_flash, + "4MB", + &[ + ( + "0x1000", + ctx.extracted_dir + .join("extracted_rnode_firmware.bootloader"), + ), + ( + "0xe000", + ctx.extracted_dir.join("extracted_rnode_firmware.boot_app0"), + ), + ( + "0x8000", + ctx.extracted_dir + .join("extracted_rnode_firmware.partitions"), + ), + ( + "0x10000", + ctx.extracted_dir.join("extracted_rnode_firmware.bin"), + ), + ( + "0x210000", + ctx.extracted_dir.join("extracted_console_image.bin"), + ), + ], + ), + }); + } + + let spec = esp32_spec(fw_filename)?; + let version_dir = ctx.update_dir.join(&ctx.selected_version); + let stem = fw_filename.strip_suffix(".zip")?; + let mut images = vec![ + ("0xe000", version_dir.join(format!("{stem}.boot_app0"))), + ( + spec.bootloader_offset, + version_dir.join(format!("{stem}.bootloader")), + ), + ("0x10000", version_dir.join(format!("{stem}.bin"))), + ]; + if spec.include_console || version_at_least(&ctx.selected_version, 1.55) { + images.push(("0x210000", version_dir.join("console_image.bin"))); + } + images.push(("0x8000", version_dir.join(format!("{stem}.partitions")))); + + Some(FlashPlan { + program: ctx.python.clone(), + args: esp32_args( + &version_dir.join("esptool.py"), + spec.chip, + &ctx.port, + &ctx.baud_flash, + spec.flash_size, + &images, + ), + }) +} + +#[derive(Debug, Clone, Copy)] +struct Esp32Spec { + chip: &'static str, + flash_size: &'static str, + bootloader_offset: &'static str, + include_console: bool, +} + +fn esp32_spec(fw_filename: &str) -> Option { + let s3 = Esp32Spec { + chip: "esp32s3", + flash_size: "4MB", + bootloader_offset: "0x0", + include_console: true, + }; + Some(match fw_filename { + "rnode_firmware_t3s3.zip" + | "rnode_firmware_t3s3_sx127x.zip" + | "rnode_firmware_t3s3_sx1280_pa.zip" + | "rnode_firmware_tbeam_supreme.zip" + | "rnode_firmware_tdeck.zip" => s3, + "rnode_firmware_xiao_esp32s3.zip" => Esp32Spec { + flash_size: "8MB", + ..s3 + }, + "rnode_firmware_heltec32v4pa.zip" => Esp32Spec { + chip: "esp32-s3", + flash_size: "16MB", + bootloader_offset: "0x0", + include_console: true, + }, + "rnode_firmware_heltec32v3.zip" => Esp32Spec { + chip: "esp32s3", + flash_size: "8MB", + bootloader_offset: "0x0", + include_console: true, + }, + "rnode_firmware_tbeam.zip" + | "rnode_firmware_tbeam_sx1262.zip" + | "rnode_firmware_lora32v10.zip" + | "rnode_firmware_lora32v20.zip" + | "rnode_firmware_lora32v21.zip" + | "rnode_firmware_lora32v21_tcxo.zip" + | "rnode_firmware_heltec32v2.zip" + | "rnode_firmware_featheresp32.zip" + | "rnode_firmware_esp32_generic.zip" + | "rnode_firmware_ng20.zip" + | "rnode_firmware_ng21.zip" => Esp32Spec { + chip: "esp32", + flash_size: "4MB", + bootloader_offset: "0x1000", + include_console: false, + }, + _ => return None, + }) +} + +fn esp32_args( + flasher: &Path, + chip: &str, + port: &str, + baud: &str, + flash_size: &str, + images: &[(&str, PathBuf)], +) -> Vec { + let mut args = vec![ + path_string(flasher), + "--chip".to_string(), + chip.to_string(), + "--port".to_string(), + port.to_string(), + "--baud".to_string(), + baud.to_string(), + "--before".to_string(), + "default_reset".to_string(), + "--after".to_string(), + "hard_reset".to_string(), + "write_flash".to_string(), + "-z".to_string(), + "--flash_mode".to_string(), + "dio".to_string(), + "--flash_freq".to_string(), + "80m".to_string(), + "--flash_size".to_string(), + flash_size.to_string(), + ]; + for (offset, path) in images { + args.push((*offset).to_string()); + args.push(path_string(path)); + } + args +} + +fn version_at_least(version: &str, min: f64) -> bool { + version.parse::().map(|v| v >= min).unwrap_or(false) +} + +fn path_string(path: &Path) -> String { + path.to_string_lossy().into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> FlashContext { + FlashContext { + python: "python3".to_string(), + port: "/dev/ttyUSB0".to_string(), + baud_flash: "921600".to_string(), + update_dir: PathBuf::from("/cache/update"), + extracted_dir: PathBuf::from("/cache/extracted"), + selected_version: "1.74".to_string(), + } + } + + fn update_version_file(filename: &str) -> String { + path_string(&PathBuf::from("/cache/update").join("1.74").join(filename)) + } + + #[test] + fn avr_plan_matches_upstream_avrdude_shape() { + let plan = plan_flasher(model::PLATFORM_AVR, "rnode_firmware.hex", &ctx()).unwrap(); + let argv = plan.argv(); + assert_eq!(argv[0], "avrdude"); + assert!(argv.contains(&"m1284p".to_string())); + let flash_arg = format!("flash:w:{}:i", update_version_file("rnode_firmware.hex")); + assert!( + argv.iter().any(|arg| arg == &flash_arg), + "missing flash argument in {argv:?}" + ); + } + + #[test] + fn esp32_s3_plan_uses_full_partition_table() { + let plan = plan_flasher(model::PLATFORM_ESP32, "rnode_firmware_t3s3.zip", &ctx()).unwrap(); + let argv = plan.argv(); + assert_eq!(argv[0], "python3"); + assert!(argv.contains(&"esp32s3".to_string())); + assert!(argv.contains(&"0x210000".to_string())); + let firmware_bin = update_version_file("rnode_firmware_t3s3.bin"); + assert!( + argv.iter().any(|arg| arg == &firmware_bin), + "missing firmware image in {argv:?}" + ); + } + + #[test] + fn nrf52_plan_never_invokes_hardware_in_tests() { + let plan = + plan_flasher(model::PLATFORM_NRF52, "rnode_firmware_rak4631.zip", &ctx()).unwrap(); + assert_eq!( + plan.argv(), + vec![ + "adafruit-nrfutil".to_string(), + "dfu".to_string(), + "serial".to_string(), + "--package".to_string(), + update_version_file("rnode_firmware_rak4631.zip"), + "-p".to_string(), + "/dev/ttyUSB0".to_string(), + "-b".to_string(), + "115200".to_string(), + "-t".to_string(), + "1200".to_string(), + ] + ); + } +} diff --git a/crates/rns-tools/src/commands/rnodeconf/model.rs b/crates/rns-tools/src/commands/rnodeconf/model.rs new file mode 100644 index 0000000..792188e --- /dev/null +++ b/crates/rns-tools/src/commands/rnodeconf/model.rs @@ -0,0 +1,556 @@ +//! RNode platform, product and firmware model tables. + +pub const PLATFORM_AVR: u8 = 0x90; +pub const PLATFORM_ESP32: u8 = 0x80; +pub const PLATFORM_NRF52: u8 = 0x70; + +pub const MCU_1284P: u8 = 0x91; +pub const MCU_2560: u8 = 0x92; +pub const MCU_ESP32: u8 = 0x81; +pub const MCU_NRF52: u8 = 0x71; + +pub const PRODUCT_RNODE: u8 = 0x03; +pub const PRODUCT_RAK4631: u8 = 0x10; +pub const PRODUCT_TECHO: u8 = 0x15; +pub const PRODUCT_OPENCOM_XL: u8 = 0x20; +pub const PRODUCT_T32_20: u8 = 0xB0; +pub const PRODUCT_T32_21: u8 = 0xB1; +pub const PRODUCT_T32_10: u8 = 0xB2; +pub const PRODUCT_H32_V2: u8 = 0xC0; +pub const PRODUCT_H32_V3: u8 = 0xC1; +pub const PRODUCT_HELTEC_T114: u8 = 0xC2; +pub const PRODUCT_H32_V4: u8 = 0xC3; +pub const PRODUCT_TDECK: u8 = 0xD0; +pub const PRODUCT_TBEAM: u8 = 0xE0; +pub const PRODUCT_TBEAM_S_V1: u8 = 0xEA; +pub const PRODUCT_XIAO_S3: u8 = 0xEB; +pub const PRODUCT_HMBRW: u8 = 0xF0; + +pub const MODEL_B4_TCXO: u8 = 0x04; +pub const MODEL_B9_TCXO: u8 = 0x09; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ModelInfo { + pub model: u8, + pub min_frequency: u32, + pub max_frequency: u32, + pub max_tx_power: u8, + pub band_label: &'static str, + pub firmware_filename: Option<&'static str>, + pub radio: &'static str, +} + +pub const MODELS: &[ModelInfo] = &[ + model( + 0xA4, + 410000000, + 525000000, + 14, + "410 - 525 MHz", + Some("rnode_firmware.hex"), + "SX1278", + ), + model( + 0xA9, + 820000000, + 1020000000, + 17, + "820 - 1020 MHz", + Some("rnode_firmware.hex"), + "SX1276", + ), + model( + 0xA1, + 410000000, + 525000000, + 22, + "410 - 525 MHz", + Some("rnode_firmware_t3s3.zip"), + "SX1268", + ), + model( + 0xA6, + 820000000, + 1020000000, + 22, + "820 - 960 MHz", + Some("rnode_firmware_t3s3.zip"), + "SX1262", + ), + model( + 0xA5, + 410000000, + 525000000, + 17, + "410 - 525 MHz", + Some("rnode_firmware_t3s3_sx127x.zip"), + "SX1278", + ), + model( + 0xAA, + 820000000, + 1020000000, + 17, + "820 - 960 MHz", + Some("rnode_firmware_t3s3_sx127x.zip"), + "SX1276", + ), + model( + 0xAC, + 2400000000, + 2500000000, + 20, + "2.4 - 2.5 GHz", + Some("rnode_firmware_t3s3_sx1280_pa.zip"), + "SX1280", + ), + model( + 0xA2, + 410000000, + 525000000, + 17, + "410 - 525 MHz", + Some("rnode_firmware_ng21.zip"), + "SX1278", + ), + model( + 0xA7, + 820000000, + 1020000000, + 17, + "820 - 1020 MHz", + Some("rnode_firmware_ng21.zip"), + "SX1276", + ), + model( + 0xA3, + 410000000, + 525000000, + 17, + "410 - 525 MHz", + Some("rnode_firmware_ng20.zip"), + "SX1278", + ), + model( + 0xA8, + 820000000, + 1020000000, + 17, + "820 - 1020 MHz", + Some("rnode_firmware_ng20.zip"), + "SX1276", + ), + model( + 0xB3, + 420000000, + 520000000, + 17, + "420 - 520 MHz", + Some("rnode_firmware_lora32v20.zip"), + "SX1278", + ), + model( + 0xB8, + 850000000, + 950000000, + 17, + "850 - 950 MHz", + Some("rnode_firmware_lora32v20.zip"), + "SX1276", + ), + model( + 0xB4, + 420000000, + 520000000, + 17, + "420 - 520 MHz", + Some("rnode_firmware_lora32v21.zip"), + "SX1278", + ), + model( + 0xB9, + 850000000, + 950000000, + 17, + "850 - 950 MHz", + Some("rnode_firmware_lora32v21.zip"), + "SX1276", + ), + model( + MODEL_B4_TCXO, + 420000000, + 520000000, + 17, + "420 - 520 MHz", + Some("rnode_firmware_lora32v21_tcxo.zip"), + "SX1278", + ), + model( + MODEL_B9_TCXO, + 850000000, + 950000000, + 17, + "850 - 950 MHz", + Some("rnode_firmware_lora32v21_tcxo.zip"), + "SX1276", + ), + model( + 0xBA, + 420000000, + 520000000, + 17, + "420 - 520 MHz", + Some("rnode_firmware_lora32v10.zip"), + "SX1278", + ), + model( + 0xBB, + 850000000, + 950000000, + 17, + "850 - 950 MHz", + Some("rnode_firmware_lora32v10.zip"), + "SX1276", + ), + model( + 0xC4, + 420000000, + 520000000, + 17, + "420 - 520 MHz", + Some("rnode_firmware_heltec32v2.zip"), + "SX1278", + ), + model( + 0xC9, + 850000000, + 950000000, + 17, + "850 - 950 MHz", + Some("rnode_firmware_heltec32v2.zip"), + "SX1276", + ), + model( + 0xC5, + 420000000, + 520000000, + 22, + "420 - 520 MHz", + Some("rnode_firmware_heltec32v3.zip"), + "SX1268", + ), + model( + 0xCA, + 850000000, + 950000000, + 22, + "850 - 950 MHz", + Some("rnode_firmware_heltec32v3.zip"), + "SX1262", + ), + model( + 0xC8, + 860000000, + 930000000, + 28, + "850 - 950 MHz", + Some("rnode_firmware_heltec32v4pa.zip"), + "SX1262", + ), + model( + 0xC6, + 420000000, + 520000000, + 22, + "420 - 520 MHz", + Some("rnode_firmware_heltec_t114.zip"), + "SX1268", + ), + model( + 0xC7, + 850000000, + 950000000, + 22, + "850 - 950 MHz", + Some("rnode_firmware_heltec_t114.zip"), + "SX1262", + ), + model( + 0xE4, + 420000000, + 520000000, + 17, + "420 - 520 MHz", + Some("rnode_firmware_tbeam.zip"), + "SX1278", + ), + model( + 0xE9, + 850000000, + 950000000, + 17, + "850 - 950 MHz", + Some("rnode_firmware_tbeam.zip"), + "SX1276", + ), + model( + 0xD4, + 420000000, + 520000000, + 22, + "420 - 520 MHz", + Some("rnode_firmware_tdeck.zip"), + "SX1268", + ), + model( + 0xD9, + 850000000, + 950000000, + 22, + "850 - 950 MHz", + Some("rnode_firmware_tdeck.zip"), + "SX1262", + ), + model( + 0xDB, + 420000000, + 520000000, + 22, + "420 - 520 MHz", + Some("rnode_firmware_tbeam_supreme.zip"), + "SX1268", + ), + model( + 0xDC, + 850000000, + 950000000, + 22, + "850 - 950 MHz", + Some("rnode_firmware_tbeam_supreme.zip"), + "SX1262", + ), + model( + 0xE3, + 420000000, + 520000000, + 22, + "420 - 520 MHz", + Some("rnode_firmware_tbeam_sx1262.zip"), + "SX1268", + ), + model( + 0xE8, + 850000000, + 950000000, + 22, + "850 - 950 MHz", + Some("rnode_firmware_tbeam_sx1262.zip"), + "SX1262", + ), + model( + 0x11, + 430000000, + 510000000, + 22, + "430 - 510 MHz", + Some("rnode_firmware_rak4631.zip"), + "SX1262", + ), + model( + 0x12, + 779000000, + 928000000, + 22, + "779 - 928 MHz", + Some("rnode_firmware_rak4631.zip"), + "SX1262", + ), + model( + 0x13, + 430000000, + 510000000, + 22, + "430 - 510 MHz", + Some("rnode_firmware_rak4631_sx1280.zip"), + "SX1262 + SX1280", + ), + model( + 0x14, + 779000000, + 928000000, + 22, + "779 - 928 MHz", + Some("rnode_firmware_rak4631_sx1280.zip"), + "SX1262 + SX1280", + ), + model( + 0x16, + 779000000, + 928000000, + 22, + "430 - 510 Mhz", + Some("rnode_firmware_techo.zip"), + "SX1262", + ), + model( + 0x17, + 779000000, + 928000000, + 22, + "779 - 928 Mhz", + Some("rnode_firmware_techo.zip"), + "SX1262", + ), + model( + 0x21, + 820000000, + 960000000, + 22, + "820 - 960 MHz", + Some("rnode_firmware_opencom_xl.zip"), + "SX1262 + SX1280", + ), + model( + 0xDE, + 420000000, + 520000000, + 22, + "420 - 520 MHz", + Some("rnode_firmware_xiao_esp32s3.zip"), + "SX1262", + ), + model( + 0xDD, + 850000000, + 950000000, + 22, + "850 - 950 MHz", + Some("rnode_firmware_xiao_esp32s3.zip"), + "SX1262", + ), + model( + 0xFE, + 100000000, + 1100000000, + 17, + "(Band capabilities unknown)", + None, + "Unknown", + ), + model( + 0xFF, + 100000000, + 1100000000, + 14, + "(Band capabilities unknown)", + None, + "Unknown", + ), +]; + +const fn model( + model: u8, + min_frequency: u32, + max_frequency: u32, + max_tx_power: u8, + band_label: &'static str, + firmware_filename: Option<&'static str>, + radio: &'static str, +) -> ModelInfo { + ModelInfo { + model, + min_frequency, + max_frequency, + max_tx_power, + band_label, + firmware_filename, + radio, + } +} + +pub fn model_info(model: u8) -> Option<&'static ModelInfo> { + MODELS.iter().find(|entry| entry.model == model) +} + +pub fn normalize_eeprom_model(model: u8) -> u8 { + match model { + MODEL_B4_TCXO => 0xB4, + MODEL_B9_TCXO => 0xB9, + other => other, + } +} + +pub fn product_name(product: u8) -> Option<&'static str> { + Some(match product { + PRODUCT_RNODE => "RNode", + PRODUCT_HMBRW => "Hombrew RNode", + PRODUCT_TBEAM => "LilyGO T-Beam", + PRODUCT_TBEAM_S_V1 => "LilyGO T-Beam Supreme", + PRODUCT_TDECK => "LilyGO T-Deck", + PRODUCT_T32_10 => "LilyGO LoRa32 v1.0", + PRODUCT_T32_20 => "LilyGO LoRa32 v2.0", + PRODUCT_T32_21 => "LilyGO LoRa32 v2.1", + PRODUCT_H32_V2 => "Heltec LoRa32 v2", + PRODUCT_H32_V3 => "Heltec LoRa32 v3", + PRODUCT_H32_V4 => "Heltec LoRa32 v4", + PRODUCT_TECHO => "LilyGO T-Echo", + PRODUCT_RAK4631 => "RAK4631", + PRODUCT_OPENCOM_XL => "openCom XL", + PRODUCT_HELTEC_T114 => "Heltec Mesh Node T114", + PRODUCT_XIAO_S3 => "Seeed XIAO ESP32S3 Wio-SX1262", + _ => return None, + }) +} + +pub fn platform_name(platform: u8) -> Option<&'static str> { + Some(match platform { + PLATFORM_AVR => "AVR", + PLATFORM_ESP32 => "ESP32", + PLATFORM_NRF52 => "NRF52", + _ => return None, + }) +} + +pub fn mcu_name(mcu: u8) -> Option<&'static str> { + Some(match mcu { + MCU_1284P => "ATmega1284P", + MCU_2560 => "ATmega2560", + MCU_ESP32 => "Espressif Systems ESP32", + MCU_NRF52 => "Nordic Semiconductor nRF52840", + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn model_table_matches_upstream_shape() { + assert_eq!(MODELS.len(), 45); + assert_eq!( + model_info(0xA4).unwrap().firmware_filename, + Some("rnode_firmware.hex") + ); + assert_eq!( + model_info(0xAC).unwrap().firmware_filename, + Some("rnode_firmware_t3s3_sx1280_pa.zip") + ); + assert_eq!(model_info(0xFE).unwrap().firmware_filename, None); + assert_eq!(model_info(0xFF).unwrap().max_tx_power, 14); + } + + #[test] + fn tcxo_models_are_normalized_for_eeprom() { + assert_eq!(normalize_eeprom_model(MODEL_B4_TCXO), 0xB4); + assert_eq!(normalize_eeprom_model(MODEL_B9_TCXO), 0xB9); + assert_eq!(normalize_eeprom_model(0xA4), 0xA4); + } + + #[test] + fn names_match_upstream_spellings() { + assert_eq!(product_name(PRODUCT_HMBRW), Some("Hombrew RNode")); + assert_eq!(platform_name(PLATFORM_ESP32), Some("ESP32")); + assert_eq!(mcu_name(MCU_NRF52), Some("Nordic Semiconductor nRF52840")); + } +} diff --git a/crates/rns-tools/src/commands/rnodeconf/trust.rs b/crates/rns-tools/src/commands/rnodeconf/trust.rs new file mode 100644 index 0000000..16c3bcb --- /dev/null +++ b/crates/rns-tools/src/commands/rnodeconf/trust.rs @@ -0,0 +1,87 @@ +//! Trust-store and device-signing helpers for rnodeconf. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use rns_identity::identity::Identity; +use rns_interface::rnode_admin::{self, AdminFrame}; + +pub const SIGNING_KEY_RELATIVE_PATH: &[&str] = &["firmware", "signing.key"]; +pub const DEVICE_KEY_FILENAME: &str = "device.key"; + +pub fn trusted_key_filename(public_key_der: &[u8]) -> String { + format!( + "{}.pubkey", + hex::encode(rns_crypto::sha::sha256(public_key_der)) + ) +} + +pub fn trusted_key_path(root: &Path, public_key_der: &[u8]) -> PathBuf { + root.join("trusted_keys") + .join(trusted_key_filename(public_key_der)) +} + +pub fn write_trusted_key(root: &Path, public_key_der: &[u8]) -> io::Result { + let path = trusted_key_path(root, public_key_der); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&path, public_key_der)?; + Ok(path) +} + +pub fn signing_key_path(root: &Path) -> PathBuf { + SIGNING_KEY_RELATIVE_PATH + .iter() + .fold(root.to_path_buf(), |path, component| path.join(component)) +} + +pub fn device_key_path(root: &Path) -> PathBuf { + root.join(DEVICE_KEY_FILENAME) +} + +pub fn load_device_identity(path: &Path) -> Result { + Identity::from_file(path).map_err(|e| format!("could not load device identity: {e}")) +} + +pub fn sign_device_hash(identity: &Identity, device_hash: &[u8; 32]) -> Result<[u8; 64], String> { + identity + .sign(device_hash) + .ok_or_else(|| "device identity does not contain a private signing key".to_string()) +} + +pub fn device_signature_frame(signature: &[u8; 64]) -> AdminFrame { + rnode_admin::device_signature_frame(signature) +} + +pub fn firmware_hash_frame(hash: &[u8; 32]) -> AdminFrame { + rnode_admin::firmware_hash_frame(hash) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trusted_key_filename_is_sha256_pubkey_name() { + let der = b"not-real-der-but-stable"; + assert_eq!( + trusted_key_filename(der), + format!("{}.pubkey", hex::encode(rns_crypto::sha::sha256(der))) + ); + } + + #[test] + fn device_hash_signing_uses_reticulum_identity_key() { + let private = [7u8; 64]; + let identity = Identity::from_private_key(&private).unwrap(); + let device_hash = [9u8; 32]; + let signature = sign_device_hash(&identity, &device_hash).unwrap(); + assert!(identity.verify(&device_hash, &signature)); + assert_eq!( + device_signature_frame(&signature), + rnode_admin::device_signature_frame(&signature) + ); + } +} diff --git a/crates/rns-tools/src/commands/rnpath.rs b/crates/rns-tools/src/commands/rnpath.rs new file mode 100644 index 0000000..93ca09d --- /dev/null +++ b/crates/rns-tools/src/commands/rnpath.rs @@ -0,0 +1,1291 @@ +//! rnpath-rs — path and routing management. +//! +//! Local mode supports the full table/rate/blackhole surface via HMAC RPC +//! (TCP or shared Unix socket). +//! Remote mode (`-R -i `) is read-only (`--table` / `--rates`); +//! `-p ` fetches a remote transport's published blackhole list. + +use std::fmt; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +use clap::Parser; + +use rns_runtime::config::Config; +use rns_runtime::lifecycle::ShutdownSignal; +use rns_runtime::link_client::{LinkClient, LinkClientError}; +use rns_runtime::platform::resolve_config_dir; +use rns_runtime::reticulum::{ReticulumConfig, SharedInstanceRpcEndpoint, init}; +use rns_runtime::rpc::{self, RpcRequest, RpcResponse}; +use rns_tools::{format, hash}; + +const DEFAULT_TIMEOUT_SECS: u64 = 5; +const REMOTE_TIMEOUT_SECS: u64 = 30; +const REMOTE_HOPS: u8 = 8; +const MGMT_APP: &str = "rnstransport.remote.management"; +const BLACKHOLE_APP: &str = "rnstransport.info.blackhole"; +const RETICULUM_COMPAT_VERSION: &str = "1.2.2"; + +#[derive(Parser)] +#[command( + name = "rnpath-rs", + about = "Reticulum path management", + disable_version_flag = true +)] +struct Args { + /// Destination hash to request a path to. + destination: Option, + + /// Show the full path table. + #[arg(short, long)] + table: bool, + + /// Show announce rate-limiting table. + #[arg(short, long)] + rates: bool, + + /// Drop the path to a specific destination. + #[arg(short, long)] + drop: Option, + + /// Drop all queued announces on all interfaces. + #[arg(short = 'D', long)] + drop_announces: bool, + + /// Drop all paths routed via a specific transport identity. + #[arg(short = 'x', long)] + drop_via: Option, + + /// Filter path table by maximum hops. + #[arg(short, long)] + max: Option, + + /// List blackholed identities. + #[arg(short, long)] + blackholed: bool, + + /// View published blackhole list for remote transport instance. + #[arg(short = 'p', long = "blackholed-list")] + blackholed_list: bool, + + /// Blackhole an identity (pass its hash). + #[arg(short = 'B', long)] + blackhole: Option, + + /// Remove the blackhole on an identity. + #[arg(short = 'U', long)] + unblackhole: Option, + + /// Blackhole duration (hours, float). + #[arg(long)] + duration: Option, + + /// Reason to record on the blackhole entry. + #[arg(long)] + reason: Option, + + /// JSON output (machine-readable). + #[arg(short, long)] + json: bool, + + /// Alternative config directory. + #[arg(short = 'c', long)] + config: Option, + + /// Remote transport hash (32 hex chars). Query that node over Reticulum. + /// Only `--table` and `--rates` are supported in remote mode; mutations + /// are local-only. + #[arg(short = 'R', long = "remote")] + remote: Option, + + /// Identity file for remote authentication (used with `-R`). + #[arg(short = 'i', long)] + identity: Option, + + /// Seconds to wait for local shared-instance responses. + #[arg(short = 'w', long)] + timeout: Option, + + /// Seconds to wait for remote management responses. + #[arg(short = 'W', long = "remote-timeout")] + remote_timeout: Option, + + /// Print version and exit. + #[arg(long)] + version: bool, + + /// Increase verbosity. + #[arg(short, action = clap::ArgAction::Count)] + verbose: u8, + + /// Filter for remote blackhole list view. + list_filter: Option, +} + +#[tokio::main(flavor = "multi_thread", worker_threads = 2)] +pub(crate) async fn main() -> ExitCode { + let args = Args::parse(); + + if args.version { + println!("rnpath-rs {RETICULUM_COMPAT_VERSION}"); + return ExitCode::SUCCESS; + } + + let level = match args.verbose { + 0 => tracing::Level::WARN, + 1 => tracing::Level::INFO, + _ => tracing::Level::DEBUG, + }; + tracing_subscriber::fmt().with_max_level(level).init(); + + if args.blackholed_list { + return run_remote_blackhole_list(args).await; + } + + if args.remote.is_some() { + return run_remote(args).await; + } + + if !local_action_requested(&args) { + eprintln!("rnpath-rs: no action specified (use --help)"); + return ExitCode::from(2); + } + if let Err(e) = validate_local_hash_args(&args) { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + + let config_dir = resolve_config_dir(args.config.as_deref()); + let config_path = config_dir.join("config"); + let config = match Config::from_file(&config_path) { + Ok(c) => c, + Err(e) => { + eprintln!( + "rnpath-rs: could not read config at {}: {e}", + config_path.display() + ); + return ExitCode::from(1); + } + }; + let rc = ReticulumConfig::from_config(&config); + + let rpc_key = match local_rpc_key(&config_dir, &rc) { + Some(k) => k, + None => { + eprintln!( + "rnpath-rs: no rpc_key configured and no transport identity at {} — cannot query rnsd.", + config_path.display() + ); + return ExitCode::from(1); + } + }; + + let ctx = ClientCtx { + endpoint: rc.shared_rpc_endpoint(&std::env::temp_dir()), + config_dir, + rpc_key, + timeout: std::time::Duration::from_secs(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)), + }; + + // First matching branch wins when multiple action flags are passed. + if args.table { + return show_path_table(&ctx, args.max, args.json, args.destination.as_deref()).await; + } + if args.rates { + return show_rate_table(&ctx, args.json, args.destination.as_deref()).await; + } + if args.blackholed { + return show_blackholed(&ctx, args.json).await; + } + if let Some(dest_hex) = args.drop.as_deref() { + return drop_path(&ctx, dest_hex).await; + } + if args.drop_announces { + return drop_announces(&ctx).await; + } + if let Some(via_hex) = args.drop_via.as_deref() { + return drop_all_via(&ctx, via_hex).await; + } + if let Some(h) = args.blackhole.as_deref() { + return do_blackhole(&ctx, h, args.duration, args.reason).await; + } + if let Some(h) = args.unblackhole.as_deref() { + return do_unblackhole(&ctx, h).await; + } + if let Some(dest) = args.destination.as_deref() { + return query_path(&ctx, dest).await; + } + + unreachable!("local action was validated before config load") +} + +fn local_action_requested(args: &Args) -> bool { + args.table + || args.rates + || args.blackholed + || args.drop.is_some() + || args.drop_announces + || args.drop_via.is_some() + || args.blackhole.is_some() + || args.unblackhole.is_some() + || args.destination.is_some() +} + +fn validate_hash_arg(value: Option<&str>) -> Result<(), String> { + if let Some(value) = value { + hash::parse_dest_hash(value)?; + } + Ok(()) +} + +fn validate_local_hash_args(args: &Args) -> Result<(), String> { + validate_hash_arg(args.destination.as_deref())?; + validate_hash_arg(args.drop.as_deref())?; + validate_hash_arg(args.drop_via.as_deref())?; + validate_hash_arg(args.blackhole.as_deref())?; + validate_hash_arg(args.unblackhole.as_deref())?; + Ok(()) +} + +fn local_rpc_key(config_dir: &Path, rc: &ReticulumConfig) -> Option> { + if let Some(key) = rc.rpc_key.as_ref() { + return Some(key.clone()); + } + let paths = rns_runtime::platform::StoragePaths::from_config_dir(config_dir); + let identity = + rns_identity::identity::Identity::from_file(&paths.storage_dir.join("transport_identity")) + .ok()?; + let private_key = identity.get_private_key()?; + Some(rpc::derive_rpc_key(&*private_key).to_vec()) +} + +struct ClientCtx { + endpoint: SharedInstanceRpcEndpoint, + config_dir: PathBuf, + rpc_key: Vec, + timeout: std::time::Duration, +} + +async fn request(ctx: &ClientCtx, req: &RpcRequest) -> Result { + let result = match &ctx.endpoint { + SharedInstanceRpcEndpoint::Tcp(port) => { + rpc::connect_and_request(*port, &ctx.rpc_key, req, ctx.timeout).await + } + SharedInstanceRpcEndpoint::Unix(socket_path) => { + rpc::connect_unix_and_request(socket_path, &ctx.rpc_key, req, ctx.timeout).await + } + }; + result.map_err(|source| LocalRpcFailure { + endpoint: ctx.endpoint.clone(), + config_dir: ctx.config_dir.clone(), + source, + }) +} + +#[derive(Debug)] +struct LocalRpcFailure { + endpoint: SharedInstanceRpcEndpoint, + config_dir: PathBuf, + source: rns_runtime::rpc::RpcError, +} + +impl fmt::Display for LocalRpcFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + local_rpc_failure_message(&self.endpoint, &self.config_dir, &self.source) + ) + } +} + +impl std::error::Error for LocalRpcFailure {} + +fn local_rpc_failure_message( + endpoint: &SharedInstanceRpcEndpoint, + config_dir: &Path, + err: &rns_runtime::rpc::RpcError, +) -> String { + let endpoint = endpoint.display(); + let config_path = config_dir.join("config"); + let transport_identity_path = rns_runtime::platform::StoragePaths::from_config_dir(config_dir) + .storage_dir + .join("transport_identity"); + + match err { + rns_runtime::rpc::RpcError::AuthFailed => format!( + "local RPC authentication failed for rnsd-rs-compatible daemon at {endpoint}.\n\ + This usually means a config mismatch (different --config, rpc_key, or \ + transport_identity) or another app is owning the control port.\n\ + System Reticulum defaults are 37428/37429; Ratspeak app-private \ + configs use 37430/37431.\n\ + Config checked: {}.\n\ + If rpc_key is unset, the fallback key is derived from {}.", + config_path.display(), + transport_identity_path.display() + ), + rns_runtime::rpc::RpcError::Io(e) + if matches!( + e.kind(), + std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound + ) => + { + format!( + "could not connect to local rnsd-rs-compatible daemon at {endpoint}: {e}.\n\ + Start rnsd-rs with the same --config directory, or check \ + shared_instance_type and instance_control_port in {}. \ + System Reticulum defaults are 37428/37429; Ratspeak \ + app-private configs use 37430/37431.", + config_path.display() + ) + } + rns_runtime::rpc::RpcError::Io(e) if e.kind() == std::io::ErrorKind::TimedOut => { + format!( + "timed out while talking to local rnsd-rs-compatible daemon at {endpoint}: {e}.\n\ + If a process is listening there, it may not be rnsd-rs-compatible or may be using \ + a different local RPC auth key. Config checked: {}.", + config_path.display() + ) + } + _ => format!( + "could not query local rnsd-rs-compatible daemon at {endpoint} using {}: {err}", + config_path.display() + ), + } +} + +fn optional_dest_filter(value: Option<&str>) -> Result, String> { + value.map(hash::parse_dest_hash).transpose() +} + +async fn show_path_table( + ctx: &ClientCtx, + max_hops: Option, + json: bool, + destination_filter: Option<&str>, +) -> ExitCode { + let destination_filter = match optional_dest_filter(destination_filter) { + Ok(v) => v, + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + }; + let mut resp = match request(ctx, &RpcRequest::GetPathTable { max_hops }).await { + Ok(RpcResponse::PathTable(v)) => v, + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + return ExitCode::from(1); + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(1); + } + }; + if let Some(dest) = destination_filter { + resp.retain(|entry| entry.hash.as_slice() == dest); + } + + if json { + println!("{}", path_table_json(&resp)); + return ExitCode::SUCCESS; + } + + if resp.is_empty() { + println!("Path table is empty."); + return ExitCode::SUCCESS; + } + println!( + "{:<36} {:>5} {:<36} Interface", + "Destination", "Hops", "Via" + ); + for e in &resp { + let via = e + .via + .as_ref() + .map(hex::encode) + .unwrap_or_else(|| "-".to_string()); + println!( + "{:<36} {:>5} {:<36} {}", + hex::encode(&e.hash), + e.hops, + via, + e.interface + ); + } + ExitCode::SUCCESS +} + +async fn show_rate_table( + ctx: &ClientCtx, + json: bool, + destination_filter: Option<&str>, +) -> ExitCode { + let destination_filter = match optional_dest_filter(destination_filter) { + Ok(v) => v, + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + }; + let mut resp = match request(ctx, &RpcRequest::GetRateTable).await { + Ok(RpcResponse::RateTable(v)) => v, + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + return ExitCode::from(1); + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(1); + } + }; + if let Some(dest) = destination_filter { + resp.retain(|entry| entry.hash.as_slice() == dest); + } + + if json { + print!("["); + for (i, e) in resp.iter().enumerate() { + if i > 0 { + print!(","); + } + print!( + "{{\"hash\":\"{}\",\"violations\":{},\"blocked_until\":{}}}", + hex::encode(&e.hash), + e.rate_violations, + e.blocked_until + ); + } + println!("]"); + return ExitCode::SUCCESS; + } + + if resp.is_empty() { + println!("Rate table is empty."); + return ExitCode::SUCCESS; + } + println!( + "{:<36} {:>10} {:>12}", + "Destination", "Violations", "Blocked" + ); + for e in &resp { + let blocked = if e.blocked_until > 0.0 { + format::pretty_time(e.blocked_until - now_epoch()) + } else { + "-".to_string() + }; + println!( + "{:<36} {:>10} {:>12}", + hex::encode(&e.hash), + e.rate_violations, + blocked + ); + } + ExitCode::SUCCESS +} + +async fn show_blackholed(ctx: &ClientCtx, json: bool) -> ExitCode { + let resp = match request(ctx, &RpcRequest::GetBlackholedIdentities).await { + Ok(RpcResponse::BlackholeList(v)) => v, + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + return ExitCode::from(1); + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(1); + } + }; + + if json { + print!("["); + for (i, e) in resp.iter().enumerate() { + if i > 0 { + print!(","); + } + let reason = e.reason.as_deref().unwrap_or("manual"); + let until = e + .until + .map(|u| format!("{u}")) + .unwrap_or_else(|| "null".to_string()); + print!( + "{{\"identity\":\"{}\",\"reason\":\"{}\",\"until\":{}}}", + hex::encode(&e.identity_hash), + reason, + until + ); + } + println!("]"); + return ExitCode::SUCCESS; + } + + if resp.is_empty() { + println!("No identities are blackholed."); + return ExitCode::SUCCESS; + } + println!("Blackholed identities:"); + println!(" {:<32} {:<18} {:<10}", "identity", "reason", "expires"); + for e in &resp { + let reason = e.reason.as_deref().unwrap_or("manual"); + let expires = match e.until { + Some(u) => { + let now = now_epoch(); + let secs = (u - now) as i64; + if secs <= 0 { + "expired".to_string() + } else if secs >= 3600 { + format!("{}h", secs / 3600) + } else if secs >= 60 { + format!("{}m", secs / 60) + } else { + format!("{}s", secs) + } + } + None => "never".to_string(), + }; + println!( + " {:<32} {:<18} {:<10}", + hex::encode(&e.identity_hash), + reason, + expires + ); + } + ExitCode::SUCCESS +} + +async fn drop_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode { + let dest = match hash::parse_dest_hash(dest_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + }; + match request( + ctx, + &RpcRequest::DropPath { + destination_hash: dest.to_vec(), + }, + ) + .await + { + Ok(RpcResponse::Ok) => { + println!("Dropped path to {}", hex::encode(dest)); + ExitCode::SUCCESS + } + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + ExitCode::from(1) + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + ExitCode::from(1) + } + } +} + +async fn drop_announces(ctx: &ClientCtx) -> ExitCode { + match request(ctx, &RpcRequest::DropAnnounceQueues).await { + Ok(RpcResponse::Ok) => { + println!("All announce queues cleared."); + ExitCode::SUCCESS + } + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + ExitCode::from(1) + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + ExitCode::from(1) + } + } +} + +async fn drop_all_via(ctx: &ClientCtx, via_hex: &str) -> ExitCode { + let via = match hash::parse_dest_hash(via_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + }; + match request( + ctx, + &RpcRequest::DropAllVia { + transport_hash: via.to_vec(), + }, + ) + .await + { + Ok(RpcResponse::IntResult(n)) => { + println!( + "Dropped {n} path{} via {}", + if n == 1 { "" } else { "s" }, + hex::encode(via) + ); + ExitCode::SUCCESS + } + Ok(RpcResponse::Ok) => { + println!("Dropped all paths via {}", hex::encode(via)); + ExitCode::SUCCESS + } + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + ExitCode::from(1) + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + ExitCode::from(1) + } + } +} + +async fn do_blackhole( + ctx: &ClientCtx, + identity_hex: &str, + duration_hours: Option, + reason: Option, +) -> ExitCode { + let id = match hash::parse_dest_hash(identity_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + }; + let until = duration_hours.map(|h| now_epoch() + h * 3600.0); + match request( + ctx, + &RpcRequest::BlackholeIdentity { + identity_hash: id.to_vec(), + until, + reason, + }, + ) + .await + { + Ok(RpcResponse::Ok) => { + println!("Blackholed {}", hex::encode(id)); + ExitCode::SUCCESS + } + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + ExitCode::from(1) + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + ExitCode::from(1) + } + } +} + +async fn do_unblackhole(ctx: &ClientCtx, identity_hex: &str) -> ExitCode { + let id = match hash::parse_dest_hash(identity_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + }; + match request( + ctx, + &RpcRequest::UnblackholeIdentity { + identity_hash: id.to_vec(), + }, + ) + .await + { + Ok(RpcResponse::Ok) => { + println!("Removed blackhole on {}", hex::encode(id)); + ExitCode::SUCCESS + } + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + ExitCode::from(1) + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + ExitCode::from(1) + } + } +} + +async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode { + let dest = match hash::parse_dest_hash(dest_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(2); + } + }; + + let next_hop = match request( + ctx, + &RpcRequest::GetNextHop { + destination_hash: dest.to_vec(), + }, + ) + .await + { + Ok(RpcResponse::HashResult(Some(h))) => Some(h), + Ok(RpcResponse::HashResult(None)) => None, + Ok(other) => { + eprintln!("rnpath-rs: unexpected response: {other:?}"); + return ExitCode::from(1); + } + Err(e) => { + eprintln!("rnpath-rs: {e}"); + return ExitCode::from(1); + } + }; + + let iface = match request( + ctx, + &RpcRequest::GetNextHopIfName { + destination_hash: dest.to_vec(), + }, + ) + .await + { + Ok(RpcResponse::StringResult(s)) => s, + _ => None, + }; + + let path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await { + Ok(RpcResponse::PathTable(entries)) => entries + .into_iter() + .find(|entry| entry.hash.as_slice() == dest), + _ => None, + }; + + println!("Destination: {}", hex::encode(dest)); + match next_hop.as_ref() { + Some(h) => println!(" Next hop : {}", hex::encode(h)), + None if path_entry.is_some() => println!(" Next hop : (direct)"), + None => println!(" Next hop : (no known path)"), + } + if let Some(entry) = path_entry.as_ref() { + println!(" Hops : {}", entry.hops); + } + if let Some(i) = iface { + println!(" Interface: {i}"); + } + + if next_hop.is_none() && path_entry.is_none() { + println!( + " Note : no cached local path was found; active path requests are not implemented in rnpath yet" + ); + ExitCode::from(1) + } else { + ExitCode::SUCCESS + } +} + +fn path_table_json(entries: &[rpc::PathTableEntry]) -> String { + let mut out = String::from("["); + for (i, e) in entries.iter().enumerate() { + if i > 0 { + out.push(','); + } + let via = e + .via + .as_ref() + .map(|v| format!("\"{}\"", hex::encode(v))) + .unwrap_or_else(|| "null".to_string()); + out.push_str(&format!( + "{{\"hash\":\"{}\",\"hops\":{},\"via\":{},\"timestamp\":{},\"expires\":{},\"interface\":{:?}}}", + hex::encode(&e.hash), + e.hops, + via, + e.timestamp, + e.expires, + e.interface + )); + } + out.push(']'); + out +} + +fn now_epoch() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0) +} + +async fn run_remote_blackhole_list(args: Args) -> ExitCode { + let remote_hex = args.remote.as_deref().or(args.destination.as_deref()); + let Some(remote_hex) = remote_hex else { + eprintln!("rnpath-rs: -p requires a remote transport identity hash."); + return ExitCode::from(2); + }; + let remote_hash = match hash::parse_dest_hash(remote_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: remote blackhole source: {e}"); + return ExitCode::from(2); + } + }; + + let identity = match args.identity.as_ref() { + Some(path) => match rns_identity::identity::Identity::from_file(path) { + Ok(id) => id, + Err(e) => { + eprintln!( + "rnpath-rs: could not load identity from {}: {e:?}", + path.display() + ); + return ExitCode::from(1); + } + }, + None => rns_identity::identity::Identity::new(), + }; + + let shutdown = ShutdownSignal::new(); + let foreground = Arc::new(AtomicBool::new(true)); + let handle = match init(args.config.as_deref(), None, shutdown.clone(), foreground).await { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: failed to initialize Reticulum runtime: {e:?}"); + return ExitCode::from(1); + } + }; + + let timeout = Duration::from_secs( + args.remote_timeout + .or(args.timeout) + .unwrap_or(REMOTE_TIMEOUT_SECS), + ); + let client = LinkClient::new(handle.transport_tx.clone(), identity); + let response_bytes = match client + .query( + remote_hash, + BLACKHOLE_APP, + "/list", + Vec::new(), + REMOTE_HOPS, + timeout, + ) + .await + { + Ok(b) => b, + Err(e) => { + eprintln!( + "rnpath-rs: remote blackhole query failed: {}", + remote_err(&e) + ); + shutdown.trigger(); + return match e { + LinkClientError::Timeout(_) => ExitCode::from(124), + _ => ExitCode::from(1), + }; + } + }; + + let list_filter = args.list_filter.as_deref().or_else(|| { + if args.remote.is_some() { + args.destination.as_deref() + } else { + None + } + }); + let exit = print_remote_blackhole_list(&response_bytes, args.json, list_filter, remote_hash); + shutdown.trigger(); + exit +} + +fn print_remote_blackhole_list( + bytes: &[u8], + json: bool, + filter: Option<&str>, + publisher: [u8; 16], +) -> ExitCode { + let entries = match rns_transport::discovery::decode_manifest(bytes) { + Ok(entries) => entries, + Err(e) => { + eprintln!("rnpath-rs: malformed blackhole manifest: {e}"); + return ExitCode::from(1); + } + }; + + let filter_match = |identity: &[u8; 16], reason: &str, source: &[u8; 16]| { + filter.is_none_or(|needle| { + let haystack = format!( + "{} {} {}", + hex::encode(identity), + reason, + hex::encode(source) + ); + haystack.contains(needle) + }) + }; + let entries: Vec<_> = entries + .into_iter() + .filter(|(identity, entry)| filter_match(identity, &entry.reason, entry.source.as_bytes())) + .collect(); + + if json { + print!("["); + for (i, (identity, entry)) in entries.iter().enumerate() { + if i > 0 { + print!(","); + } + let until = entry + .until + .map(|u| u.to_string()) + .unwrap_or_else(|| "null".to_string()); + print!( + "{{\"identity\":\"{}\",\"until\":{},\"reason\":{:?},\"source\":\"{}\"}}", + hex::encode(identity), + until, + entry.reason, + hex::encode(entry.source.as_bytes()) + ); + } + println!("]"); + return ExitCode::SUCCESS; + } + + if entries.is_empty() { + println!("No blackholed identity data available."); + return ExitCode::SUCCESS; + } + + let now = now_epoch(); + for (identity, entry) in entries { + let until = match entry.until { + Some(u) => format!("for {}", format::pretty_time((u - now).max(0.0))), + None => "indefinitely".to_string(), + }; + let reason = if entry.reason.is_empty() { + String::new() + } else { + format!(" ({})", entry.reason) + }; + let by = if entry.source.as_bytes() == &publisher { + String::new() + } else { + format!(" by {}", hex::encode(entry.source.as_bytes())) + }; + println!("{} blackholed {until}{reason}{by}", hex::encode(identity)); + } + ExitCode::SUCCESS +} + +fn remote_mutation_flag(args: &Args) -> Option<&'static str> { + if args.drop.is_some() { + Some("--drop") + } else if args.drop_announces { + Some("--drop-announces") + } else if args.drop_via.is_some() { + Some("--drop-via") + } else if args.blackhole.is_some() { + Some("--blackhole") + } else if args.unblackhole.is_some() { + Some("--unblackhole") + } else { + None + } +} + +async fn run_remote(args: Args) -> ExitCode { + let remote_hex = args.remote.as_deref().expect("checked in main"); + let remote_hash = match hash::parse_dest_hash(remote_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: --remote: {e}"); + return ExitCode::from(2); + } + }; + + // Remote management protocol is read-only — reject any mutation flag. + if let Some(flag) = remote_mutation_flag(&args) { + eprintln!("rnpath-rs: {flag} is local-only in remote mode."); + eprintln!( + " Remote mode supports read-only --table and --rates queries; \ + path mutations and blackhole management are local-only \ + (no remote endpoint exists in the Reticulum management protocol)." + ); + return ExitCode::from(2); + } + if args.blackholed { + eprintln!("rnpath-rs: --blackholed is local-only (no remote endpoint)."); + return ExitCode::from(2); + } + if !args.table && !args.rates { + if args.destination.is_some() { + eprintln!( + "rnpath-rs: remote destination path requests are not implemented; use --table or --rates with the destination as a filter, or run the path request locally." + ); + } else { + eprintln!("rnpath-rs: remote mode requires --table or --rates."); + } + return ExitCode::from(2); + } + + let identity_path = match args.identity.as_ref() { + Some(p) => p.clone(), + None => { + eprintln!("rnpath-rs: --remote requires --identity ."); + return ExitCode::from(2); + } + }; + let identity = match rns_identity::identity::Identity::from_file(&identity_path) { + Ok(id) => id, + Err(e) => { + eprintln!( + "rnpath-rs: could not load identity from {}: {e:?}", + identity_path.display() + ); + return ExitCode::from(1); + } + }; + + let shutdown = ShutdownSignal::new(); + let foreground = Arc::new(AtomicBool::new(true)); + let handle = match init(args.config.as_deref(), None, shutdown.clone(), foreground).await { + Ok(h) => h, + Err(e) => { + eprintln!("rnpath-rs: failed to initialize Reticulum runtime: {e:?}"); + return ExitCode::from(1); + } + }; + + let timeout = Duration::from_secs( + args.remote_timeout + .or(args.timeout) + .unwrap_or(REMOTE_TIMEOUT_SECS), + ); + + // Wire payload: [command, destination, max_hops]. Destination filter not + // exposed by all older peers; max_hops is table-only. + let command = if args.table { "table" } else { "rates" }; + let mut req_args: Vec = vec![rmpv::Value::from(command)]; + if let Some(dest_hex) = args.destination.as_deref() { + let dest = match hash::parse_dest_hash(dest_hex) { + Ok(dest) => dest, + Err(e) => { + eprintln!("rnpath-rs: destination filter: {e}"); + shutdown.trigger(); + return ExitCode::from(2); + } + }; + req_args.push(rmpv::Value::Binary(dest.to_vec())); + } + if args.table + && let Some(m) = args.max + { + if args.destination.is_none() { + req_args.push(rmpv::Value::Nil); + } + req_args.push(rmpv::Value::from(m)); + } + let req_value = rmpv::Value::Array(req_args); + let mut payload = Vec::new(); + if let Err(e) = rmpv::encode::write_value(&mut payload, &req_value) { + eprintln!("rnpath-rs: msgpack encode failed: {e}"); + shutdown.trigger(); + return ExitCode::from(1); + } + + let client = LinkClient::new(handle.transport_tx.clone(), identity); + let response_bytes = match client + .query( + remote_hash, + MGMT_APP, + "/path", + payload, + REMOTE_HOPS, + timeout, + ) + .await + { + Ok(b) => b, + Err(e) => { + eprintln!("rnpath-rs: remote query failed: {}", remote_err(&e)); + shutdown.trigger(); + return match e { + LinkClientError::Timeout(_) => ExitCode::from(124), + _ => ExitCode::from(1), + }; + } + }; + + let exit = if args.table { + print_remote_path_table(&response_bytes, args.json) + } else { + print_remote_rate_table(&response_bytes, args.json) + }; + shutdown.trigger(); + exit +} + +fn print_remote_path_table(bytes: &[u8], json: bool) -> ExitCode { + let value: rmpv::Value = match rmp_serde::from_slice(bytes) { + Ok(v) => v, + Err(e) => { + eprintln!("rnpath-rs: malformed response: {e}"); + return ExitCode::from(1); + } + }; + let arr = match value.as_array() { + Some(a) => a, + None => { + eprintln!("rnpath-rs: response is not an array"); + return ExitCode::from(1); + } + }; + + if json { + print!("["); + for (i, entry) in arr.iter().enumerate() { + if i > 0 { + print!(","); + } + if let Some(m) = entry.as_map() { + let h = map_bin(m, "hash").unwrap_or_default(); + let via = map_bin(m, "via"); + let hops = map_u64(m, "hops").unwrap_or(0); + let iface = map_str(m, "interface").unwrap_or_default(); + let via_str = via + .map(|v| format!("\"{}\"", hex::encode(v))) + .unwrap_or_else(|| "null".to_string()); + print!( + "{{\"hash\":\"{}\",\"hops\":{hops},\"via\":{via_str},\"interface\":{:?}}}", + hex::encode(&h), + iface + ); + } + } + println!("]"); + return ExitCode::SUCCESS; + } + + if arr.is_empty() { + println!("Remote path table is empty."); + return ExitCode::SUCCESS; + } + println!( + "{:<36} {:>5} {:<36} Interface", + "Destination", "Hops", "Via" + ); + for entry in arr { + if let Some(m) = entry.as_map() { + let h = map_bin(m, "hash").unwrap_or_default(); + let via = map_bin(m, "via") + .map(hex::encode) + .unwrap_or_else(|| "-".to_string()); + let hops = map_u64(m, "hops").unwrap_or(0); + let iface = map_str(m, "interface").unwrap_or_default(); + println!("{:<36} {:>5} {:<36} {iface}", hex::encode(&h), hops, via); + } + } + ExitCode::SUCCESS +} + +fn print_remote_rate_table(bytes: &[u8], json: bool) -> ExitCode { + let value: rmpv::Value = match rmp_serde::from_slice(bytes) { + Ok(v) => v, + Err(e) => { + eprintln!("rnpath-rs: malformed response: {e}"); + return ExitCode::from(1); + } + }; + let arr = match value.as_array() { + Some(a) => a, + None => { + eprintln!("rnpath-rs: response is not an array"); + return ExitCode::from(1); + } + }; + + if json { + print!("["); + for (i, entry) in arr.iter().enumerate() { + if i > 0 { + print!(","); + } + if let Some(m) = entry.as_map() { + let h = map_bin(m, "hash").unwrap_or_default(); + let rate = map_f64(m, "rate").unwrap_or(0.0); + print!("{{\"hash\":\"{}\",\"rate\":{rate}}}", hex::encode(&h)); + } + } + println!("]"); + return ExitCode::SUCCESS; + } + + if arr.is_empty() { + println!("Remote rate table is empty."); + return ExitCode::SUCCESS; + } + println!("{:<36} {:>10}", "Destination", "Rate"); + for entry in arr { + if let Some(m) = entry.as_map() { + let h = map_bin(m, "hash").unwrap_or_default(); + let rate = map_f64(m, "rate").unwrap_or(0.0); + println!("{:<36} {:>10.4}", hex::encode(&h), rate); + } + } + ExitCode::SUCCESS +} + +fn remote_err(e: &LinkClientError) -> String { + match e { + LinkClientError::PubkeyNotDiscovered => { + "remote node not discovered (no announce received). \ + Verify the transport hash and that the local rnsd has connectivity." + .to_string() + } + LinkClientError::Timeout(stage) => format!("timeout while waiting for {stage}"), + other => other.to_string(), + } +} + +fn map_str(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_str().map(|s| s.to_string())) +} + +fn map_u64(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_u64()) +} + +fn map_f64(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_f64()) +} + +fn map_bin(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option> { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_slice().map(|s| s.to_vec())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn local_rpc_auth_failure_explains_config_mismatch_and_port_owner() { + let endpoint = SharedInstanceRpcEndpoint::Tcp(37429); + let msg = local_rpc_failure_message( + &endpoint, + Path::new("/tmp/rns-auth-test"), + &rns_runtime::rpc::RpcError::AuthFailed, + ); + + assert!(msg.contains("config mismatch")); + assert!(msg.contains("another app is owning the control port")); + assert!(msg.contains("rpc_key")); + assert!(msg.contains("transport_identity")); + assert!(msg.contains("37430/37431")); + } +} diff --git a/crates/rns-tools/src/commands/rnprobe.rs b/crates/rns-tools/src/commands/rnprobe.rs new file mode 100644 index 0000000..2fff6b5 --- /dev/null +++ b/crates/rns-tools/src/commands/rnprobe.rs @@ -0,0 +1,290 @@ +//! rnprobe-rs — send PROBE packets, measure RTT. +//! +//! Exit codes: 0 all delivered, 1 path timeout, 2 packet loss, 3 size > MTU. + +use std::process; +use std::time::Duration; + +use clap::Parser; + +use rns_runtime::probe::{ + ProbeError, ProbeOutcome, default_probe_app_name, parse_dest_hash, probe_once, +}; + +const DEFAULT_PROBE_SIZE: usize = 16; +const DEFAULT_TIMEOUT_SECS: f64 = 12.0; +const RETICULUM_COMPAT_VERSION: &str = "1.2.2"; + +#[derive(Parser)] +#[command( + name = "rnprobe-rs", + about = "Reticulum Probe Utility", + disable_version_flag = true +)] +struct Args { + /// Path to alternative Reticulum config directory + #[arg(long)] + config: Option, + + /// Size of probe packet payload in bytes + #[arg(short = 's', long)] + size: Option, + + /// Number of probes to send + #[arg(short = 'n', long, default_value_t = 1)] + probes: u32, + + /// Timeout before giving up (seconds) + #[arg(short = 't', long, value_name = "seconds")] + timeout: Option, + + /// Time between each probe (seconds) + #[arg(short = 'w', long, default_value_t = 0.0, value_name = "seconds")] + wait: f64, + + /// Output one JSON object per probe to stdout (machine-readable) + #[arg(long)] + json: bool, + + /// Increase verbosity + #[arg(short = 'v', long, action = clap::ArgAction::Count)] + verbose: u8, + + /// Print version and exit. + #[arg(long)] + version: bool, + + /// Full destination name in dotted notation (e.g. `rnstransport.probe`) + full_name: Option, + + /// Hexadecimal hash of the destination (32 hex chars) + destination_hash: Option, +} + +#[tokio::main] +pub(crate) async fn main() { + let args = Args::parse(); + if args.version { + println!("rnprobe-rs {RETICULUM_COMPAT_VERSION}"); + return; + } + + let Some(dest_hex) = args.destination_hash.clone() else { + // Print help on missing args (don't error). + let mut cmd = ::command(); + cmd.print_help().ok(); + println!(); + return; + }; + + let level = match args.verbose { + 0 => tracing::Level::WARN, + 1 => tracing::Level::INFO, + _ => tracing::Level::DEBUG, + }; + tracing_subscriber::fmt() + .with_max_level(level) + .with_writer(std::io::stderr) + .init(); + + let full_name = args + .full_name + .clone() + .unwrap_or_else(|| default_probe_app_name().to_string()); + + let dest_hash = match parse_dest_hash(&dest_hex) { + Ok(h) => h, + Err(_) => { + eprintln!( + "Destination length is invalid, must be 32 hexadecimal characters (16 bytes)." + ); + process::exit(1); + } + }; + + let size = args.size.unwrap_or(DEFAULT_PROBE_SIZE); + let timeout = Duration::from_secs_f64(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)); + let wait = Duration::from_secs_f64(args.wait.max(0.0)); + let path_wait = timeout; + + let shutdown = rns_runtime::lifecycle::ShutdownSignal::new(); + let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone()); + let is_foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let handle = match rns_runtime::reticulum::init( + args.config.as_deref(), + None, + shutdown.clone(), + is_foreground, + ) + .await + { + Ok(h) => h, + Err(e) => { + eprintln!("failed to start reticulum: {e}"); + process::exit(1); + } + }; + + let mut sent: u32 = 0; + let mut replies: u32 = 0; + let mut first = true; + let mut remaining = args.probes; + + while remaining > 0 { + if !first { + tokio::time::sleep(wait).await; + } + first = false; + + sent += 1; + let result = probe_once( + handle.transport_tx.clone(), + dest_hash, + &full_name, + size, + timeout, + path_wait, + handle.should_use_implicit_proof(), + ) + .await; + + match result { + Ok(outcome) => { + replies += 1; + if args.json { + print_json(sent, size, dest_hash, &full_name, Some(&outcome), None); + } else { + let via = outcome + .via + .map(|v| format!(" via <{}>", hex::encode(v))) + .unwrap_or_default(); + let iface = outcome + .interface + .as_deref() + .filter(|n| !n.is_empty()) + .map(|n| format!(" on {n}")) + .unwrap_or_default(); + println!( + "Sent probe {sent} ({size} bytes) to <{}>{via}{iface}", + hex::encode(dest_hash) + ); + let ms = if outcome.hops == 1 { "" } else { "s" }; + let rttstring = if outcome.rtt.as_secs_f64() >= 1.0 { + format!("{:.3} seconds", outcome.rtt.as_secs_f64()) + } else { + format!("{:.3} milliseconds", outcome.rtt.as_secs_f64() * 1000.0) + }; + println!( + "Valid reply from <{}>\nRound-trip time is {} over {} hop{}\n", + hex::encode(dest_hash), + rttstring, + outcome.hops, + ms + ); + } + } + Err(ProbeError::MtuExceeded(s, mtu)) => { + eprintln!("Error: Probe packet size of {s} bytes exceed MTU of {mtu} bytes"); + process::exit(3); + } + Err(ProbeError::PathTimeout) => { + if args.json { + print_json( + sent, + size, + dest_hash, + &full_name, + None, + Some("path_timeout"), + ); + } else { + println!("Path request timed out"); + } + process::exit(1); + } + Err(ProbeError::NoIdentity) => { + if args.json { + print_json(sent, size, dest_hash, &full_name, None, Some("no_identity")); + } else { + eprintln!( + "Destination's identity is not known — wait for an announce or use rnstatus to verify the destination has been seen." + ); + } + process::exit(1); + } + Err(ProbeError::PacketTimeout) => { + if args.json { + print_json( + sent, + size, + dest_hash, + &full_name, + None, + Some("packet_timeout"), + ); + } else { + println!("Probe timed out"); + } + } + Err(e) => { + eprintln!("probe error: {e}"); + process::exit(1); + } + } + + remaining -= 1; + } + + let loss_pct = if sent > 0 { + (1.0 - (replies as f64 / sent as f64)) * 100.0 + } else { + 0.0 + }; + let loss_rounded = (loss_pct * 100.0).round() / 100.0; + if !args.json { + println!("Sent {sent}, received {replies}, packet loss {loss_rounded}%"); + } + + if loss_rounded > 0.0 { + process::exit(2); + } + process::exit(0); +} + +fn print_json( + probe_num: u32, + size: usize, + dest_hash: [u8; 16], + full_name: &str, + outcome: Option<&ProbeOutcome>, + error: Option<&str>, +) { + use std::fmt::Write; + let mut out = String::new(); + write!( + out, + "{{\"probe\":{probe_num},\"size\":{size},\"destination\":\"{}\",\"name\":\"{}\"", + hex::encode(dest_hash), + full_name + ) + .ok(); + if let Some(o) = outcome { + write!( + out, + ",\"status\":\"ok\",\"rtt_ms\":{:.3},\"hops\":{}", + o.rtt.as_secs_f64() * 1000.0, + o.hops + ) + .ok(); + if let Some(via) = o.via { + write!(out, ",\"via\":\"{}\"", hex::encode(via)).ok(); + } + if let Some(ref iface) = o.interface { + write!(out, ",\"interface\":\"{iface}\"").ok(); + } + } else if let Some(err) = error { + write!(out, ",\"status\":\"error\",\"error\":\"{err}\"").ok(); + } + out.push('}'); + println!("{out}"); +} diff --git a/crates/rns-tools/src/commands/rnsd.rs b/crates/rns-tools/src/commands/rnsd.rs new file mode 100644 index 0000000..bb0bb2f --- /dev/null +++ b/crates/rns-tools/src/commands/rnsd.rs @@ -0,0 +1,466 @@ +//! rnsd-rs - Reticulum daemon. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufRead, Write}; +use std::path::{Path, PathBuf}; + +use clap::Parser; +use tracing_subscriber::fmt::MakeWriter; + +const RETICULUM_COMPAT_VERSION: &str = "1.2.2"; +const LOG_ROTATE_BYTES: u64 = 5 * 1024 * 1024; +const RNSD_EXAMPLE_CONFIG: &str = r#"# This is an example Reticulum config file. + +[reticulum] +enable_transport = No +share_instance = Yes +instance_name = default + +[logging] +loglevel = 4 + +[interfaces] + +[[Default Interface]] +type = AutoInterface +enabled = Yes + +[[UDP Interface]] +type = UDPInterface +enabled = no +listen_ip = 0.0.0.0 +listen_port = 4242 +forward_ip = 255.255.255.255 +forward_port = 4242 + +[[TCP Server Interface]] +type = TCPServerInterface +enabled = no +listen_ip = 0.0.0.0 +listen_port = 4242 + +[[TCP Client Interface]] +type = TCPClientInterface +enabled = no +target_host = 127.0.0.1 +target_port = 4242 + +[[I2P]] +type = I2PInterface +enabled = no +connectable = yes +peers = ykzlw5ujbaqc2xkec4cpvgyxj257wcrmmgkuxqmqcur7cq3w3lha.b32.i2p + +[[RNode LoRa Interface]] +type = RNodeInterface +enabled = no +port = /dev/ttyUSB0 +frequency = 867200000 +bandwidth = 125000 +txpower = 7 +spreadingfactor = 8 +codingrate = 5 +flow_control = False + +[[Packet Radio KISS Interface]] +type = KISSInterface +enabled = no +port = /dev/ttyUSB1 +speed = 115200 +databits = 8 +parity = none +stopbits = 1 +preamble = 150 +txtail = 10 +persistence = 200 +slottime = 20 +flow_control = false + +[[Packet Radio AX.25 KISS Interface]] +type = AX25KISSInterface +callsign = NO1CLL +ssid = 0 +enabled = no +port = /dev/ttyUSB2 +speed = 115200 +databits = 8 +parity = none +stopbits = 1 +flow_control = false +preamble = 150 +txtail = 10 +persistence = 200 +slottime = 20 +"#; + +#[derive(Parser)] +#[command( + name = "rnsd-rs", + about = "Reticulum Network Stack Daemon", + disable_version_flag = true +)] +struct Args { + /// Alternative config directory. + #[arg(long, short = 'c', hide_short_help = true)] + config: Option, + + /// Increase verbosity. + #[arg(short = 'v', long, action = clap::ArgAction::Count)] + verbose: u8, + + /// Decrease verbosity. + #[arg(short = 'q', long, action = clap::ArgAction::Count)] + quiet: u8, + + /// Run as service and log to /logfile. + #[arg(short = 's', long)] + service: bool, + + /// Drop into an interactive shell after initialisation. + #[arg(short = 'i', long)] + interactive: bool, + + /// Print verbose configuration example to stdout and exit. + #[arg(long)] + exampleconfig: bool, + + /// Print version and exit. + #[arg(long)] + version: bool, +} + +#[tokio::main] +pub(crate) async fn main() { + let args = Args::parse(); + + if args.version { + println!("rnsd-rs {RETICULUM_COMPAT_VERSION}"); + return; + } + + if args.exampleconfig { + print!("{RNSD_EXAMPLE_CONFIG}"); + return; + } + + let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref()); + let config_loglevel = read_config_loglevel(&config_dir).unwrap_or(4); + let verbosity = if args.service { + config_loglevel + } else { + config_loglevel + args.verbose as i32 - args.quiet as i32 + }; + let level = tracing_level(verbosity); + + if args.service { + if let Err(e) = fs::create_dir_all(&config_dir) { + eprintln!( + "rnsd-rs: failed to create config directory {}: {e}", + config_dir.display() + ); + std::process::exit(1); + } + let log_path = config_dir.join("logfile"); + if let Err(e) = rotate_log_if_needed(&log_path) { + eprintln!( + "rnsd-rs: failed to rotate logfile {}: {e}", + log_path.display() + ); + std::process::exit(1); + } + tracing_subscriber::fmt() + .with_max_level(level) + .with_writer(LogFileWriter { path: log_path }) + .init(); + } else { + tracing_subscriber::fmt().with_max_level(level).init(); + } + + tracing::info!("rnsd-rs {RETICULUM_COMPAT_VERSION} starting"); + + let shutdown = rns_runtime::lifecycle::ShutdownSignal::new(); + let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone()); + + let is_foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + match rns_runtime::reticulum::init( + args.config.as_deref(), + None, + shutdown.clone(), + is_foreground, + ) + .await + { + Ok(handle) => { + tracing::info!("reticulum started in {:?} mode", handle.instance_mode); + if args.interactive { + run_interactive_shell(handle.clone()).await; + shutdown.trigger(); + } + + shutdown.wait().await; + tracing::info!("rnsd-rs shutting down"); + } + Err(e) => { + tracing::error!("failed to start reticulum: {e}"); + std::process::exit(1); + } + } +} + +async fn run_interactive_shell(handle: rns_runtime::reticulum::ReticulumHandle) { + let _ = tokio::task::spawn_blocking(move || { + let stdin = io::stdin(); + let mut stdin = stdin.lock(); + let mut stdout = io::stdout(); + let _ = writeln!( + stdout, + "rnsd-rs {RETICULUM_COMPAT_VERSION} interactive console" + ); + let _ = writeln!( + stdout, + "Reticulum instance mode: {:?}", + handle.instance_mode + ); + let _ = writeln!(stdout, "Type exit() or press Ctrl-D to return."); + + let mut line = String::new(); + loop { + line.clear(); + let _ = write!(stdout, ">>> "); + let _ = stdout.flush(); + match stdin.read_line(&mut line) { + Ok(0) => { + let _ = writeln!(stdout); + break; + } + Ok(_) => { + let trimmed = line.trim(); + match trimmed { + "" => {} + "exit()" | "quit()" | "exit" | "quit" => break, + "__version__" => { + let _ = writeln!(stdout, "{RETICULUM_COMPAT_VERSION:?}"); + } + "reticulum.is_shared_instance" => { + let _ = writeln!( + stdout, + "{}", + py_bool( + handle.instance_mode + == rns_runtime::reticulum::InstanceMode::Shared + ) + ); + } + "reticulum.is_connected_to_shared_instance" => { + let _ = writeln!( + stdout, + "{}", + py_bool( + handle.instance_mode + == rns_runtime::reticulum::InstanceMode::Client + ) + ); + } + "reticulum.is_standalone_instance" => { + let _ = writeln!( + stdout, + "{}", + py_bool( + handle.instance_mode + == rns_runtime::reticulum::InstanceMode::Standalone + ) + ); + } + "reticulum.configdir" => { + let _ = writeln!(stdout, "{:?}", handle.config_dir.display().to_string()); + } + "reticulum.local_socket_path" => { + let _ = writeln!(stdout, "{:?}", handle.config.instance_name); + } + "reticulum.rpc_type" => { + let rpc_type = if handle.config.shared_instance_type + == rns_runtime::reticulum::SharedInstanceType::Unix + { + "AF_UNIX" + } else { + "AF_INET" + }; + let _ = writeln!(stdout, "{rpc_type:?}"); + } + "mode" | "instance_mode" => { + let _ = writeln!(stdout, "{:?}", handle.instance_mode); + } + "config" | "config_dir" => { + let _ = writeln!(stdout, "{}", handle.config_dir.display()); + } + "help" | "help()" => { + let _ = writeln!( + stdout, + "Available names: __version__, reticulum, mode, instance_mode, config, config_dir, exit()" + ); + } + other => { + if let Some(inner) = + other.strip_prefix("print(").and_then(|s| s.strip_suffix(')')) + { + write_interactive_print(&mut stdout, &handle, inner.trim()); + } else { + let _ = writeln!( + stdout, + "NameError: name '{}' is not defined", + other.replace('\'', "\\'") + ); + } + } + } + } + Err(e) => { + let _ = writeln!(stdout, "I/O error: {e}"); + break; + } + } + } + }) + .await; +} + +fn py_bool(value: bool) -> &'static str { + if value { "True" } else { "False" } +} + +fn write_interactive_print( + stdout: &mut io::Stdout, + handle: &rns_runtime::reticulum::ReticulumHandle, + expr: &str, +) { + let value = match expr { + "__version__" => Some(RETICULUM_COMPAT_VERSION.to_string()), + "reticulum.is_shared_instance" => Some( + py_bool(handle.instance_mode == rns_runtime::reticulum::InstanceMode::Shared) + .to_string(), + ), + "reticulum.is_connected_to_shared_instance" => Some( + py_bool(handle.instance_mode == rns_runtime::reticulum::InstanceMode::Client) + .to_string(), + ), + "reticulum.is_standalone_instance" => Some( + py_bool(handle.instance_mode == rns_runtime::reticulum::InstanceMode::Standalone) + .to_string(), + ), + _ => parse_string_literal(expr), + }; + let _ = writeln!(stdout, "{}", value.unwrap_or_else(|| expr.to_string())); +} + +fn parse_string_literal(value: &str) -> Option { + value + .strip_prefix('"') + .and_then(|s| s.strip_suffix('"')) + .or_else(|| value.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))) + .map(str::to_string) +} + +fn read_config_loglevel(config_dir: &Path) -> Option { + let config = rns_runtime::config::Config::from_file(&config_dir.join("config")).ok()?; + let section = config.section("logging")?; + section.get_int("loglevel").map(|v| v as i32) +} + +fn tracing_level(verbosity: i32) -> tracing::Level { + match verbosity { + i32::MIN..=1 => tracing::Level::ERROR, + 2 => tracing::Level::WARN, + 3..=4 => tracing::Level::INFO, + 5..=6 => tracing::Level::DEBUG, + _ => tracing::Level::TRACE, + } +} + +fn rotate_log_if_needed(path: &Path) -> std::io::Result<()> { + if path.metadata().map(|m| m.len()).unwrap_or(0) < LOG_ROTATE_BYTES { + return Ok(()); + } + let rotated = path.with_file_name("logfile.1"); + let _ = fs::remove_file(&rotated); + fs::rename(path, rotated) +} + +#[derive(Clone)] +struct LogFileWriter { + path: PathBuf, +} + +impl<'a> MakeWriter<'a> for LogFileWriter { + type Writer = Box; + + fn make_writer(&'a self) -> Self::Writer { + match OpenOptions::new() + .create(true) + .append(true) + .open(&self.path) + { + Ok(file) => Box::new(RotatingLogFile { + path: self.path.clone(), + file: Some(file), + }), + Err(_) => Box::new(std::io::stderr()), + } + } +} + +struct RotatingLogFile { + path: PathBuf, + file: Option, +} + +impl RotatingLogFile { + fn file_mut(&mut self) -> io::Result<&mut File> { + if self.file.is_none() { + self.file = Some( + OpenOptions::new() + .create(true) + .append(true) + .open(&self.path)?, + ); + } + Ok(self.file.as_mut().expect("log file was just opened")) + } + + fn rotate_if_needed(&mut self) -> io::Result<()> { + if self.path.metadata().map(|m| m.len()).unwrap_or(0) <= LOG_ROTATE_BYTES { + return Ok(()); + } + + if let Some(mut file) = self.file.take() { + file.flush()?; + } + + let rotated = self.path.with_file_name("logfile.1"); + let _ = fs::remove_file(&rotated); + match fs::rename(&self.path, &rotated) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + self.file = Some( + OpenOptions::new() + .create(true) + .append(true) + .open(&self.path)?, + ); + Ok(()) + } +} + +impl Write for RotatingLogFile { + fn write(&mut self, buf: &[u8]) -> io::Result { + let written = self.file_mut()?.write(buf)?; + self.rotate_if_needed()?; + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + self.file_mut()?.flush() + } +} diff --git a/crates/rns-tools/src/commands/rnsh.rs b/crates/rns-tools/src/commands/rnsh.rs new file mode 100644 index 0000000..12941f1 --- /dev/null +++ b/crates/rns-tools/src/commands/rnsh.rs @@ -0,0 +1,997 @@ +//! rnsh-rs - Reticulum remote shell utility. + +use std::io::{IsTerminal, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +#[cfg(test)] +use std::collections::HashSet; +#[cfg(test)] +use std::process::{Command as ProcessCommand, Stdio}; + +use clap::{ArgAction, CommandFactory, Parser}; +use rns_identity::destination::{DestType, Destination, Direction}; +use rns_identity::identity::Identity; +use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers}; +use rns_runtime::platform::{StoragePaths, resolve_config_dir}; +use rns_runtime::rnsh::{ + RnshClientConfig, RnshError, RnshListenerConfig, RnshWindowSize, rnsh_client_execute, + run_rnsh_listener, +}; +use tokio::sync::mpsc; + +const RNS_VERSION: &str = "1.2.2"; +const RNSH_PROTOCOL_VERSION: &str = "0.2.0"; +const APP_NAME: &str = "rnsh"; +const DEFAULT_SERVICE_NAME: &str = "default"; +const IDENTITY_HASH_HEX_LEN: usize = 32; + +#[derive(Debug, Parser, Clone)] +#[command( + name = "rnsh-rs", + about = "Reticulum Remote Shell Utility", + disable_version_flag = true, + after_help = "When specifying a command to execute, separate rnsh-rs options from the command and its arguments with --\n\nFor example:\n rnsh-rs -l -- /bin/bash --login\n rnsh-rs -- ls -la /tmp" +)] +struct Args { + #[arg(short = 'c', long = "config")] + config: Option, + #[arg(short = 'i', long = "identity")] + identity: Option, + #[arg(short = 'v', long = "verbose", action = ArgAction::Count)] + verbose: u8, + #[arg(short = 'q', long = "quiet", action = ArgAction::Count)] + quiet: u8, + #[arg(short = 'p', long = "print-identity")] + print_identity: bool, + #[arg(long = "version")] + version: bool, + + #[arg(short = 'l', long = "listen")] + listen: bool, + #[arg(short = 's', long = "service")] + service: Option, + #[arg(short = 'b', long = "announce", value_name = "PERIOD")] + announce: Option, + #[arg(short = 'a', long = "allowed", value_name = "HASH")] + allowed: Vec, + #[arg(short = 'n', long = "no-auth")] + no_auth: bool, + #[arg(short = 'A', long = "remote-command-as-args")] + remote_command_as_args: bool, + #[arg(short = 'C', long = "no-remote-command")] + no_remote_command: bool, + + #[arg(short = 'N', long = "no-id")] + no_id: bool, + #[arg(short = 'm', long = "mirror")] + mirror: bool, + #[arg(short = 'w', long = "timeout", value_name = "SECONDS")] + timeout: Option, + + destination: Option, + + #[arg(last = true)] + command: Vec, +} + +#[tokio::main] +pub(crate) async fn main() -> ExitCode { + let args = Args::parse(); + run(args).await +} + +async fn run(mut args: Args) -> ExitCode { + if args.version { + println!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"); + return ExitCode::SUCCESS; + } + + if args.listen && args.service.is_none() { + args.service = Some(DEFAULT_SERVICE_NAME.to_string()); + } + + if args.print_identity { + return match print_identity(&args) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("rnsh-rs: {e}"); + ExitCode::from(1) + } + }; + } + + if args.listen { + return run_listener(args).await; + } + + if args.destination.is_some() { + return run_initiator(args).await; + } + + let mut cmd = Args::command(); + println!(); + let _ = cmd.print_help(); + println!(); + ExitCode::from(1) +} + +async fn run_listener(args: Args) -> ExitCode { + init_logging(args.verbose, args.quiet); + + let handle = match start_reticulum(args.config.as_deref()).await { + Ok(handle) => handle, + Err(e) => { + eprintln!("rnsh-rs: failed to start reticulum: {e}"); + return ExitCode::from(1); + } + }; + let paths = StoragePaths::from_config_dir(&handle.config_dir); + let identity_path = identity_path(args.identity.as_deref(), &paths, args.service.as_deref()); + let identity = match load_or_create_identity(&identity_path) { + Ok(identity) => identity, + Err(e) => { + eprintln!("rnsh-rs: {e}"); + return ExitCode::from(1); + } + }; + + let mut allowed = match parse_allowed_identities(&args.allowed) { + Ok(allowed) => allowed, + Err(e) => { + eprintln!("rnsh-rs: {e}"); + return ExitCode::from(1); + } + }; + let allowed_identity_files = allowed_identity_file_candidates(); + allowed.extend(load_allowed_identity_files(&allowed_identity_files)); + + let cfg = RnshListenerConfig { + identity, + command: listener_default_command(&args.command), + allow_all: args.no_auth, + allowed, + allowed_identity_files, + allow_remote_command: !args.no_remote_command, + remote_command_as_args: args.remote_command_as_args, + announce_period: args.announce, + }; + + match run_rnsh_listener(handle.transport_tx.clone(), cfg).await { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("rnsh-rs: {e}"); + ExitCode::from(error_exit_code(&e)) + } + } +} + +async fn run_initiator(args: Args) -> ExitCode { + init_logging(args.verbose, args.quiet); + + let destination = match args.destination.as_deref().and_then(parse_hash16) { + Some(hash) => hash, + None => { + eprintln!("Invalid destination entered. Check your input."); + return ExitCode::from(1); + } + }; + + let handle = match start_reticulum(args.config.as_deref()).await { + Ok(handle) => handle, + Err(e) => { + eprintln!("rnsh-rs: failed to start reticulum: {e}"); + return ExitCode::from(1); + } + }; + let paths = StoragePaths::from_config_dir(&handle.config_dir); + let identity_path = identity_path(args.identity.as_deref(), &paths, None); + let identity = match load_or_create_identity(&identity_path) { + Ok(identity) => identity, + Err(e) => { + eprintln!("rnsh-rs: {e}"); + return ExitCode::from(1); + } + }; + + let pipe_stdin = !std::io::stdin().is_terminal(); + let pipe_stdout = !std::io::stdout().is_terminal(); + let pipe_stderr = !std::io::stderr().is_terminal(); + let (rows, cols, hpix, vpix) = terminal_window_size(); + let _terminal_mode = if pipe_stdin { + None + } else { + enter_raw_stdin_mode() + }; + let stdin_rx = Some(spawn_stdin_reader()); + let (stdout_tx, stdout_writer) = spawn_output_writer(false); + let (stderr_tx, stderr_writer) = spawn_output_writer(true); + let window_rx = spawn_window_size_watcher(); + + let timeout = Duration::from_secs_f64(args.timeout.unwrap_or(15.0).max(1.0)); + let cfg = RnshClientConfig { + identity, + destination_hash: destination, + command: args.command.clone(), + no_id: args.no_id, + timeout, + stdin_data: Vec::new(), + stdin_rx, + stdout_tx: Some(stdout_tx), + stderr_tx: Some(stderr_tx), + window_rx, + pipe_stdin, + pipe_stdout, + pipe_stderr, + term: std::env::var("TERM").ok(), + rows, + cols, + hpix, + vpix, + }; + + match rnsh_client_execute(handle.transport_tx.clone(), cfg).await { + Ok(outcome) => { + if let Err(e) = finish_output_writers(stdout_writer, stderr_writer).await { + eprintln!("rnsh-rs: {e}"); + return ExitCode::from(1); + } + ExitCode::from(remote_exit_code(outcome.return_code, args.mirror)) + } + Err(e) => { + let _ = finish_output_writers(stdout_writer, stderr_writer).await; + eprintln!("rnsh-rs: {e}"); + ExitCode::from(error_exit_code(&e)) + } + } +} + +async fn start_reticulum( + config_dir: Option<&Path>, +) -> Result { + let shutdown = ShutdownSignal::new(); + let _signal_rx = install_signal_handlers(shutdown.clone()); + let is_foreground = Arc::new(AtomicBool::new(true)); + let config = config_dir.and_then(|path| path.to_str()); + rns_runtime::reticulum::init(config, None, shutdown, is_foreground).await +} + +fn init_logging(verbose: u8, quiet: u8) { + let level = match (verbose as i32) - (quiet as i32) { + n if n >= 2 => tracing::Level::DEBUG, + 1 => tracing::Level::INFO, + 0 => tracing::Level::WARN, + _ => tracing::Level::ERROR, + }; + let _ = tracing_subscriber::fmt() + .with_max_level(level) + .with_writer(std::io::stderr) + .try_init(); +} + +fn terminal_window_size() -> (Option, Option, Option, Option) { + terminal_window_size_for_fds(&[0, 1, 2]) +} + +#[cfg(unix)] +struct TerminalModeGuard { + original: nix::libc::termios, +} + +#[cfg(unix)] +impl Drop for TerminalModeGuard { + fn drop(&mut self) { + unsafe { + nix::libc::tcsetattr(0, nix::libc::TCSANOW, &self.original); + } + } +} + +#[cfg(unix)] +fn enter_raw_stdin_mode() -> Option { + let mut original = std::mem::MaybeUninit::::uninit(); + let rc = unsafe { nix::libc::tcgetattr(0, original.as_mut_ptr()) }; + if rc == -1 { + return None; + } + let original = unsafe { original.assume_init() }; + let mut raw = original; + unsafe { + nix::libc::cfmakeraw(&mut raw); + } + let rc = unsafe { nix::libc::tcsetattr(0, nix::libc::TCSANOW, &raw) }; + if rc == -1 { + return None; + } + Some(TerminalModeGuard { original }) +} + +#[cfg(not(unix))] +fn enter_raw_stdin_mode() -> Option<()> { + None +} + +fn spawn_stdin_reader() -> mpsc::Receiver> { + let (tx, rx) = mpsc::channel(16); + std::thread::spawn(move || { + let mut stdin = std::io::stdin(); + let mut buf = [0u8; 1024]; + loop { + match stdin.read(&mut buf) { + Ok(0) => { + let _ = tx.blocking_send(Vec::new()); + break; + } + Ok(n) => { + if tx.blocking_send(buf[..n].to_vec()).is_err() { + break; + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => { + let _ = tx.blocking_send(Vec::new()); + break; + } + } + } + }); + rx +} + +fn spawn_output_writer( + stderr: bool, +) -> ( + mpsc::Sender>, + tokio::task::JoinHandle>, +) { + let (tx, mut rx) = mpsc::channel::>(64); + let task = tokio::task::spawn_blocking(move || { + if stderr { + let stderr = std::io::stderr(); + let mut handle = stderr.lock(); + while let Some(chunk) = rx.blocking_recv() { + handle + .write_all(&chunk) + .map_err(|e| format!("could not write stderr: {e}"))?; + handle + .flush() + .map_err(|e| format!("could not flush stderr: {e}"))?; + } + } else { + let stdout = std::io::stdout(); + let mut handle = stdout.lock(); + while let Some(chunk) = rx.blocking_recv() { + handle + .write_all(&chunk) + .map_err(|e| format!("could not write stdout: {e}"))?; + handle + .flush() + .map_err(|e| format!("could not flush stdout: {e}"))?; + } + } + Ok(()) + }); + (tx, task) +} + +async fn finish_output_writers( + stdout_writer: tokio::task::JoinHandle>, + stderr_writer: tokio::task::JoinHandle>, +) -> Result<(), String> { + let (stdout, stderr) = tokio::join!(stdout_writer, stderr_writer); + stdout.map_err(|e| format!("stdout writer task failed: {e}"))??; + stderr.map_err(|e| format!("stderr writer task failed: {e}"))??; + Ok(()) +} + +#[cfg(unix)] +fn spawn_window_size_watcher() -> Option> { + let (tx, rx) = mpsc::channel(8); + tokio::spawn(async move { + let Ok(mut sigwinch) = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::window_change()) + else { + return; + }; + while sigwinch.recv().await.is_some() { + let (rows, cols, hpix, vpix) = terminal_window_size(); + if tx + .send(RnshWindowSize { + rows, + cols, + hpix, + vpix, + }) + .await + .is_err() + { + break; + } + } + }); + Some(rx) +} + +#[cfg(not(unix))] +fn spawn_window_size_watcher() -> Option> { + None +} + +#[cfg(unix)] +fn terminal_window_size_for_fds( + fds: &[i32], +) -> (Option, Option, Option, Option) { + for fd in fds { + let mut winsize = nix::libc::winsize { + ws_row: 0, + ws_col: 0, + ws_xpixel: 0, + ws_ypixel: 0, + }; + let rc = unsafe { nix::libc::ioctl(*fd, nix::libc::TIOCGWINSZ, &mut winsize) }; + if rc == 0 && (winsize.ws_row != 0 || winsize.ws_col != 0) { + return ( + Some(u32::from(winsize.ws_row)), + Some(u32::from(winsize.ws_col)), + Some(u32::from(winsize.ws_xpixel)), + Some(u32::from(winsize.ws_ypixel)), + ); + } + } + (None, None, None, None) +} + +#[cfg(not(unix))] +fn terminal_window_size_for_fds( + _fds: &[i32], +) -> (Option, Option, Option, Option) { + (None, None, None, None) +} + +fn error_exit_code(error: &RnshError) -> u8 { + match error { + RnshError::PathTimeout | RnshError::NoIdentity | RnshError::Timeout(_) => 1, + RnshError::Remote(_) => 255, + _ => 1, + } +} + +fn print_identity(args: &Args) -> Result<(), String> { + let config_dir = resolve_config_dir(args.config.as_deref().and_then(Path::to_str)); + let paths = StoragePaths::from_config_dir(&config_dir); + paths + .ensure_dirs() + .map_err(|e| format!("could not prepare Reticulum storage: {e}"))?; + + let identity_path = identity_path(args.identity.as_deref(), &paths, args.service.as_deref()); + let identity = load_or_create_identity(&identity_path)?; + let destination = Destination::new(Some(&identity), Direction::In, DestType::Single, APP_NAME) + .map_err(|e| format!("could not create rnsh destination: {e}"))?; + + if let Some(service) = args + .service + .as_deref() + .filter(|service| !service.is_empty()) + { + println!("Using service name \"{service}\""); + } + println!("Identity : {}", hex::encode(identity.hash)); + if args.listen { + println!("Listening on : {}", hex::encode(destination.hash)); + } + Ok(()) +} + +fn load_or_create_identity(path: &Path) -> Result { + if path.is_file() { + return Identity::from_file(path) + .map_err(|e| format!("could not load identity {}: {e}", path.display())); + } + + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| { + format!( + "could not create identity directory {}: {e}", + parent.display() + ) + })?; + } + let identity = Identity::new(); + identity + .to_file(path) + .map_err(|e| format!("could not write identity {}: {e}", path.display()))?; + Ok(identity) +} + +fn identity_path(explicit: Option<&Path>, paths: &StoragePaths, service: Option<&str>) -> PathBuf { + if let Some(path) = explicit { + return path.to_path_buf(); + } + let mut name = APP_NAME.to_string(); + let service = sanitize_service_name(service.unwrap_or("")); + if !service.is_empty() { + name.push('.'); + name.push_str(&service); + } + paths.identity_dir.join(name) +} + +fn sanitize_service_name(service: &str) -> String { + service + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg(test)] +enum LocalProcessMode { + Pipes, + Pty, +} + +#[cfg(test)] +fn local_process_mode(pipe_stdin: bool, pipe_stdout: bool, pipe_stderr: bool) -> LocalProcessMode { + if pipe_stdin && pipe_stdout && pipe_stderr { + LocalProcessMode::Pipes + } else { + LocalProcessMode::Pty + } +} + +fn env_nonempty(name: &str) -> Option { + std::env::var(name).ok().filter(|value| !value.is_empty()) +} + +fn default_shell_command() -> Vec { + #[cfg(windows)] + let shell = env_nonempty("COMSPEC") + .or_else(|| env_nonempty("SHELL")) + .unwrap_or_else(|| "cmd.exe".to_string()); + + #[cfg(not(windows))] + let shell = env_nonempty("SHELL").unwrap_or_else(|| "/bin/sh".to_string()); + + vec![shell] +} + +fn listener_default_command(command: &[String]) -> Vec { + if command.is_empty() { + default_shell_command() + } else { + command.to_vec() + } +} + +#[cfg(test)] +fn select_listener_command( + default_command: &[String], + remote_command: Option<&[String]>, + allow_remote_command: bool, + remote_command_as_args: bool, +) -> Result, String> { + let remote_command = remote_command.unwrap_or(&[]); + let has_remote_command = !remote_command.is_empty(); + + if !allow_remote_command && has_remote_command { + return Err("Remote command line not allowed by listener".to_string()); + } + + if default_command.is_empty() && (!has_remote_command || remote_command_as_args) { + return Err("no command configured for listener".to_string()); + } + + if remote_command_as_args && has_remote_command { + let mut command = default_command.to_vec(); + command.extend_from_slice(remote_command); + return Ok(command); + } + + if has_remote_command { + Ok(remote_command.to_vec()) + } else { + Ok(default_command.to_vec()) + } +} + +#[derive(Debug, Clone)] +#[cfg(test)] +struct ListenerAuth { + allow_all: bool, + allowed: HashSet<[u8; 16]>, +} + +#[cfg(test)] +impl ListenerAuth { + fn from_flags(no_auth: bool, allowed: &[String]) -> Result { + let mut parsed = HashSet::new(); + for item in allowed { + parsed.insert(parse_identity_hash(item)?); + } + Ok(Self { + allow_all: no_auth, + allowed: parsed, + }) + } + + fn is_allowed(&self, identity_hash: Option<[u8; 16]>) -> bool { + self.allow_all + || identity_hash + .as_ref() + .is_some_and(|hash| self.allowed.contains(hash)) + } +} + +fn parse_identity_hash(input: &str) -> Result<[u8; 16], String> { + let trimmed = input.trim(); + if trimmed.len() != IDENTITY_HASH_HEX_LEN { + return Err(format!( + "identity hash must be {IDENTITY_HASH_HEX_LEN} hexadecimal characters" + )); + } + let decoded = hex::decode(trimmed).map_err(|_| "identity hash is not valid hex".to_string())?; + let mut hash = [0u8; 16]; + hash.copy_from_slice(&decoded); + Ok(hash) +} + +fn parse_hash16(input: &str) -> Option<[u8; 16]> { + if input.len() != IDENTITY_HASH_HEX_LEN { + return None; + } + let decoded = hex::decode(input).ok()?; + let mut hash = [0u8; 16]; + hash.copy_from_slice(decoded.get(..16)?); + Some(hash) +} + +fn parse_allowed_identities(values: &[String]) -> Result, String> { + values + .iter() + .map(|value| parse_identity_hash(value)) + .collect() +} + +fn allowed_identity_file_candidates() -> Vec { + let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else { + return Vec::new(); + }; + vec![ + home.join(".config/rnsh/allowed_identities"), + home.join(".rnsh/allowed_identities"), + ] +} + +fn load_allowed_identity_files(candidates: &[PathBuf]) -> Vec<[u8; 16]> { + let Some(path) = candidates.iter().find(|path| path.is_file()) else { + return Vec::new(); + }; + let Ok(content) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + content + .replace('\r', "") + .lines() + .filter_map(|line| parse_hash16(line.trim())) + .collect() +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg(test)] +struct LocalProcessResult { + stdout: Vec, + stderr: Vec, + return_code: i32, +} + +#[cfg(test)] +fn run_local_process_once( + command: &[String], + stdin_data: &[u8], + pipe_stdin: bool, + pipe_stdout: bool, + pipe_stderr: bool, + term: Option<&str>, + remote_identity_hash: Option<[u8; 16]>, +) -> Result { + if command.is_empty() { + return Err("no command specified".to_string()); + } + + match local_process_mode(pipe_stdin, pipe_stdout, pipe_stderr) { + LocalProcessMode::Pipes => {} + LocalProcessMode::Pty => { + return Err("local test helper only supports all-pipe mode".to_string()); + } + } + + let mut child = ProcessCommand::new(&command[0]) + .args(&command[1..]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .env("TERM", term.unwrap_or("xterm")) + .env( + "RNS_REMOTE_IDENTITY", + remote_identity_hash + .map(|hash| format!("<{}>", hex::encode(hash))) + .unwrap_or_default(), + ) + .spawn() + .map_err(|e| format!("could not start {}: {e}", command[0]))?; + + if let Some(mut stdin) = child.stdin.take() { + stdin + .write_all(stdin_data) + .map_err(|e| format!("could not write process stdin: {e}"))?; + } + + let output = child + .wait_with_output() + .map_err(|e| format!("could not wait for process: {e}"))?; + Ok(LocalProcessResult { + stdout: output.stdout, + stderr: output.stderr, + return_code: output.status.code().unwrap_or(255), + }) +} + +fn remote_exit_code(return_code: i64, mirror: bool) -> u8 { + if mirror { + return_code.clamp(0, u8::MAX as i64) as u8 + } else { + 0 + } +} + +fn _rnsh_config_dir(home: &Path, dot_config_exists: bool, _dot_rnsh_exists: bool) -> PathBuf { + if dot_config_exists { + home.join(".config/rnsh") + } else { + home.join(".rnsh") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(args: &[&str]) -> Args { + Args::parse_from(std::iter::once("rnsh").chain(args.iter().copied())) + } + + #[cfg(windows)] + fn local_pipe_test_command(script: &str) -> Vec { + vec![ + "powershell.exe".to_string(), + "-NoProfile".to_string(), + "-NonInteractive".to_string(), + "-Command".to_string(), + script.to_string(), + ] + } + + #[cfg(not(windows))] + fn local_pipe_test_command(script: &str) -> Vec { + vec!["/bin/sh".to_string(), "-c".to_string(), script.to_string()] + } + + #[test] + fn parser_accepts_upstream_flag_surface() { + let args = parse(&[ + "--config", + "/tmp/rns", + "--identity", + "/tmp/id", + "-vv", + "-q", + "-p", + "-l", + "-s", + "svc.name", + "-b", + "30", + "-a", + "00112233445566778899aabbccddeeff", + "-a", + "ffeeddccbbaa99887766554433221100", + "-n", + "-A", + "-C", + "-N", + "-m", + "-w", + "1.5", + "--", + "sh", + "-lc", + "echo hi", + ]); + + assert_eq!(args.config, Some(PathBuf::from("/tmp/rns"))); + assert_eq!(args.identity, Some(PathBuf::from("/tmp/id"))); + assert_eq!(args.verbose, 2); + assert_eq!(args.quiet, 1); + assert!(args.print_identity); + assert!(args.listen); + assert_eq!(args.service.as_deref(), Some("svc.name")); + assert_eq!(args.announce, Some(30)); + assert_eq!(args.allowed.len(), 2); + assert!(args.no_auth); + assert!(args.remote_command_as_args); + assert!(args.no_remote_command); + assert!(args.no_id); + assert!(args.mirror); + assert_eq!(args.timeout, Some(1.5)); + assert_eq!(args.command, vec!["sh", "-lc", "echo hi"]); + } + + #[test] + fn parser_accepts_initiator_destination_and_command() { + let args = parse(&["00112233445566778899aabbccddeeff", "--", "ls", "-la"]); + assert_eq!( + args.destination.as_deref(), + Some("00112233445566778899aabbccddeeff") + ); + assert_eq!(args.command, vec!["ls", "-la"]); + } + + #[test] + fn service_defaults_only_in_listener_mode() { + let mut listener = parse(&["-l"]); + if listener.listen && listener.service.is_none() { + listener.service = Some(DEFAULT_SERVICE_NAME.to_string()); + } + assert_eq!(listener.service.as_deref(), Some("default")); + + let initiator = parse(&["00112233445566778899aabbccddeeff"]); + assert_eq!(initiator.service, None); + } + + #[test] + fn identity_paths_match_upstream_service_suffix() { + let paths = StoragePaths::from_config_dir(Path::new("/tmp/reticulum")); + assert_eq!( + identity_path(None, &paths, Some("default")), + PathBuf::from("/tmp/reticulum/storage/identities/rnsh.default") + ); + assert_eq!( + identity_path(None, &paths, Some("svc/name!")), + PathBuf::from("/tmp/reticulum/storage/identities/rnsh.svcname") + ); + assert_eq!( + identity_path(Some(Path::new("/tmp/custom")), &paths, None), + PathBuf::from("/tmp/custom") + ); + } + + #[test] + fn version_string_uses_rust_command_name() { + assert_eq!( + format!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"), + "rnsh-rs 1.2.2 (protocol 0.2.0)" + ); + } + + #[test] + fn listener_command_policy_matches_upstream_modes() { + let default = vec!["/bin/sh".to_string(), "-lc".to_string()]; + let remote = vec!["echo".to_string(), "remote".to_string()]; + + assert_eq!( + select_listener_command(&default, None, false, false).unwrap(), + default + ); + assert_eq!( + select_listener_command(&default, Some(&remote), true, false).unwrap(), + remote + ); + assert_eq!( + select_listener_command(&default, Some(&remote), true, true).unwrap(), + vec!["/bin/sh", "-lc", "echo", "remote"] + ); + assert!( + select_listener_command(&default, Some(&remote), false, false) + .unwrap_err() + .contains("not allowed") + ); + } + + #[test] + fn listener_default_command_uses_explicit_command_or_shell_fallback() { + let explicit = vec!["/usr/bin/env".to_string(), "sh".to_string()]; + assert_eq!(listener_default_command(&explicit), explicit); + assert!(!listener_default_command(&[]).is_empty()); + } + + #[test] + fn listener_auth_allows_no_auth_or_configured_identity_only() { + let allowed_hash = "00112233445566778899aabbccddeeff".to_string(); + let allowed = parse_identity_hash(&allowed_hash).unwrap(); + let denied = parse_identity_hash("ffeeddccbbaa99887766554433221100").unwrap(); + + let auth = ListenerAuth::from_flags(false, std::slice::from_ref(&allowed_hash)).unwrap(); + assert!(auth.is_allowed(Some(allowed))); + assert!(!auth.is_allowed(Some(denied))); + assert!(!auth.is_allowed(None)); + + let no_auth = ListenerAuth::from_flags(true, &[]).unwrap(); + assert!(no_auth.is_allowed(None)); + assert!(no_auth.is_allowed(Some(denied))); + } + + #[test] + fn listener_auth_rejects_malformed_identity_hashes() { + assert!(parse_identity_hash("001122").is_err()); + assert!(parse_identity_hash("zz112233445566778899aabbccddeeff").is_err()); + } + + #[test] + fn local_process_mode_selects_pipes_only_when_all_streams_are_piped() { + assert_eq!( + local_process_mode(true, true, true), + LocalProcessMode::Pipes + ); + assert_eq!(local_process_mode(false, true, true), LocalProcessMode::Pty); + assert_eq!(local_process_mode(true, false, true), LocalProcessMode::Pty); + assert_eq!(local_process_mode(true, true, false), LocalProcessMode::Pty); + } + + #[test] + fn local_pipe_process_streams_stdin_stdout_stderr_and_exit() { + #[cfg(windows)] + let command = local_pipe_test_command( + r#"$line = [Console]::In.ReadLine(); [Console]::Out.Write("out:$line`n"); [Console]::Error.Write("err:$line`n"); exit 7"#, + ); + #[cfg(not(windows))] + let command = local_pipe_test_command( + "read line; printf 'out:%s\\n' \"$line\"; printf 'err:%s\\n' \"$line\" >&2; exit 7", + ); + let result = + run_local_process_once(&command, b"hello\n", true, true, true, Some("vt100"), None) + .unwrap(); + + assert_eq!(result.stdout, b"out:hello\n"); + assert_eq!(result.stderr, b"err:hello\n"); + assert_eq!(result.return_code, 7); + } + + #[test] + fn local_pipe_process_sets_term_and_remote_identity_env() { + let remote = parse_identity_hash("00112233445566778899aabbccddeeff").unwrap(); + #[cfg(windows)] + let command = local_pipe_test_command( + r#"[Console]::Out.Write($env:TERM + "/" + $env:RNS_REMOTE_IDENTITY)"#, + ); + #[cfg(not(windows))] + let command = local_pipe_test_command("printf '%s/%s' \"$TERM\" \"$RNS_REMOTE_IDENTITY\""); + let result = + run_local_process_once(&command, b"", true, true, true, Some("ansi"), Some(remote)) + .unwrap(); + + assert_eq!( + String::from_utf8(result.stdout).unwrap(), + "ansi/<00112233445566778899aabbccddeeff>" + ); + assert!(result.stderr.is_empty()); + assert_eq!(result.return_code, 0); + } + + #[test] + fn local_process_helper_rejects_non_pipe_mode() { + let command = local_pipe_test_command(""); + let err = run_local_process_once(&command, b"", false, true, true, None, None).unwrap_err(); + assert!(err.contains("all-pipe")); + } + + #[test] + fn mirrored_remote_exit_matches_upstream_cli_flag() { + assert_eq!(remote_exit_code(7, false), 0); + assert_eq!(remote_exit_code(7, true), 7); + assert_eq!(remote_exit_code(300, true), 255); + assert_eq!(remote_exit_code(-1, true), 0); + } +} diff --git a/crates/rns-tools/src/commands/rnstatus.rs b/crates/rns-tools/src/commands/rnstatus.rs new file mode 100644 index 0000000..1516c7c --- /dev/null +++ b/crates/rns-tools/src/commands/rnstatus.rs @@ -0,0 +1,1179 @@ +//! rnstatus-rs — interface status viewer. +//! +//! Local: HMAC RPC to local rnsd (TCP or shared Unix socket). Remote +//! (`-R -i `): Link to `rnstransport.remote.management` +//! `/status`; remote must allow-list our identity hash. + +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +use clap::Parser; +use serde_json::json; + +use rns_runtime::config::Config; +use rns_runtime::lifecycle::ShutdownSignal; +use rns_runtime::link_client::{LinkClient, LinkClientError}; +use rns_runtime::platform::StoragePaths; +use rns_runtime::platform::resolve_config_dir; +use rns_runtime::reticulum::{ReticulumConfig, SharedInstanceRpcEndpoint, init}; +use rns_runtime::rpc::{self, RpcRequest, RpcResponse}; +use rns_tools::{format, hash}; +use rns_transport::discovery::{DiscoveredInterface, DiscoveryStore}; + +const DEFAULT_TIMEOUT_SECS: u64 = 5; +const REMOTE_TIMEOUT_SECS: u64 = 30; +const REMOTE_HOPS: u8 = 8; +const MGMT_APP: &str = "rnstransport.remote.management"; +const RETICULUM_COMPAT_VERSION: &str = "1.2.2"; + +#[derive(Parser)] +#[command( + name = "rnstatus-rs", + about = "Reticulum interface status", + disable_version_flag = true +)] +struct Args { + /// Show all interfaces (including internal / disabled). + #[arg(short, long)] + all: bool, + + /// Show announce queue / frequency stats. + #[arg(short = 'A', long)] + announce_stats: bool, + + /// Show link table entry count. + #[arg(short, long)] + link_stats: bool, + + /// Display traffic totals. + #[arg(short, long)] + totals: bool, + + /// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held. + #[arg(short, long)] + sort: Option, + + /// Reverse sorting. + #[arg(short, long)] + reverse: bool, + + /// JSON output (machine-readable). + #[arg(short, long)] + json: bool, + + /// Alternative config directory. + #[arg(short = 'c', long)] + config: Option, + + /// Remote transport hash (32 hex chars). Query that node over Reticulum. + #[arg(short = 'R', long = "remote")] + remote: Option, + + /// Identity file used to authenticate to the remote node (required with `-R`). + #[arg(short = 'i', long)] + identity: Option, + + /// Seconds to wait for the response (default 5 local, 30 remote). + #[arg(short = 'w', long)] + timeout: Option, + + /// List discovered interfaces from the local discovery store. + #[arg(short = 'd', long)] + discovered: bool, + + /// Show details and config data for discovered interfaces. + #[arg(short = 'D')] + discovered_details: bool, + + /// Continuously monitor status. + #[arg(short = 'm', long)] + monitor: bool, + + /// Refresh interval for monitor mode, in seconds. + #[arg(short = 'I', long = "monitor-interval", default_value_t = 1.0)] + monitor_interval: f64, + + /// Print version and exit. + #[arg(long)] + version: bool, + + /// Increase verbosity (info level by default; `-vv` for debug). + #[arg(short, action = clap::ArgAction::Count)] + verbose: u8, + + /// Decrease verbosity. + #[arg(short, action = clap::ArgAction::Count)] + quiet: u8, + + /// Only display interfaces with names including this filter. + filter: Option, +} + +#[tokio::main(flavor = "multi_thread", worker_threads = 2)] +pub(crate) async fn main() -> ExitCode { + let args = Args::parse(); + + if args.version { + println!("rnstatus-rs {RETICULUM_COMPAT_VERSION}"); + return ExitCode::SUCCESS; + } + if let Err(e) = validate_args(&args) { + eprintln!("rnstatus-rs: {e}"); + return ExitCode::from(2); + } + + let verbosity = (args.verbose as i32) - (args.quiet as i32); + let level = match verbosity { + v if v <= -1 => tracing::Level::ERROR, + 0 => tracing::Level::WARN, + 1 => tracing::Level::INFO, + _ => tracing::Level::DEBUG, + }; + tracing_subscriber::fmt().with_max_level(level).init(); + + if args.monitor { + run_monitor(args).await + } else if args.remote.is_some() { + run_remote(args).await + } else { + run_local(args).await + } +} + +async fn run_monitor(args: Args) -> ExitCode { + let interval = Duration::from_secs_f64(args.monitor_interval.max(0.1)); + loop { + print!("\x1b[2J\x1b[H"); + let exit = if args.remote.is_some() { + run_remote_once(&args).await + } else { + run_local_once(&args).await + }; + if exit != ExitCode::SUCCESS { + return exit; + } + tokio::time::sleep(interval).await; + } +} + +async fn run_local(args: Args) -> ExitCode { + run_local_once(&args).await +} + +async fn run_local_once(args: &Args) -> ExitCode { + let config_dir = resolve_config_dir(args.config.as_deref()); + let config_path = config_dir.join("config"); + let config = match Config::from_file(&config_path) { + Ok(c) => c, + Err(e) => { + eprintln!( + "rnstatus-rs: could not read config at {}: {e}", + config_path.display() + ); + return ExitCode::from(1); + } + }; + let rc = ReticulumConfig::from_config(&config); + + if args.discovered || args.discovered_details { + return print_discovered_interfaces(&config_dir, &rc, args); + } + + let rpc_key = match local_rpc_key(&config_dir, &rc) { + Some(k) => k, + None => { + eprintln!( + "rnstatus-rs: no rpc_key configured and no transport identity at {} — nothing to query.", + config_path.display() + ); + return ExitCode::from(1); + } + }; + + let timeout = Duration::from_secs(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)); + let endpoint = rc.shared_rpc_endpoint(&std::env::temp_dir()); + + let stats = + match local_rpc_request(&endpoint, &rpc_key, &RpcRequest::GetInterfaceStats, timeout).await + { + Ok(RpcResponse::InterfaceStats(v)) => v, + Ok(other) => { + eprintln!("rnstatus-rs: unexpected response: {other:?}"); + return ExitCode::from(1); + } + Err(e) => { + eprintln!( + "rnstatus-rs: {}", + local_rpc_failure_message(&endpoint, &config_dir, &e) + ); + return ExitCode::from(1); + } + }; + + let link_count = if args.link_stats { + match local_rpc_request(&endpoint, &rpc_key, &RpcRequest::GetLinkCount, timeout).await { + Ok(RpcResponse::IntResult(n)) => Some(n), + _ => None, + } + } else { + None + }; + + if args.json { + print_local_json(&stats, link_count, args); + } else { + print_local_human(&stats, link_count, args); + } + + ExitCode::SUCCESS +} + +async fn local_rpc_request( + endpoint: &SharedInstanceRpcEndpoint, + rpc_key: &[u8], + request: &RpcRequest, + timeout: Duration, +) -> Result { + match endpoint { + SharedInstanceRpcEndpoint::Tcp(port) => { + rpc::connect_and_request(*port, rpc_key, request, timeout).await + } + SharedInstanceRpcEndpoint::Unix(socket_path) => { + rpc::connect_unix_and_request(socket_path, rpc_key, request, timeout).await + } + } +} + +fn local_rpc_key(config_dir: &Path, rc: &ReticulumConfig) -> Option> { + if let Some(key) = rc.rpc_key.as_ref() { + return Some(key.clone()); + } + let paths = rns_runtime::platform::StoragePaths::from_config_dir(config_dir); + let identity = + rns_identity::identity::Identity::from_file(&paths.storage_dir.join("transport_identity")) + .ok()?; + let private_key = identity.get_private_key()?; + Some(rpc::derive_rpc_key(&*private_key).to_vec()) +} + +fn local_rpc_failure_message( + endpoint: &SharedInstanceRpcEndpoint, + config_dir: &Path, + err: &rns_runtime::rpc::RpcError, +) -> String { + let endpoint = endpoint.display(); + let config_path = config_dir.join("config"); + let transport_identity_path = rns_runtime::platform::StoragePaths::from_config_dir(config_dir) + .storage_dir + .join("transport_identity"); + + match err { + rns_runtime::rpc::RpcError::AuthFailed => format!( + "local RPC authentication failed for rnsd-rs-compatible daemon at {endpoint}.\n\ + This usually means a config mismatch (different --config, rpc_key, or \ + transport_identity) or another app is owning the control port.\n\ + System Reticulum defaults are 37428/37429; Ratspeak app-private \ + configs use 37430/37431.\n\ + Config checked: {}.\n\ + If rpc_key is unset, the fallback key is derived from {}.", + config_path.display(), + transport_identity_path.display() + ), + rns_runtime::rpc::RpcError::Io(e) + if matches!( + e.kind(), + std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound + ) => + { + format!( + "could not connect to local rnsd-rs-compatible daemon at {endpoint}: {e}.\n\ + Start rnsd-rs with the same --config directory, or check \ + shared_instance_type and instance_control_port in {}. \ + System Reticulum defaults are 37428/37429; Ratspeak \ + app-private configs use 37430/37431.", + config_path.display() + ) + } + rns_runtime::rpc::RpcError::Io(e) if e.kind() == std::io::ErrorKind::TimedOut => { + format!( + "timed out while talking to local rnsd-rs-compatible daemon at {endpoint}: {e}.\n\ + If a process is listening there, it may not be rnsd-rs-compatible or may be using \ + a different local RPC auth key. Config checked: {}.", + config_path.display() + ) + } + _ => format!( + "could not query local rnsd-rs-compatible daemon at {endpoint} using {}: {err}", + config_path.display() + ), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SortKey { + Rate, + Rx, + Tx, + RxRate, + TxRate, + Traffic, + Announces, + AnnounceRx, + AnnounceTx, + Held, +} + +fn validate_args(args: &Args) -> Result<(), String> { + parse_sort_key(args.sort.as_deref()).map(|_| ())?; + if args.monitor_interval <= 0.0 { + return Err("--monitor-interval must be greater than 0".to_string()); + } + if (args.discovered || args.discovered_details) && args.remote.is_some() { + return Err( + "--discovered/-D is local-only and cannot be combined with --remote".to_string(), + ); + } + Ok(()) +} + +fn parse_sort_key(value: Option<&str>) -> Result, String> { + let Some(value) = value else { + return Ok(None); + }; + let key = match value.to_ascii_lowercase().as_str() { + "rate" | "bitrate" => SortKey::Rate, + "rx" => SortKey::Rx, + "tx" => SortKey::Tx, + "rxs" => SortKey::RxRate, + "txs" => SortKey::TxRate, + "traffic" => SortKey::Traffic, + "announces" | "announce" => SortKey::Announces, + "arx" => SortKey::AnnounceRx, + "atx" => SortKey::AnnounceTx, + "held" => SortKey::Held, + _ => { + return Err(format!( + "--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held; got {value}" + )); + } + }; + Ok(Some(key)) +} + +fn local_stat_sort_value(e: &rpc::InterfaceStatEntry, key: SortKey) -> f64 { + match key { + SortKey::Rate => e.bitrate as f64, + SortKey::Rx => e.rx_bytes as f64, + SortKey::Tx => e.tx_bytes as f64, + SortKey::RxRate => e.rx_rate as f64, + SortKey::TxRate => e.tx_rate as f64, + SortKey::Traffic => e.rx_bytes.saturating_add(e.tx_bytes) as f64, + SortKey::Announces => e.incoming_announce_frequency + e.outgoing_announce_frequency, + SortKey::AnnounceRx => e.incoming_announce_frequency, + SortKey::AnnounceTx => e.outgoing_announce_frequency, + SortKey::Held => e.held_announces as f64, + } +} + +fn visible_by_default(name: &str) -> bool { + !(name.starts_with("LocalInterface[") + || name.starts_with("TCPInterface[Client") + || name.starts_with("BackboneInterface[Client on") + || name.starts_with("AutoInterfacePeer[") + || name.starts_with("WeaveInterfacePeer[") + || name.starts_with("I2PInterfacePeer[Connected peer")) +} + +fn interface_matches_filter(name: &str, filter: Option<&str>) -> bool { + filter.is_none_or(|needle| { + name.to_ascii_lowercase() + .contains(&needle.to_ascii_lowercase()) + }) +} + +fn filtered_local_stats<'a>( + stats: &'a [rpc::InterfaceStatEntry], + args: &Args, +) -> Vec<&'a rpc::InterfaceStatEntry> { + let mut entries: Vec<_> = stats + .iter() + .filter(|entry| args.all || visible_by_default(&entry.name)) + .filter(|entry| interface_matches_filter(&entry.name, args.filter.as_deref())) + .collect(); + if let Ok(Some(key)) = parse_sort_key(args.sort.as_deref()) { + entries.sort_by(|a, b| { + let ord = local_stat_sort_value(a, key) + .partial_cmp(&local_stat_sort_value(b, key)) + .unwrap_or(std::cmp::Ordering::Equal); + if args.reverse { ord } else { ord.reverse() } + }); + } + entries +} + +fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option, args: &Args) { + println!( + "Reticulum Status [rnstatus-rs {}]", + env!("CARGO_PKG_VERSION") + ); + println!(); + + let entries = filtered_local_stats(stats, args); + if entries.is_empty() { + println!(" No interfaces."); + } else { + for entry in entries { + let status = if entry.online { "Up" } else { "Down" }; + println!(" {}", entry.name); + println!(" Status : {status}"); + println!(" Mode : {}", entry.mode); + println!(" Role : {}", entry.role); + println!(" Bitrate : {}", format::pretty_speed(entry.bitrate)); + println!(" MTU : {} B", entry.mtu); + if let Some(clients) = entry.clients { + println!(" Clients : {clients}"); + } + if entry.ifac_size > 0 { + println!(" IFAC : {} bits", entry.ifac_size * 8); + } + if args.announce_stats { + if let Some(queued) = entry.announce_queue + && queued > 0 + { + println!( + " Queued : {queued} announce{}", + if queued == 1 { "" } else { "s" } + ); + } + if entry.held_announces > 0 { + println!( + " Held : {} announce{}", + entry.held_announces, + if entry.held_announces == 1 { "" } else { "s" } + ); + } + if entry.incoming_announce_frequency > 0.0 + || entry.outgoing_announce_frequency > 0.0 + { + println!( + " Announces: {:.3}/s rx / {:.3}/s tx", + entry.incoming_announce_frequency, entry.outgoing_announce_frequency + ); + } + } + println!( + " Traffic : {} rx / {} tx", + format::pretty_size(entry.rx_bytes), + format::pretty_size(entry.tx_bytes) + ); + if entry.rx_rate > 0 || entry.tx_rate > 0 { + println!( + " Rates : {} rx / {} tx", + format::pretty_speed(entry.rx_rate), + format::pretty_speed(entry.tx_rate) + ); + } + if entry.tx_drops > 0 { + println!(" TX drops : {}", entry.tx_drops); + } + println!(); + } + } + + if args.totals { + let (rxb, txb) = stats + .iter() + .fold((0u64, 0u64), |(r, t), e| (r + e.rx_bytes, t + e.tx_bytes)); + println!(" Totals:"); + println!(" RX : {}", format::pretty_size(rxb)); + println!(" TX : {}", format::pretty_size(txb)); + println!(); + } + + if let Some(n) = link_count { + println!(" Active links: {n}"); + } +} + +fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option, args: &Args) { + let (total_rxb, total_txb) = stats + .iter() + .fold((0u64, 0u64), |(r, t), e| (r + e.rx_bytes, t + e.tx_bytes)); + let entries = filtered_local_stats(stats, args); + + print!("{{\"interfaces\":["); + for (i, e) in entries.iter().enumerate() { + if i > 0 { + print!(","); + } + print!( + "{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"tx_drops\":{}}}", + json_str(&e.name), + e.online, + json_str(&e.mode), + json_str(&e.role), + e.bitrate, + e.mtu, + e.rx_bytes, + e.tx_bytes, + e.rx_rate, + e.tx_rate, + e.announce_queue + .map(|v| v.to_string()) + .unwrap_or_else(|| "null".to_string()), + e.held_announces, + e.incoming_announce_frequency, + e.outgoing_announce_frequency, + e.tx_drops, + ); + } + print!("]"); + if args.totals { + print!(",\"rxb_total\":{total_rxb},\"txb_total\":{total_txb}"); + } + if let Some(n) = link_count { + print!(",\"link_count\":{n}"); + } + println!("}}"); +} + +fn print_discovered_interfaces(config_dir: &Path, rc: &ReticulumConfig, args: &Args) -> ExitCode { + let paths = StoragePaths::from_config_dir(config_dir); + let store = match DiscoveryStore::open(&paths.storage_dir) { + Ok(store) => store, + Err(e) => { + eprintln!("rnstatus-rs: could not open discovery store: {e}"); + return ExitCode::from(1); + } + }; + let sources = if rc.interface_discovery_sources.is_empty() { + None + } else { + Some(rc.interface_discovery_sources.as_slice()) + }; + let mut records = match store.list(sources) { + Ok(records) => records, + Err(e) => { + eprintln!("rnstatus-rs: could not read discovered interfaces: {e}"); + return ExitCode::from(1); + } + }; + records.retain(|record| interface_matches_filter(&record.info.name, args.filter.as_deref())); + + if args.json { + let value = records + .iter() + .map(discovered_json) + .collect::>(); + println!("{}", serde_json::Value::Array(value)); + return ExitCode::SUCCESS; + } + + if args.discovered_details { + print_discovered_details(&records); + } else { + print_discovered_summary(&records); + } + ExitCode::SUCCESS +} + +fn discovered_json(record: &DiscoveredInterface) -> serde_json::Value { + let info = &record.info; + json!({ + "name": info.name, + "type": info.interface_type, + "status": record.status.map(|s| s.as_str()).unwrap_or("unknown"), + "transport": info.transport_enabled, + "transport_id": hex::encode(info.transport_id), + "network_id": hex::encode(record.network_id), + "hops": record.hops, + "value": record.stamp_value, + "discovered": record.discovered, + "last_heard": record.last_heard, + "heard_count": record.heard_count, + "latitude": finite_location(info.latitude), + "longitude": finite_location(info.longitude), + "height": finite_location(info.height), + "reachable_on": info.reachable_on, + "port": info.port, + "frequency": info.frequency, + "bandwidth": info.bandwidth, + "sf": info.spreading_factor, + "cr": info.coding_rate, + "modulation": info.modulation, + "channel": info.channel, + "config_entry": discovered_config_entry(record), + }) +} + +fn finite_location(value: f64) -> Option { + value.is_finite().then_some(value) +} + +fn print_discovered_summary(records: &[DiscoveredInterface]) { + if records.is_empty() { + println!("No discovered interfaces."); + return; + } + println!( + "{:<25} {:<18} {:<10} {:<12} {:<8} Location", + "Name", "Type", "Status", "Last Heard", "Value" + ); + println!("{}", "-".repeat(92)); + let now = unix_now_secs(); + for record in records { + let info = &record.info; + let status = record.status.map(|s| s.as_str()).unwrap_or("unknown"); + let location = location_summary(info.latitude, info.longitude, info.height); + println!( + "{:<25} {:<18} {:<10} {:<12} {:<8} {}", + truncate_ascii(&info.name, 25), + truncate_ascii(&info.interface_type.replace("Interface", ""), 18), + status, + age_label(now, record.last_heard), + record.stamp_value, + location + ); + } +} + +fn print_discovered_details(records: &[DiscoveredInterface]) { + if records.is_empty() { + println!("No discovered interfaces."); + return; + } + let now = unix_now_secs(); + for (idx, record) in records.iter().enumerate() { + if idx > 0 { + println!("\n{}\n", "=".repeat(32)); + } + let info = &record.info; + println!("Name : {}", info.name); + println!("Type : {}", info.interface_type); + println!( + "Status : {}", + record.status.map(|s| s.as_str()).unwrap_or("unknown") + ); + println!( + "Transport : {}", + if info.transport_enabled { + "Enabled" + } else { + "Disabled" + } + ); + println!("Transport ID : {}", hex::encode(info.transport_id)); + if record.network_id != info.transport_id { + println!("Network ID : {}", hex::encode(record.network_id)); + } + println!( + "Distance : {} hop{}", + record.hops, + if record.hops == 1 { "" } else { "s" } + ); + println!("Discovered : {} ago", age_label(now, record.discovered)); + println!("Last Heard : {} ago", age_label(now, record.last_heard)); + println!( + "Location : {}", + location_summary(info.latitude, info.longitude, info.height) + ); + if let Some(freq) = info.frequency { + println!("Frequency : {freq} Hz"); + } + if let Some(bw) = info.bandwidth { + println!("Bandwidth : {bw} Hz"); + } + if let Some(sf) = info.spreading_factor { + println!("Sprd. Factor : {sf}"); + } + if let Some(cr) = info.coding_rate { + println!("Coding Rate : {cr}"); + } + if let Some(modu) = &info.modulation { + println!("Modulation : {modu}"); + } + if let Some(ch) = info.channel { + println!("Channel : {ch}"); + } + if let Some(addr) = &info.reachable_on { + println!("Address : {addr}"); + } + if let Some(port) = info.port { + println!("Port : {port}"); + } + println!("Stamp Value : {}", record.stamp_value); + println!("\nConfiguration Entry:"); + for line in discovered_config_entry(record).lines() { + println!(" {line}"); + } + } +} + +fn discovered_config_entry(record: &DiscoveredInterface) -> String { + let info = &record.info; + let mut lines = vec![ + format!("[[{}]]", info.name), + format!("type = {}", info.interface_type), + "interface_enabled = True".to_string(), + format!( + "transport = {}", + if info.transport_enabled { + "True" + } else { + "False" + } + ), + ]; + if let Some(addr) = &info.reachable_on { + lines.push(format!("target_host = {addr}")); + } + if let Some(port) = info.port { + lines.push(format!("target_port = {port}")); + } + if let Some(freq) = info.frequency { + lines.push(format!("frequency = {freq}")); + } + if let Some(bw) = info.bandwidth { + lines.push(format!("bandwidth = {bw}")); + } + if let Some(sf) = info.spreading_factor { + lines.push(format!("spreading_factor = {sf}")); + } + if let Some(cr) = info.coding_rate { + lines.push(format!("coding_rate = {cr}")); + } + if let Some(modu) = &info.modulation { + lines.push(format!("modulation = {modu}")); + } + if let Some(ch) = info.channel { + lines.push(format!("channel = {ch}")); + } + if let Some(netname) = &info.ifac_netname { + lines.push(format!("ifac_netname = {netname}")); + } + lines.join("\n") +} + +fn location_summary(latitude: f64, longitude: f64, height: f64) -> String { + if latitude == 0.0 && longitude == 0.0 { + return "N/A".to_string(); + } + if height != 0.0 { + format!("{latitude:.4}, {longitude:.4}, {height:.0}m h") + } else { + format!("{latitude:.4}, {longitude:.4}") + } +} + +fn truncate_ascii(s: &str, max_chars: usize) -> String { + if s.chars().count() <= max_chars { + return s.to_string(); + } + s.chars() + .take(max_chars.saturating_sub(3)) + .collect::() + + "..." +} + +fn age_label(now: u64, timestamp: u64) -> String { + let diff = now.saturating_sub(timestamp); + if diff < 60 { + "0s".to_string() + } else if diff < 3600 { + format!("{}m", diff / 60) + } else if diff < 86400 { + format!("{}h", diff / 3600) + } else { + format!("{}d", diff / 86400) + } +} + +fn unix_now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +async fn run_remote(args: Args) -> ExitCode { + run_remote_once(&args).await +} + +async fn run_remote_once(args: &Args) -> ExitCode { + let remote_hex = args.remote.as_deref().expect("checked in main"); + let remote_hash = match hash::parse_dest_hash(remote_hex) { + Ok(h) => h, + Err(e) => { + eprintln!("rnstatus-rs: --remote: {e}"); + return ExitCode::from(2); + } + }; + + let identity_path = match args.identity.as_ref() { + Some(p) => p.clone(), + None => { + eprintln!("rnstatus-rs: --remote requires --identity ."); + return ExitCode::from(2); + } + }; + let identity = match rns_identity::identity::Identity::from_file(&identity_path) { + Ok(id) => id, + Err(e) => { + eprintln!( + "rnstatus-rs: could not load identity from {}: {e:?}", + identity_path.display() + ); + return ExitCode::from(1); + } + }; + + let shutdown = ShutdownSignal::new(); + let foreground = Arc::new(AtomicBool::new(true)); + let handle = match init(args.config.as_deref(), None, shutdown.clone(), foreground).await { + Ok(h) => h, + Err(e) => { + eprintln!("rnstatus-rs: failed to initialize Reticulum runtime: {e:?}"); + return ExitCode::from(1); + } + }; + + let timeout = Duration::from_secs(args.timeout.unwrap_or(REMOTE_TIMEOUT_SECS)); + + // Wire format: msgpack 1-tuple `(include_link_count,)`. + let payload = match rmp_serde::to_vec(&(args.link_stats,)) { + Ok(v) => v, + Err(e) => { + eprintln!("rnstatus-rs: msgpack encode failed: {e}"); + shutdown.trigger(); + return ExitCode::from(1); + } + }; + + let client = LinkClient::new(handle.transport_tx.clone(), identity); + let response_bytes = match client + .query( + remote_hash, + MGMT_APP, + "/status", + payload, + REMOTE_HOPS, + timeout, + ) + .await + { + Ok(b) => b, + Err(e) => { + eprintln!("rnstatus-rs: remote query failed: {}", remote_err(&e)); + shutdown.trigger(); + return match e { + LinkClientError::Timeout(_) => ExitCode::from(124), + _ => ExitCode::from(1), + }; + } + }; + + let exit = print_remote_status(&response_bytes, args); + shutdown.trigger(); + exit +} + +#[derive(Debug, Clone)] +struct RemoteInterface { + name: String, + online: bool, + mode: u64, + bitrate: u64, + rxb: u64, + txb: u64, + rxs: u64, + txs: u64, + announce_queue: Option, + held_announces: u64, + incoming_announce_frequency: f64, + outgoing_announce_frequency: f64, + clients: Option, +} + +impl RemoteInterface { + fn sort_value(&self, key: SortKey) -> f64 { + match key { + SortKey::Rate => self.bitrate as f64, + SortKey::Rx => self.rxb as f64, + SortKey::Tx => self.txb as f64, + SortKey::RxRate => self.rxs as f64, + SortKey::TxRate => self.txs as f64, + SortKey::Traffic => self.rxb.saturating_add(self.txb) as f64, + SortKey::Announces => { + self.incoming_announce_frequency + self.outgoing_announce_frequency + } + SortKey::AnnounceRx => self.incoming_announce_frequency, + SortKey::AnnounceTx => self.outgoing_announce_frequency, + SortKey::Held => self.held_announces as f64, + } + } +} + +// Wire format: outer array is [stats] or [stats, link_count]. +fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode { + let value: rmpv::Value = match rmp_serde::from_slice(bytes) { + Ok(v) => v, + Err(e) => { + eprintln!("rnstatus-rs: malformed response: {e}"); + return ExitCode::from(1); + } + }; + let arr = match value.as_array() { + Some(a) => a, + None => { + eprintln!("rnstatus-rs: response is not a msgpack array"); + return ExitCode::from(1); + } + }; + let stats = match arr.first().and_then(|v| v.as_map()) { + Some(m) => m, + None => { + eprintln!("rnstatus-rs: response missing stats dict"); + return ExitCode::from(1); + } + }; + let link_count = arr.get(1).and_then(|v| v.as_u64()); + + let interfaces = stats + .iter() + .find(|(k, _)| k.as_str() == Some("interfaces")) + .and_then(|(_, v)| v.as_array()); + let total_rxb = stats + .iter() + .find(|(k, _)| k.as_str() == Some("rxb")) + .and_then(|(_, v)| v.as_u64()) + .unwrap_or(0); + let total_txb = stats + .iter() + .find(|(k, _)| k.as_str() == Some("txb")) + .and_then(|(_, v)| v.as_u64()) + .unwrap_or(0); + + let mut parsed_interfaces = interfaces + .map(|ifs| { + ifs.iter() + .filter_map(|iface| iface.as_map().map(|m| remote_interface_from_map(m))) + .filter(|iface| args.all || visible_by_default(&iface.name)) + .filter(|iface| interface_matches_filter(&iface.name, args.filter.as_deref())) + .collect::>() + }) + .unwrap_or_default(); + if let Ok(Some(key)) = parse_sort_key(args.sort.as_deref()) { + parsed_interfaces.sort_by(|a, b| { + let ord = a + .sort_value(key) + .partial_cmp(&b.sort_value(key)) + .unwrap_or(std::cmp::Ordering::Equal); + if args.reverse { ord } else { ord.reverse() } + }); + } + + if args.json { + print!("{{"); + print!("\"interfaces\":["); + for (i, iface) in parsed_interfaces.iter().enumerate() { + if i > 0 { + print!(","); + } + print!( + "{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{}}}", + json_str(&iface.name), + iface.online, + iface.mode, + iface.bitrate, + iface.rxb, + iface.txb, + iface.rxs, + iface.txs, + iface + .announce_queue + .map(|v| v.to_string()) + .unwrap_or_else(|| "null".to_string()), + iface.held_announces, + iface.incoming_announce_frequency, + iface.outgoing_announce_frequency, + ); + } + print!("]"); + if args.totals { + print!(",\"rxb_total\":{total_rxb},\"txb_total\":{total_txb}"); + } + if let Some(n) = link_count { + print!(",\"link_count\":{n}"); + } + println!("}}"); + return ExitCode::SUCCESS; + } + + println!("Remote Reticulum Status"); + println!(); + + if !parsed_interfaces.is_empty() { + for iface in &parsed_interfaces { + let status = if iface.online { "Up" } else { "Down" }; + println!(" {}", iface.name); + println!(" Status : {status}"); + println!(" Mode : 0x{:02x}", iface.mode); + println!(" Bitrate : {}", format::pretty_speed(iface.bitrate)); + if let Some(clients) = iface.clients { + println!(" Clients : {clients}"); + } + if args.announce_stats { + if let Some(queued) = iface.announce_queue + && queued > 0 + { + println!( + " Queued : {queued} announce{}", + if queued == 1 { "" } else { "s" } + ); + } + if iface.held_announces > 0 { + println!( + " Held : {} announce{}", + iface.held_announces, + if iface.held_announces == 1 { "" } else { "s" } + ); + } + if iface.incoming_announce_frequency > 0.0 + || iface.outgoing_announce_frequency > 0.0 + { + println!( + " Announces: {:.3}/s rx / {:.3}/s tx", + iface.incoming_announce_frequency, iface.outgoing_announce_frequency + ); + } + } + println!( + " Traffic : {} rx / {} tx", + format::pretty_size(iface.rxb), + format::pretty_size(iface.txb) + ); + if iface.rxs > 0 || iface.txs > 0 { + println!( + " Rates : {} rx / {} tx", + format::pretty_speed(iface.rxs), + format::pretty_speed(iface.txs) + ); + } + println!(); + } + } else { + println!(" No interfaces reported."); + } + + if args.totals { + println!(" Totals:"); + println!(" RX : {}", format::pretty_size(total_rxb)); + println!(" TX : {}", format::pretty_size(total_txb)); + println!(); + } + if let Some(n) = link_count { + println!(" Active links: {n}"); + } + + ExitCode::SUCCESS +} + +fn remote_interface_from_map(m: &[(rmpv::Value, rmpv::Value)]) -> RemoteInterface { + RemoteInterface { + name: map_str(m, "name").unwrap_or_else(|| "(unnamed)".to_string()), + online: map_bool(m, "status") + .or_else(|| map_bool(m, "online")) + .unwrap_or(false), + mode: map_u64(m, "mode").unwrap_or(0), + bitrate: map_u64(m, "bitrate").unwrap_or(0), + rxb: map_u64(m, "rxb").unwrap_or(0), + txb: map_u64(m, "txb").unwrap_or(0), + rxs: map_u64(m, "rxs").unwrap_or(0), + txs: map_u64(m, "txs").unwrap_or(0), + announce_queue: map_u64(m, "announce_queue"), + held_announces: map_u64(m, "held_announces").unwrap_or(0), + incoming_announce_frequency: map_f64_or_u64(m, "incoming_announce_frequency") + .unwrap_or(0.0), + outgoing_announce_frequency: map_f64_or_u64(m, "outgoing_announce_frequency") + .unwrap_or(0.0), + clients: map_u64(m, "clients"), + } +} + +fn map_str(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_str().map(|s| s.to_string())) +} + +fn map_u64(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_u64()) +} + +fn map_f64_or_u64(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_f64().or_else(|| v.as_u64().map(|n| n as f64))) +} + +fn map_bool(map: &[(rmpv::Value, rmpv::Value)], key: &str) -> Option { + map.iter() + .find(|(k, _)| k.as_str() == Some(key)) + .and_then(|(_, v)| v.as_bool()) +} + +fn remote_err(e: &LinkClientError) -> String { + match e { + LinkClientError::PubkeyNotDiscovered => { + "remote node not discovered (no announce received). \ + Verify the transport hash and that the local rnsd has connectivity." + .to_string() + } + LinkClientError::Timeout(stage) => format!("timeout while waiting for {stage}"), + other => other.to_string(), + } +} + +fn json_str(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn local_rpc_auth_failure_explains_config_mismatch_and_port_owner() { + let endpoint = SharedInstanceRpcEndpoint::Tcp(37429); + let msg = local_rpc_failure_message( + &endpoint, + Path::new("/tmp/rns-auth-test"), + &rns_runtime::rpc::RpcError::AuthFailed, + ); + + assert!(msg.contains("config mismatch")); + assert!(msg.contains("another app is owning the control port")); + assert!(msg.contains("rpc_key")); + assert!(msg.contains("transport_identity")); + assert!(msg.contains("37430/37431")); + } +} diff --git a/crates/rns-tools/src/format.rs b/crates/rns-tools/src/format.rs new file mode 100644 index 0000000..a4dbdaa --- /dev/null +++ b/crates/rns-tools/src/format.rs @@ -0,0 +1,131 @@ +//! Python ref: `RNS/__init__.py` (`prettyspeed`, `prettysize`, `prettytime`). + +pub fn pretty_size(num: u64) -> String { + if num == 0 { + return "0 B".to_string(); + } + let units = ["B", "KB", "MB", "GB", "TB"]; + let mut val = num as f64; + for unit in &units { + if val < 1024.0 { + return if val < 10.0 { + format!("{val:.2} {unit}") + } else if val < 100.0 { + format!("{val:.1} {unit}") + } else { + format!("{val:.0} {unit}") + }; + } + val /= 1024.0; + } + format!("{val:.1} PB") +} + +pub fn pretty_speed(bps: u64) -> String { + if bps == 0 { + return "0 bps".to_string(); + } + let units = ["bps", "Kbps", "Mbps", "Gbps"]; + let mut val = bps as f64; + for unit in &units { + if val < 1000.0 { + return if val < 10.0 { + format!("{val:.2} {unit}") + } else if val < 100.0 { + format!("{val:.1} {unit}") + } else { + format!("{val:.0} {unit}") + }; + } + val /= 1000.0; + } + format!("{val:.1} Tbps") +} + +pub fn pretty_time(seconds: f64) -> String { + if seconds < 0.0 { + return "unknown".to_string(); + } + let s = seconds as u64; + if s < 60 { + format!("{s}s") + } else if s < 3600 { + format!("{}m {}s", s / 60, s % 60) + } else if s < 86400 { + format!("{}h {}m", s / 3600, (s % 3600) / 60) + } else { + format!("{}d {}h", s / 86400, (s % 86400) / 3600) + } +} + +pub fn pretty_frequency(hz: f64) -> String { + if hz >= 1_000_000_000.0 { + format!("{:.3} GHz", hz / 1_000_000_000.0) + } else if hz >= 1_000_000.0 { + format!("{:.3} MHz", hz / 1_000_000.0) + } else if hz >= 1_000.0 { + format!("{:.3} KHz", hz / 1_000.0) + } else { + format!("{hz:.1} Hz") + } +} + +pub fn hex_rep(data: &[u8]) -> String { + data.iter() + .map(|b| format!("{b:02x}")) + .collect::>() + .join(":") +} + +pub fn pretty_hex_rep(data: &[u8]) -> String { + format!("<{}>", hex::encode(data)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pretty_size() { + assert_eq!(pretty_size(0), "0 B"); + assert_eq!(pretty_size(100), "100 B"); + assert_eq!(pretty_size(1024), "1.00 KB"); + assert_eq!(pretty_size(1536), "1.50 KB"); + assert_eq!(pretty_size(1048576), "1.00 MB"); + assert_eq!(pretty_size(1073741824), "1.00 GB"); + } + + #[test] + fn test_pretty_speed() { + assert_eq!(pretty_speed(0), "0 bps"); + assert_eq!(pretty_speed(115200), "115 Kbps"); + assert_eq!(pretty_speed(1000000), "1.00 Mbps"); + assert_eq!(pretty_speed(1000000000), "1.00 Gbps"); + } + + #[test] + fn test_pretty_time() { + assert_eq!(pretty_time(30.0), "30s"); + assert_eq!(pretty_time(90.0), "1m 30s"); + assert_eq!(pretty_time(3661.0), "1h 1m"); + assert_eq!(pretty_time(90061.0), "1d 1h"); + assert_eq!(pretty_time(-1.0), "unknown"); + } + + #[test] + fn test_pretty_frequency() { + assert_eq!(pretty_frequency(433_000_000.0), "433.000 MHz"); + assert_eq!(pretty_frequency(868_000_000.0), "868.000 MHz"); + assert_eq!(pretty_frequency(2_400_000_000.0), "2.400 GHz"); + } + + #[test] + fn test_hex_rep() { + assert_eq!(hex_rep(&[0xAA, 0xBB, 0xCC]), "aa:bb:cc"); + } + + #[test] + fn test_pretty_hex_rep() { + assert_eq!(pretty_hex_rep(&[0xAA, 0xBB]), ""); + } +} diff --git a/crates/rns-tools/src/hash.rs b/crates/rns-tools/src/hash.rs new file mode 100644 index 0000000..c41279b --- /dev/null +++ b/crates/rns-tools/src/hash.rs @@ -0,0 +1,63 @@ +/// Accepts `aabbcc...` or `aa:bb:cc:...`; must decode to 16 bytes. +pub fn parse_dest_hash(input: &str) -> Result<[u8; 16], String> { + let clean = input.trim().replace(':', ""); + let bytes = hex::decode(&clean).map_err(|e| format!("invalid hex: {e}"))?; + if bytes.len() != 16 { + return Err(format!( + "expected 16 bytes (32 hex chars), got {} bytes", + bytes.len() + )); + } + let mut hash = [0u8; 16]; + hash.copy_from_slice(&bytes); + Ok(hash) +} + +pub fn format_dest_hash(hash: &[u8; 16]) -> String { + hex::encode(hash) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_dest_hash() { + let hex_str = "aabbccddaabbccddaabbccddaabbccdd"; + let hash = parse_dest_hash(hex_str).unwrap(); + assert_eq!( + hash, + [ + 0xaa, 0xbb, 0xcc, 0xdd, 0xaa, 0xbb, 0xcc, 0xdd, 0xaa, 0xbb, 0xcc, 0xdd, 0xaa, 0xbb, + 0xcc, 0xdd + ] + ); + } + + #[test] + fn test_parse_dest_hash_with_colons() { + let hex_str = "aa:bb:cc:dd:aa:bb:cc:dd:aa:bb:cc:dd:aa:bb:cc:dd"; + let hash = parse_dest_hash(hex_str).unwrap(); + assert_eq!(hash[0], 0xaa); + assert_eq!(hash[15], 0xdd); + } + + #[test] + fn test_parse_dest_hash_wrong_length() { + assert!(parse_dest_hash("aabbcc").is_err()); + } + + #[test] + fn test_parse_dest_hash_invalid_hex() { + assert!(parse_dest_hash("gghhiijjkkllmmnnooppqqrrssttaabb").is_err()); + } + + #[test] + fn test_format_dest_hash() { + let hash = [ + 0xaa, 0xbb, 0xcc, 0xdd, 0xaa, 0xbb, 0xcc, 0xdd, 0xaa, 0xbb, 0xcc, 0xdd, 0xaa, 0xbb, + 0xcc, 0xdd, + ]; + assert_eq!(format_dest_hash(&hash), "aabbccddaabbccddaabbccddaabbccdd"); + } +} diff --git a/crates/rns-tools/src/lib.rs b/crates/rns-tools/src/lib.rs new file mode 100644 index 0000000..c5bf95d --- /dev/null +++ b/crates/rns-tools/src/lib.rs @@ -0,0 +1,4 @@ +//! Shared utility code for Reticulum CLI tools. + +pub mod format; +pub mod hash; diff --git a/crates/rns-transport/Cargo.toml b/crates/rns-transport/Cargo.toml new file mode 100644 index 0000000..de60f61 --- /dev/null +++ b/crates/rns-transport/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "rns-transport" +description = "Transport and routing engine for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[features] +default = [] +# When enabled, the transport actor tick slows from 250ms to 2s while the +# shared `is_foreground` flag is false. Enabled only on mobile builds of the +# Tauri wrapper — desktop leaves this off so nothing degrades when a window +# is minimized or hidden. +mobile-throttle = [] + +[dependencies] +rns-crypto = { workspace = true, features = ["std"] } +rns-wire = { workspace = true, features = ["std"] } +rns-identity = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +bytes = { workspace = true } +rand = { workspace = true } +tracing = { workspace = true } +subtle = { workspace = true } +serde = { workspace = true } +rmp-serde = { workspace = true } +rmpv = { workspace = true } +hex = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/rns-transport/src/actor/inbound.rs b/crates/rns-transport/src/actor/inbound.rs new file mode 100644 index 0000000..88c82cc --- /dev/null +++ b/crates/rns-transport/src/actor/inbound.rs @@ -0,0 +1,1044 @@ +use super::*; + +impl TransportActor { + #[tracing::instrument( + level = "trace", + name = "actor.on_inbound", + skip_all, + fields(interface_id = packet.interface_id, raw_len = packet.raw.len()), + )] + pub(super) fn on_inbound(&mut self, packet: crate::messages::InboundPacket) { + self.traffic + .record_rx(packet.interface_id, packet.raw.len() as u64); + + // Strip the IFAC tag if the interface gates membership on one; packets + // that fail verification are silently dropped so a misconfigured peer + // can't leak into a closed access group. + let raw: bytes::Bytes = if let Some(entry) = self.interfaces.get(&packet.interface_id) + && let Some(ref ifac_key) = entry.ifac_key + { + let ifac_size = entry.ifac_size; + match crate::ifac::ifac_verify(&packet.raw, ifac_key, ifac_size) { + Some(stripped) => bytes::Bytes::from(stripped), + None => { + trace!( + interface_id = packet.interface_id, + "IFAC verification failed, dropping packet" + ); + return; + } + } + } else { + packet.raw.clone() + }; + + let (parsed, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) { + Ok((header, offset)) => (header, offset), + Err(e) => { + tracing::warn!( + interface_id = packet.interface_id, + raw_len = raw.len(), + first_byte = format!("0x{:02x}", raw.first().copied().unwrap_or(0)), + error = %e, + "inbound packet dropped: header parse failed" + ); + return; + } + }; + + // Dedup via the packet hashlist. A handful of contexts legitimately + // repeat (keepalives, resource transfer frames, channel traffic) and + // must bypass the check. + let pkt_hash = rns_wire::hash::packet_hash(&raw, parsed.flags.header_type); + self.record_packet_metrics( + pkt_hash, + PacketMetrics { + rssi: packet.rssi, + snr: packet.snr, + q: packet.q, + }, + ); + let skip_hashlist = matches!( + parsed.context, + rns_wire::context::PacketContext::Keepalive + | rns_wire::context::PacketContext::Resource + | rns_wire::context::PacketContext::ResourceReq + | rns_wire::context::PacketContext::ResourcePrf + | rns_wire::context::PacketContext::CacheRequest + | rns_wire::context::PacketContext::Channel + ); + + // On shared media (e.g. LoRa) we overhear our own forwards and link + // traffic; if we dedup against that, legitimate copies disappear. + // Defer the hashlist check for packets owned by the link table or + // carrying link-proof context. + let defer_hashlist = self.link_table.contains(&parsed.destination_hash) + || parsed.context == rns_wire::context::PacketContext::Lrproof; + + if !skip_hashlist && !defer_hashlist && !self.packet_hashlist.insert(pkt_hash) { + // SINGLE announces are retransmitted to refresh paths, so an + // exact duplicate is expected and must not be dropped. + if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce + && parsed.flags.destination_type == rns_wire::flags::DestinationType::Single + { + } else { + trace!("duplicate packet dropped"); + return; + } + } + + tracing::debug!( + pkt_type = ?parsed.flags.packet_type, + dest = %hex::encode(parsed.destination_hash), + hops = parsed.hops, + interface_id = packet.interface_id, + raw_len = raw.len(), + "inbound packet received" + ); + + match parsed.flags.packet_type { + rns_wire::flags::PacketType::Announce => { + self.process_announce(&raw, &parsed, data_offset, packet.interface_id); + } + rns_wire::flags::PacketType::LinkRequest => { + self.process_link_request(&raw, &parsed, packet.interface_id); + } + rns_wire::flags::PacketType::Proof => { + self.process_proof(&raw, &parsed, packet.interface_id); + } + rns_wire::flags::PacketType::Data => { + self.process_data(&raw, &parsed, packet.interface_id); + } + } + } + + fn process_announce( + &mut self, + raw: &[u8], + header: &rns_wire::header::PacketHeader, + data_offset: usize, + interface_id: InterfaceId, + ) { + let is_from_local_client = self.is_local_client_interface(interface_id); + + if header.hops > PATHFINDER_M { + debug!(hops = header.hops, "announce exceeded hop limit"); + return; + } + + if self.local_destinations.contains(&header.destination_hash) { + debug!("dropping own announce"); + return; + } + + // Per-interface ingress control. Record the announce and, if the + // interface is burst-limiting, hold it for later release by the + // maintenance tick rather than processing now. + // + // Bypass the hold when the announce answers an outstanding path + // request: the announce *is* the resolution, and delaying it there + // would stall the requester for no gain. + let answers_path_request = self.path_requests.contains_key(&header.destination_hash) + || self + .discovery_path_requests + .contains_key(&header.destination_hash); + if let Some(entry) = self.interfaces.get_mut(&interface_id) { + entry.ingress.received_announce(); + if !is_from_local_client + && !answers_path_request + && entry.ingress.should_ingress_limit() + { + entry.ingress.hold_announce(crate::ingress::HeldAnnounce { + raw: bytes::Bytes::copy_from_slice(raw), + destination_hash: header.destination_hash, + hops: header.hops, + receiving_interface_id: interface_id, + }); + debug!( + dest = hex::encode(header.destination_hash), + interface = interface_id, + "announce held by ingress controller (burst active)" + ); + return; + } + } + + let mut rate_blocked = false; + + // Per-interface rate limiting is opt-in and suppresses rebroadcast + // only; Python still learns the path, updates caches and dispatches + // handlers for blocked announces. Path responses bypass this gate. + let has_interface_rate_limit = header.context + != rns_wire::context::PacketContext::PathResponse + && self + .interfaces + .get(&interface_id) + .is_some_and(|entry| entry.announce_rate_target.is_some()); + if has_interface_rate_limit + && let Some(entry) = self.interfaces.get(&interface_id) + && let Some(target) = entry.announce_rate_target + && self.rate_table.check_interface_rate( + header.destination_hash, + target, + entry.announce_rate_grace.unwrap_or(0), + entry.announce_rate_penalty.unwrap_or(0.0), + ) + { + debug!( + dest = hex::encode(header.destination_hash), + interface = interface_id, + "announce blocked by per-interface rate limit" + ); + rate_blocked = true; + } else { + // Always record non-interface-limited announces for observability. + // `check_interface_rate` already stores its own timestamp state. + self.rate_table.record(header.destination_hash); + } + + let ( + announce_app_data, + announce_public_key, + announce_ratchet, + announce_name_hash, + announce_identity_hash, + announce_random_hash, + ) = { + if data_offset >= raw.len() { + tracing::warn!( + dest = hex::encode(header.destination_hash), + "announce missing payload, dropping" + ); + return; + } + + let payload = &raw[data_offset..]; + let has_ratchet = header.flags.context_flag; + tracing::debug!( + dest = hex::encode(header.destination_hash), + payload_len = payload.len(), + has_ratchet = has_ratchet, + header_type = ?header.flags.header_type, + "announce payload received" + ); + match rns_identity::announce::AnnounceData::unpack(payload, has_ratchet) { + Ok(announce_data) => { + tracing::debug!( + dest = hex::encode(header.destination_hash), + app_data_len = announce_data.app_data.as_ref().map(|d| d.len()), + has_ratchet_key = announce_data.ratchet.is_some(), + "announce unpacked" + ); + let known_public_key = self + .recent_announces + .get(&header.destination_hash) + .and_then(|entry| entry.public_key); + match announce_data.validate_with_known_key( + &header.destination_hash, + known_public_key.as_ref(), + ) { + Ok(validated_identity) => { + if self.blackhole_table.is_blackholed(&validated_identity.hash) { + trace!( + identity = hex::encode(validated_identity.hash), + dest = hex::encode(header.destination_hash), + "announce from blackholed identity, dropping" + ); + return; + } + + tracing::debug!( + dest = hex::encode(header.destination_hash), + app_data_present = announce_data.app_data.is_some(), + "announce validated" + ); + ( + announce_data.app_data.clone(), + Some(validated_identity.get_public_key()), + announce_data.ratchet, + announce_data.name_hash, + Some(validated_identity.hash), + announce_data.random_hash, + ) + } + Err(e) => { + tracing::warn!( + dest = hex::encode(header.destination_hash), + payload_len = payload.len(), + error = %e, + "announce validation failed, dropping" + ); + return; + } + } + } + Err(e) => { + tracing::warn!( + dest = hex::encode(header.destination_hash), + payload_len = payload.len(), + has_ratchet = has_ratchet, + error = %e, + "announce unpack failed, dropping" + ); + return; + } + } + }; + + let iface_mode = self + .interfaces + .get(&interface_id) + .map(|e| e.mode) + .unwrap_or(InterfaceMode::Gateway); + + let announce_emitted = announce_timebase(&announce_random_hash); + + // Cancel our queued rebroadcast when a neighbor already carried it. + // Same-hop neighbor rebroadcast counts toward the local cap; + // strict hops+1 forward drops our queued copy outright. + if self.is_transport_enabled + && let Some(existing) = self.announce_table.get(&header.destination_hash) + { + let existing_hops = existing.hops; + let existing_retries = existing.retries; + if header.hops > 0 && header.hops - 1 == existing_hops && existing_retries > 0 { + let existing_local_rebroadcasts = existing.local_rebroadcasts + 1; + if existing_local_rebroadcasts >= LOCAL_REBROADCASTS_MAX { + debug!( + dest = hex::encode(header.destination_hash), + "announce dedup: local rebroadcast limit reached, removing from table" + ); + self.announce_table.remove(&header.destination_hash); + } else if let Some(ae) = self.announce_table.get_mut(&header.destination_hash) { + ae.local_rebroadcasts = existing_local_rebroadcasts; + } + } + if header.hops > 0 && header.hops - 1 == existing_hops + 1 && existing_retries > 0 { + let now = now_f64(); + if let Some(ae) = self.announce_table.get(&header.destination_hash) + && now < ae.retransmit_timeout + { + debug!( + dest = hex::encode(header.destination_hash), + "announce dedup: passed on by another node, cancelling rebroadcast" + ); + self.announce_table.remove(&header.destination_hash); + } + } + } + + let mut random_blobs = self + .path_table + .get(&header.destination_hash) + .map(|entry| entry.random_blobs.clone()) + .unwrap_or_default(); + let should_add = if let Some(existing) = self.path_table.get(&header.destination_hash) { + let random_seen = existing.has_random_blob(&announce_random_hash); + let path_timebase = path_timebase_from_random_blobs(existing.random_blobs.iter()); + if header.hops <= existing.hops { + !random_seen && announce_emitted > path_timebase + } else if existing.is_expired() || announce_emitted > path_timebase { + !random_seen + } else if announce_emitted == path_timebase { + self.path_table.get_state(&header.destination_hash) + == crate::constants::PathState::Unresponsive + } else { + false + } + } else { + true + }; + + if should_add { + // Announce-table update MUST precede path-table update — the dedup + // check above compares against our own queued copy. Non-transport + // nodes never queue (would amplify the announce per hub). + if !rate_blocked + && (self.is_transport_enabled || is_from_local_client) + && header.context != rns_wire::context::PacketContext::PathResponse + && header.hops < PATHFINDER_M + { + let now = now_f64(); + let mut rebroadcast_raw = raw.to_vec(); + if rebroadcast_raw.len() >= 2 { + rebroadcast_raw[1] = header.hops.saturating_add(1); + } + let announce_entry = crate::announce::AnnounceEntry { + timestamp: now, + retransmit_timeout: if is_from_local_client { + now + } else { + now + rand_window() + }, + retries: 0, + received_from: header.transport_id.unwrap_or(header.destination_hash), + hops: header.hops, + packet_raw: rebroadcast_raw, + local_rebroadcasts: 0, + block_rebroadcast: false, + attached_interface: None, + source_interface: Some(interface_id), + }; + self.announce_table + .insert(header.destination_hash, announce_entry); + } + + // For Header2 announces via a transport node, next_hop is the relay's + // hash from transport_id; for Header1 announces the destination is + // directly reachable and next_hop stays None. + let mut entry = crate::path_table::PathEntry::new( + header.transport_id, + header.hops, + interface_id, + iface_mode, + ); + if !random_blobs.contains(&announce_random_hash) { + if random_blobs.len() >= MAX_RANDOM_BLOBS { + random_blobs.pop_front(); + } + random_blobs.push_back(announce_random_hash); + } + entry.random_blobs = random_blobs; + // Store the announce packet hash so a later CacheRequest for this + // destination can replay the exact announce bytes. + entry.packet_hash = Some(rns_wire::hash::packet_hash(raw, header.flags.header_type)); + self.path_table.insert(header.destination_hash, entry); + self.state_dirty = true; + // Wake any callers waiting on a path for this destination. + self.fire_path_waiters(&header.destination_hash); + + if let Some(request) = self + .discovery_path_requests + .get(&header.destination_hash) + .copied() + { + let response = self.path_response_from_cached_announce( + raw, + header.destination_hash, + header.hops, + ); + self.send_to_interface(request.requesting_interface, &response); + } + + debug!( + dest = hex::encode(header.destination_hash), + hops = header.hops, + next_hop = ?header.transport_id.map(hex::encode), + "path learned from announce" + ); + } else { + debug!( + dest = hex::encode(header.destination_hash), + hops = header.hops, + announce_emitted, + "ignoring replayed or stale announce" + ); + } + + // Diagnostics + identity cache. `retained` pins survive re-announce so + // a fresh announce never silently un-pins an RPC-retained destination. + // Bounded by `cleanup_known_destinations` (7-day eviction); no count cap. + let now_ts = now_f64(); + let raw_vec = raw.to_vec(); + let app_data_for_handlers = announce_app_data.clone(); + match self.recent_announces.entry(header.destination_hash) { + std::collections::hash_map::Entry::Occupied(mut o) => { + let e = o.get_mut(); + e.hops = header.hops; + e.app_data = announce_app_data; + e.timestamp = now_ts; + e.public_key = announce_public_key; + e.ratchet = announce_ratchet; + e.raw_packet = raw_vec; + e.name_hash = announce_name_hash; + } + std::collections::hash_map::Entry::Vacant(v) => { + v.insert(RecentAnnounce { + dest_hash: header.destination_hash, + hops: header.hops, + app_data: announce_app_data, + timestamp: now_ts, + public_key: announce_public_key, + ratchet: announce_ratchet, + raw_packet: raw_vec, + retained: false, + name_hash: announce_name_hash, + }); + self.state_dirty = true; + } + } + + if is_from_local_client + && header.context == rns_wire::context::PacketContext::PathResponse + && let Some(waiting_interface) = self + .pending_local_path_requests + .remove(&header.destination_hash) + { + let response = + self.path_response_from_cached_announce(raw, header.destination_hash, header.hops); + self.send_to_interface(waiting_interface, &response); + } + + self.send_announce_to_local_clients( + raw, + header.destination_hash, + header.hops, + Some(interface_id), + rns_wire::context::PacketContext::None, + ); + + // Aspect-filtered handler dispatch: for handlers with a non-None + // `aspect_filter`, fire only when + // `hash_from_name_and_identity(filter, identity_hash) == destination_hash`. + // Without a validated identity, filtered handlers are skipped. + if !self.announce_handlers.is_empty() { + let handler_app_data = app_data_for_handlers; + let is_path_response = header.context == rns_wire::context::PacketContext::PathResponse; + let announce_packet_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type); + for registration in &self.announce_handlers { + if is_path_response && !registration.receive_path_responses { + continue; + } + if let Some(filter) = ®istration.aspect_filter { + let Some(ref ih) = announce_identity_hash else { + continue; + }; + let expected = + rns_identity::destination::Destination::hash_from_name_and_identity( + filter, + Some(ih), + ); + if expected != header.destination_hash { + continue; + } + } + let _ = registration + .tx + .try_send(crate::messages::AnnounceHandlerEvent { + destination_hash: header.destination_hash, + identity_hash: announce_identity_hash, + announce_packet_hash, + is_path_response, + hops: header.hops, + app_data: handler_app_data.clone(), + public_key: announce_public_key, + ratchet: announce_ratchet, + name_hash: announce_name_hash, + }); + } + } + } + + /// Well-known PLAIN destination hash for tunnel-synthesis announces. + fn tunnel_synthesize_dest_hash() -> [u8; 16] { + rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.tunnel.synthesize", + None, + ) + } + + /// Well-known PLAIN destination hash for path-request packets. + fn path_request_dest_hash() -> [u8; 16] { + rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.path.request", + None, + ) + } + + fn process_data( + &mut self, + raw: &bytes::Bytes, + header: &rns_wire::header::PacketHeader, + interface_id: InterfaceId, + ) { + let from_local_client = self.is_local_client_interface(interface_id); + let for_local_client = self + .path_table + .get(&header.destination_hash) + .is_some_and(|path| self.is_local_client_interface(path.interface_id)); + + let path_request_dest = Self::path_request_dest_hash(); + let tunnel_synth_dest = Self::tunnel_synthesize_dest_hash(); + let is_control_plain = header.destination_hash == path_request_dest + || header.destination_hash == tunnel_synth_dest; + + if !is_control_plain + && header.flags.destination_type == rns_wire::flags::DestinationType::Plain + && header.flags.transport_type == rns_wire::flags::TransportType::Broadcast + { + if from_local_client { + self.broadcast_on_interfaces(raw, Some(interface_id)); + } else { + for id in self.local_client_interface_ids_except(Some(interface_id)) { + self.send_to_interface(id, raw); + } + } + } + + // Reverse entries only exist to route proofs back through us, so a + // non-transport node has no reason to keep one unless it is acting for + // a local shared client. + if self.is_transport_enabled || from_local_client { + let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type); + self.reverse_table + .insert(pkt_hash, interface_id, header.hops); + } + + if self.route_link_packet_via_link_table(raw, header, interface_id, "data") { + return; + } + + if header.destination_hash == path_request_dest { + if let Some(payload_start) = self.data_payload_offset(raw, header) { + let payload = &raw[payload_start..]; + self.handle_inbound_path_request(payload, interface_id); + } + return; + } + + // Tunnel-synthesis: validate the Ed25519 signature, install the + // tunnel, and replay any cached paths for it. Uses TUNNEL_TIMEOUT + // (short) rather than DESTINATION_TIMEOUT (long) because the + // tunnel-layer binding is more volatile than identity lifetime. + if header.destination_hash == tunnel_synth_dest { + if let Some(payload_start) = self.data_payload_offset(raw, header) { + let payload = &raw[payload_start..]; + if let Some(synth_data) = crate::tunnel::TunnelSynthesisData::unpack(payload) { + let ed25519_pub_bytes: [u8; 32] = { + let mut buf = [0u8; 32]; + // First 32 bytes of the 64-byte public_key blob are + // the Ed25519 signing key; remaining 32 are X25519. + buf.copy_from_slice(&synth_data.public_key[..32]); + buf + }; + + match rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&ed25519_pub_bytes) { + Ok(verify_key) => { + let mut signed_data = Vec::with_capacity(112); + signed_data.extend_from_slice(&synth_data.public_key); + signed_data.extend_from_slice(&synth_data.interface_hash); + signed_data.extend_from_slice(&synth_data.random_hash); + + if verify_key + .verify(&signed_data, &synth_data.signature) + .is_ok() + { + let tunnel_id = synth_data.tunnel_id(); + debug!( + tunnel_id = hex::encode(&tunnel_id[..16]), + interface_id, "tunnel synthesis request validated" + ); + crate::tunnel::handle_tunnel( + &mut self.tunnel_table, + tunnel_id, + interface_id, + TUNNEL_TIMEOUT as f64, + ); + self.state_dirty = true; + + self.restore_tunnel_paths(&tunnel_id, interface_id); + } else { + debug!( + interface_id, + "tunnel synthesis signature verification failed" + ); + } + } + Err(_) => { + debug!(interface_id, "tunnel synthesis invalid Ed25519 public key"); + } + } + } else { + trace!(interface_id, "tunnel synthesis data too short or malformed"); + } + } + return; + } + + if header.context == rns_wire::context::PacketContext::PathResponse { + let iface_mode = self + .interfaces + .get(&interface_id) + .map(|e| e.mode) + .unwrap_or(InterfaceMode::Gateway); + let entry = crate::path_table::PathEntry::new( + Some(header.destination_hash), + header.hops, + interface_id, + iface_mode, + ); + self.path_table.insert(header.destination_hash, entry); + self.state_dirty = true; + self.fire_path_waiters(&header.destination_hash); + debug!( + dest = hex::encode(header.destination_hash), + "path learned from PathResponse" + ); + return; + } + + if header.context == rns_wire::context::PacketContext::CacheRequest { + self.handle_cache_request(raw, header, interface_id); + return; + } + + tracing::info!( + dest = %hex::encode(header.destination_hash), + is_local = self.local_destinations.contains(&header.destination_hash), + has_channel = self.destination_channels.contains_key(&header.destination_hash), + registered_dests = ?self.local_destinations.iter().map(hex::encode).collect::>(), + "data packet routing" + ); + if self.local_destinations.contains(&header.destination_hash) { + if let Some(tx) = self.destination_channels.get(&header.destination_hash) + && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { + raw: raw.clone(), + interface_id, + }) + { + self.channel_drops += 1; + warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver InboundPacket to local destination (channel full)"); + } + return; + } + + if (self.is_transport_enabled || from_local_client || for_local_client) + && let Some(path) = self.path_table.get(&header.destination_hash) + { + let target_interface = path.interface_id; + let mut forwarded = raw.to_vec(); + if forwarded.len() >= 2 { + forwarded[1] = header.hops.saturating_add(1); + } + self.send_to_interface(target_interface, &forwarded); + trace!( + dest = hex::encode(header.destination_hash), + via_interface = target_interface, + "data packet forwarded" + ); + } + } + + fn process_link_request( + &mut self, + raw: &bytes::Bytes, + header: &rns_wire::header::PacketHeader, + interface_id: InterfaceId, + ) { + let from_local_client = self.is_local_client_interface(interface_id); + let for_local_client = self + .path_table + .get(&header.destination_hash) + .is_some_and(|path| self.is_local_client_interface(path.interface_id)); + + if self.is_transport_enabled || from_local_client { + let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type); + self.reverse_table + .insert(pkt_hash, interface_id, header.hops); + } + + if self.local_destinations.contains(&header.destination_hash) { + if let Some(tx) = self.destination_channels.get(&header.destination_hash) + && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::LinkRequest { + raw: raw.clone(), + interface_id, + }) + { + self.channel_drops += 1; + error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver LinkRequest; link establishment will fail"); + } + return; + } + + if (self.is_transport_enabled || from_local_client || for_local_client) + && let Some(path) = self.path_table.get(&header.destination_hash) + { + let target_interface = path.interface_id; + let remaining_hops = path.hops; + let next_hop = path.next_hop; + let mut forwarded = raw.to_vec(); + if forwarded.len() >= 2 { + forwarded[1] = header.hops.saturating_add(1); + } + self.send_to_interface(target_interface, &forwarded); + + // Cache the relay so the matching LRPROOF can be routed back to + // the initiator without a fresh path lookup. Proof timeout scales + // with remaining hops and adds a serialization allowance for + // slow outbound interfaces. + let link_id = rns_wire::hash::link_id_from_raw(raw, header.flags.header_type); + let now = now_f64(); + let base_timeout = 60.0 * (remaining_hops.max(1) as f64); + let extra_timeout = if let Some(iface) = self.interfaces.get(&target_interface) { + let bitrate = iface.bitrate.max(1) as f64; + (raw.len() as f64 * 8.0) / bitrate + } else { + 0.0 + }; + let proof_timeout = now + base_timeout + extra_timeout; + let link_entry = crate::link_table::LinkEntry { + timestamp: now, + next_hop, + interface_id: target_interface, + remaining_hops, + destination_hash: header.destination_hash, + established: false, + validated: false, + proof_timeout, + receiving_interface: interface_id, + taken_hops: header.hops, + }; + self.link_table.insert(link_id, link_entry); + + debug!( + link_id = hex::encode(link_id), + dest = hex::encode(header.destination_hash), + receiving = interface_id, + outbound = target_interface, + remaining_hops, + "link table relay entry created" + ); + + trace!( + dest = hex::encode(header.destination_hash), + via_interface = target_interface, + "link request forwarded" + ); + } + } + + fn process_proof( + &mut self, + raw: &bytes::Bytes, + header: &rns_wire::header::PacketHeader, + _interface_id: InterfaceId, + ) { + let from_local_client = self.is_local_client_interface(_interface_id); + let for_local_client_link = + self.link_table + .get(&header.destination_hash) + .is_some_and(|entry| { + self.is_local_client_interface(entry.receiving_interface) + || self.is_local_client_interface(entry.interface_id) + }); + let proof_for_local_client = self + .reverse_table + .get(&header.destination_hash) + .is_some_and(|entry| self.is_local_client_interface(entry.receiving_interface)); + + if let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash) { + let rtt = receipt + .get_rtt() + .or_else(|| Some(receipt.sent_at.elapsed())); + receipt.deliver(); + + if let Some(msg_id) = self.receipt_msg_ids.remove(&header.destination_hash) { + debug!( + msg_id = %msg_id, + trunc = hex::encode(header.destination_hash), + "delivery proof received for outbound message" + ); + // Broadcast the DeliveryProof to every destination channel — + // we don't know which local identity originated the outbound + // message, so LXMF filters by msg_id on its side. + for (dest_hash, tx) in &self.destination_channels { + if let Err(e) = + tx.try_send(crate::link_messages::DestinationEvent::DeliveryProof { + msg_id: msg_id.clone(), + rtt, + }) + { + self.channel_drops += 1; + error!(dest = hex::encode(dest_hash), msg_id = %msg_id, drops = self.channel_drops, err = %e, + "failed to deliver DeliveryProof; sender will not receive confirmation"); + } + } + } + self.receipt_table.remove(&header.destination_hash); + return; + } + + // Link-request proofs route back via the link_table to the interface + // the original request arrived on. + // + // Hop-count note: proofs start at hops=0 at the destination. Python + // auto-increments hops on receipt; we do not, so the equivalence is + // `hops+1 == remaining_hops` here and we bump hops on forward so the + // next relay sees the expected value. + if header.context == rns_wire::context::PacketContext::Lrproof { + if (self.is_transport_enabled || from_local_client || for_local_client_link) + && self.link_table.contains(&header.destination_hash) + && let Some(link_entry) = self.link_table.get(&header.destination_hash) + { + let expected_hops = link_entry.remaining_hops; + let outbound_interface = link_entry.interface_id; + let target_interface = link_entry.receiving_interface; + + // Require that the proof arrived on the same interface we + // forwarded the request to; a mismatch is either a routing + // change or a spoof and must not be relayed. + let hops_match = if expected_hops == 0 { + header.hops == 0 + } else { + header.hops.saturating_add(1) == expected_hops + }; + if hops_match && _interface_id == outbound_interface { + let mut forwarded = raw.to_vec(); + if forwarded.len() >= 2 { + forwarded[1] = header.hops.saturating_add(1); + } + if let Some(entry) = self.link_table.get_mut(&header.destination_hash) { + entry.validated = true; + } + self.send_to_interface(target_interface, &forwarded); + debug!( + link_id = hex::encode(header.destination_hash), + via_interface = target_interface, + hops = header.hops + 1, + "link proof (LRPROOF) routed via link table" + ); + return; + } else if !hops_match { + warn!( + link_id = hex::encode(header.destination_hash), + expected_hops, + actual_hops = header.hops, + "link proof hop mismatch, not transporting (expected hops+1 == remaining_hops)" + ); + } else { + warn!( + link_id = hex::encode(header.destination_hash), + expected_interface = outbound_interface, + actual_interface = _interface_id, + "link proof received on wrong interface, not transporting" + ); + } + } + + // Fall through to local-pending-link delivery when link_table + // didn't claim the proof. + if let Some(tx) = self.destination_channels.get(&header.destination_hash) + && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { + raw: raw.clone(), + interface_id: _interface_id, + }) + { + self.channel_drops += 1; + warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver LRPROOF to local pending link (channel full)"); + } + return; + } + + if self.route_link_packet_via_link_table(raw, header, _interface_id, "proof") { + return; + } + + // Data-packet proofs route back via the reverse_table. When the + // entry records the outbound interface we forwarded on, enforce the + // match — a proof on the wrong interface means a routing change or + // a spoof. Older entries without that field route unconditionally. + if (self.is_transport_enabled || from_local_client || proof_for_local_client) + && let Some(reverse_entry) = self.reverse_table.remove(&header.destination_hash) + { + if let Some(expected_outbound) = reverse_entry.outbound_interface { + if _interface_id != expected_outbound { + debug!( + dest = hex::encode(header.destination_hash), + expected = expected_outbound, + actual = _interface_id, + "proof arrived on wrong interface, not routing via reverse table" + ); + } else { + let target_interface = reverse_entry.receiving_interface; + self.send_to_interface(target_interface, raw); + trace!( + dest = hex::encode(header.destination_hash), + via_interface = target_interface, + "proof routed via reverse table" + ); + return; + } + } else { + let target_interface = reverse_entry.receiving_interface; + self.send_to_interface(target_interface, raw); + trace!( + dest = hex::encode(header.destination_hash), + via_interface = target_interface, + "proof routed via reverse table" + ); + return; + } + } + + if let Some(tx) = self.destination_channels.get(&header.destination_hash) + && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { + raw: raw.clone(), + interface_id: _interface_id, + }) + { + self.channel_drops += 1; + error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver link proof to local link"); + } + } + + fn route_link_packet_via_link_table( + &mut self, + raw: &[u8], + header: &rns_wire::header::PacketHeader, + interface_id: InterfaceId, + packet_kind: &'static str, + ) -> bool { + if header.flags.destination_type != rns_wire::flags::DestinationType::Link + || self.local_destinations.contains(&header.destination_hash) + { + return false; + } + + let Some(entry) = self.link_table.get(&header.destination_hash).cloned() else { + return false; + }; + + let shared_client_path = self.is_local_client_interface(interface_id) + || self.is_local_client_interface(entry.receiving_interface) + || self.is_local_client_interface(entry.interface_id); + if !self.is_transport_enabled && !shared_client_path { + return false; + } + + let target_interface = if interface_id == entry.receiving_interface { + entry.interface_id + } else if interface_id == entry.interface_id { + entry.receiving_interface + } else { + warn!( + link_id = hex::encode(header.destination_hash), + interface_id, + receiving_interface = entry.receiving_interface, + outbound_interface = entry.interface_id, + "link packet arrived on interface outside link table path, not transporting" + ); + return false; + }; + + let mut forwarded = raw.to_vec(); + if forwarded.len() >= 2 { + forwarded[1] = header.hops.saturating_add(1); + } + if let Some(entry) = self.link_table.get_mut(&header.destination_hash) { + entry.timestamp = now_f64(); + } + self.send_to_interface(target_interface, &forwarded); + trace!( + link_id = hex::encode(header.destination_hash), + via_interface = target_interface, + hops = header.hops.saturating_add(1), + packet_kind, + "link packet routed via link table" + ); + true + } +} diff --git a/crates/rns-transport/src/actor/maintenance.rs b/crates/rns-transport/src/actor/maintenance.rs new file mode 100644 index 0000000..e7184ef --- /dev/null +++ b/crates/rns-transport/src/actor/maintenance.rs @@ -0,0 +1,463 @@ +use super::*; + +impl TransportActor { + pub(super) fn on_tick(&mut self) { + let now = now_f64(); + + // Startup grace delays cache cleanup so freshly restored entries + // aren't immediately aged out before the first traffic arrives. + if !self.startup_complete + && self.startup_time > 0.0 + && now - self.startup_time >= STARTUP_GRACE_PERIOD + { + self.startup_complete = true; + debug!("startup grace period complete, cache cleaning enabled"); + } + + // Periodic routing-state flush. Gated on `state_dirty`. Required in + // addition to `on_shutdown` because mobile force-quit kills the + // process without delivering Shutdown. Hashlist is saved separately. + if self.storage_dir.is_some() + && self.state_dirty + && now - self.last_state_save >= STATE_SAVE_INTERVAL_SECS + { + self.save_routing_state(); + } + + if now - self.last_tables_cull >= TABLES_CULL_INTERVAL { + // Batched culls bound per-tick work; on large tables a single + // sweep would stall the actor and back up the inbound channel. + self.path_table.cull_expired_batch(100); + self.reverse_table.cull_expired_batch(100); + self.tunnel_table.cull_expired_batch(50); + + // Drop entries pointing to interfaces that have gone away — + // those routes could never be used anyway. + let active_interfaces: HashSet = self.interfaces.keys().copied().collect(); + self.path_table.cull_dead_interfaces(&active_interfaces); + self.reverse_table.cull_dead_interfaces(&active_interfaces); + self.link_table.cull_dead_interfaces(&active_interfaces); + + // An unvalidated link whose proof window elapsed means the + // cached path is probably stale — expire it and re-resolve so + // the next attempt doesn't hammer a dead route. + let (_, expired_dests) = self.link_table.cull_stale(LINK_TIMEOUT); + for dest_hash in expired_dests { + self.path_table.expire(&dest_hash); + self.on_path_request(dest_hash); + debug!( + dest = hex::encode(dest_hash), + "unvalidated link expired -- path expired and re-discovery triggered" + ); + } + + // Cull may have removed path/tunnel entries — flag for save so + // the on-disk file reflects the current routing state. False + // positives (cull found nothing) cost one no-op file rewrite at + // the next 10 s tick. + self.state_dirty = true; + self.last_tables_cull = now; + } + + if now - self.last_announces_check >= ANNOUNCES_CHECK_INTERVAL { + let due = self.announce_table.due_for_retransmit(now); + for hash in due { + let send_info = self.announce_table.get(&hash).map(|e| { + ( + e.packet_raw.clone(), + e.source_interface, + e.attached_interface, + e.block_rebroadcast, + ) + }); + if let Some((raw, _source_iface, Some(attached_interface), true)) = send_info { + self.send_to_interface(attached_interface, &raw); + self.announce_table.remove(&hash); + if let Some(held_entry) = self.held_announces.remove(hash.as_bytes()) { + self.announce_table.insert(*hash.as_bytes(), held_entry); + } + continue; + } + if let Some(entry) = self.announce_table.get_mut(&hash) { + entry.retries += 1; + entry.retransmit_timeout = now + PATHFINDER_G + rand_window(); + } + // Never retransmit back out the interface the announce came + // in on — that's just loopback and will cause dedup churn. + if let Some((raw, source_iface, _, _)) = send_info { + self.broadcast_announce_on_interfaces(&raw, source_iface); + } + } + self.announce_table.cull_exhausted(PATHFINDER_R); + self.last_announces_check = now; + } + + if now - self.last_held_announce_check >= IC_HELD_RELEASE_INTERVAL { + self.process_held_announces(now); + self.last_held_announce_check = now; + } + + self.cull_announce_queues(now); + + if now - self.last_blackhole_check >= BLACKHOLE_CHECK_INTERVAL { + self.blackhole_table.cull_expired(); + self.state_dirty = true; + self.last_blackhole_check = now; + } + + // IngressController is self-maintaining (bounded deque + held cap), + // so only the rate table needs a periodic sweep. + if now - self.last_rate_cull >= BLACKHOLE_CHECK_INTERVAL { + self.rate_table.cull(now - 3600.0); + self.last_rate_cull = now; + } + + if now - self.last_links_check >= LINKS_CHECK_INTERVAL { + self.traffic.update_speeds(); + self.last_links_check = now; + } + + if now - self.last_receipts_check >= RECEIPTS_CHECK_INTERVAL { + for receipt in self.receipt_table.values_mut() { + if receipt.status == ReceiptStatus::Sent && receipt.is_timed_out() { + receipt.fail(); + } + } + // Only in-flight (Sent) receipts are worth keeping; concluded + // ones (Delivered/Failed/Culled) were already signalled out. + self.receipt_table + .retain(|_, r| r.status == ReceiptStatus::Sent); + while self.receipt_table.len() > MAX_RECEIPTS { + if let Some(oldest_key) = self + .receipt_table + .iter() + .min_by_key(|(_, r)| r.sent_at) + .map(|(k, _)| *k) + { + if let Some(r) = self.receipt_table.get_mut(&oldest_key) { + r.cull(); + } + self.receipt_table.remove(&oldest_key); + } + } + self.last_receipts_check = now; + } + + if self.startup_complete && now - self.last_cache_clean >= CACHE_CLEAN_INTERVAL { + self.packet_hashlist.force_rotate(); + self.cleanup_known_destinations(now); + self.last_cache_clean = now; + } + + self.expire_path_waiters(now); + + // Drop pending path-request markers older than 30 s so a retried + // request isn't treated as "still in flight". + self.path_requests.retain(|_, last| now - *last < 30.0); + self.discovery_path_requests + .retain(|_, request| now < request.timeout); + self.discovery_pr_tags + .retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT); + + self.process_announce_queues(now); + } + + /// Called on background → foreground. Resets every `last_*_check` so the + /// next `on_tick` runs all maintenance paths in one go. + pub(super) fn on_resume(&mut self) { + debug!("transport actor resume — forcing maintenance pass"); + self.last_tables_cull = 0.0; + self.last_links_check = 0.0; + self.last_receipts_check = 0.0; + self.last_announces_check = 0.0; + self.last_cache_clean = 0.0; + self.last_blackhole_check = 0.0; + self.last_rate_cull = 0.0; + self.last_held_announce_check = 0.0; + } + + /// Drain per-interface announce queues one entry per spacing window + /// (shortest hops, oldest among ties). Spacing comes from + /// `packet_time / announce_cap`; stale entries past QUEUED_ANNOUNCE_LIFE drop. + pub(super) fn process_announce_queues(&mut self, now: f64) { + let iface_ids: Vec = self.interfaces.keys().copied().collect(); + for iface_id in iface_ids { + let should_process = if let Some(entry) = self.interfaces.get(&iface_id) { + !entry.announce_queue.is_empty() + && now >= entry.announce_allowed_at + && entry.direction.outbound + } else { + false + }; + + if !should_process { + continue; + } + + if let Some(entry) = self.interfaces.get_mut(&iface_id) { + entry + .announce_queue + .retain(|a| now - a.time < QUEUED_ANNOUNCE_LIFE); + } + + let selected = if let Some(entry) = self.interfaces.get(&iface_id) { + if entry.announce_queue.is_empty() { + None + } else { + let min_hops = entry + .announce_queue + .iter() + .map(|e| e.hops) + .min() + .unwrap_or(0); + entry + .announce_queue + .iter() + .enumerate() + .filter(|(_, e)| e.hops == min_hops) + .min_by(|(_, a), (_, b)| { + a.time + .partial_cmp(&b.time) + .unwrap_or(std::cmp::Ordering::Equal) + }) + .map(|(idx, e)| (idx, e.raw.clone())) + } + } else { + None + }; + + if let Some((idx, raw)) = selected { + self.send_to_interface(iface_id, &raw); + + if let Some(entry) = self.interfaces.get_mut(&iface_id) { + let bitrate = entry.bitrate.max(1) as f64; + let packet_time = (raw.len() as f64 * 8.0) / bitrate; + let announce_delay = packet_time / entry.announce_cap.max(0.001); + entry.announce_allowed_at = now + announce_delay; + + if idx < entry.announce_queue.len() { + entry.announce_queue.remove(idx); + } + } + } + } + } + + /// Release held announces with hop-priority and frequency checks; the + /// per-interface `IngressController` owns the selection logic. + fn process_held_announces(&mut self, _now: f64) { + let iface_ids: Vec = self.interfaces.keys().copied().collect(); + for iface_id in iface_ids { + let released = self + .interfaces + .get_mut(&iface_id) + .and_then(|iface| iface.ingress.try_release_held()); + + if let Some(announce) = released { + debug!( + dest = hex::encode(announce.destination_hash), + interface = iface_id, + "releasing held announce" + ); + + self.on_inbound(crate::messages::InboundPacket { + raw: announce.raw, + interface_id: announce.receiving_interface_id, + rssi: None, + snr: None, + q: None, + }); + } + } + } + + /// Sweep `recent_announces`. Keep retained + pathed entries; reap the + /// rest past `DESTINATION_TIMEOUT` (7 days). No count cap. + pub(super) fn cleanup_known_destinations(&mut self, now: f64) { + let threshold = DESTINATION_TIMEOUT as f64; + + let before = self.recent_announces.len(); + // Collect into a Vec; the has-path borrow on path_table fights an + // in-place `retain` closure on recent_announces. + let to_drop: Vec<[u8; 16]> = self + .recent_announces + .values() + .filter_map(|a| { + if a.retained { + return None; + } + if self.path_table.has_path(&a.dest_hash) { + return None; + } + let idle = now - a.timestamp; + if idle > threshold { + Some(a.dest_hash) + } else { + None + } + }) + .collect(); + + if !to_drop.is_empty() { + for hash in &to_drop { + self.recent_announces.remove(hash); + } + debug!( + removed = to_drop.len(), + remaining = self.recent_announces.len(), + before, + "known-destinations cleanup swept pathless entries" + ); + } + } + + /// Trim announce queues to age (QUEUED_ANNOUNCE_LIFE) and size + /// (MAX_QUEUED_ANNOUNCES). Oldest entries are dropped first so a burst + /// of fresh announces isn't starved by a backlog of stale ones. + pub(super) fn cull_announce_queues(&mut self, now: f64) { + for iface in self.interfaces.values_mut() { + iface + .announce_queue + .retain(|entry| now - entry.time < QUEUED_ANNOUNCE_LIFE); + if iface.announce_queue.len() > MAX_QUEUED_ANNOUNCES { + let excess = iface.announce_queue.len() - MAX_QUEUED_ANNOUNCES; + iface.announce_queue.drain(..excess); + } + } + } + + /// On interface drop: remove tunnel-bound paths and re-announce the + /// affected local destinations on remaining interfaces. + pub(super) fn void_tunnel_interface(&mut self, interface_id: InterfaceId) { + let mut voided_destinations: Vec<[u8; 16]> = Vec::new(); + + let tunnel_ids: Vec<[u8; 32]> = self + .tunnel_table + .iter() + .filter(|(_, entry)| entry.interface_id == interface_id) + .map(|(id, _)| *id) + .collect(); + + for tunnel_id in &tunnel_ids { + if let Some(tunnel) = self.tunnel_table.get(tunnel_id) { + for dest_hash in tunnel.tunnel_paths.keys() { + voided_destinations.push(*dest_hash); + self.path_table.remove(dest_hash); + self.state_dirty = true; + } + } + if let Some(tunnel) = self.tunnel_table.get_mut(tunnel_id) { + // Sentinel 0 marks the tunnel as bound to no interface until + // a fresh synthesis arrives and rebinds it. + tunnel.interface_id = 0; + debug!( + tunnel_id = hex::encode(&tunnel_id[..16]), + "voided tunnel interface" + ); + } + } + + for dest_hash in &voided_destinations { + if self.local_destinations.contains(dest_hash) + && let Some(tx) = self.destination_channels.get(dest_hash) + && let Err(e) = + tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested( + crate::link_messages::AnnounceRequest::normal(String::new()), + )) + { + self.channel_drops += 1; + warn!(dest = hex::encode(dest_hash), drops = self.channel_drops, err = %e, + "failed to send re-announce after tunnel void (channel full)"); + } + } + } +} + +#[cfg(test)] +mod cleanup_tests { + use super::*; + use crate::actor::RecentAnnounce; + use crate::path_table::PathEntry; + + fn insert_entry(actor: &mut TransportActor, hash: u8, timestamp: f64, retained: bool) { + let entry = RecentAnnounce { + dest_hash: [hash; 16], + hops: 0, + app_data: None, + timestamp, + public_key: None, + ratchet: None, + raw_packet: Vec::new(), + retained, + name_hash: [0u8; 10], + }; + actor.recent_announces.insert(entry.dest_hash, entry); + } + + #[test] + fn retained_survives_cleanup() { + let (mut actor, _tx) = TransportActor::new(); + let now = 10_000.0; + insert_entry(&mut actor, 0x01, 0.0, /*retained=*/ true); + actor.cleanup_known_destinations(now); + assert_eq!(actor.recent_announces.len(), 1); + } + + #[test] + fn pathed_entry_survives_cleanup() { + let (mut actor, _tx) = TransportActor::new(); + let now = 10_000.0; + let dest = [0x02; 16]; + insert_entry(&mut actor, 0x02, 0.0, /*retained=*/ false); + actor + .path_table + .insert(dest, PathEntry::new(None, 1, 0, InterfaceMode::Gateway)); + actor.cleanup_known_destinations(now); + assert_eq!(actor.recent_announces.len(), 1); + } + + // Pre-collapse, a never-used pathless entry was reaped after 6 min. + // Under the uniform 7-d policy, an entry only ten minutes old survives. + #[test] + fn pathless_kept_well_below_destination_timeout() { + let (mut actor, _tx) = TransportActor::new(); + let now = 10_000.0; + let ten_minutes_old = now - 10.0 * 60.0; + insert_entry(&mut actor, 0x03, ten_minutes_old, /*retained=*/ false); + + actor.cleanup_known_destinations(now); + assert_eq!(actor.recent_announces.len(), 1); + } + + #[test] + fn pathless_reaped_past_destination_timeout() { + let (mut actor, _tx) = TransportActor::new(); + let now = 10_000_000.0; + let timeout = DESTINATION_TIMEOUT as f64; + insert_entry( + &mut actor, + 0x05, + now - timeout - 1.0, + /*retained=*/ false, + ); + + actor.cleanup_known_destinations(now); + assert!(actor.recent_announces.is_empty()); + } + + #[test] + fn pathless_kept_just_inside_destination_timeout() { + let (mut actor, _tx) = TransportActor::new(); + let now = 10_000_000.0; + let timeout = DESTINATION_TIMEOUT as f64; + insert_entry( + &mut actor, + 0x07, + now - timeout + 1.0, + /*retained=*/ false, + ); + + actor.cleanup_known_destinations(now); + assert_eq!(actor.recent_announces.len(), 1); + } +} diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs new file mode 100644 index 0000000..6659ac6 --- /dev/null +++ b/crates/rns-transport/src/actor/mod.rs @@ -0,0 +1,5778 @@ +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +use bytes::Bytes; +use tokio::sync::mpsc; +use tracing::{debug, error, trace, warn}; + +use crate::announce::AnnounceTable; +use crate::blackhole::BlackholeTable; +use crate::constants::*; +use crate::hashlist::PacketHashlist; +use crate::link_table::LinkTable; +use crate::messages::{ + InterfaceEntry, InterfaceId, InterfaceRole, TransportMessage, msg_variant_name, +}; +use crate::path_table::PathTable; +use crate::rate_limit::RateTable; +use crate::reverse_table::ReverseTable; +use crate::traffic::TrafficCounter; +use crate::tunnel::TunnelTable; +use rns_wire::receipt::{PacketReceipt, ReceiptStatus}; + +mod inbound; +mod maintenance; +mod outbound; +mod persistence; +mod rpc; + +/// Owns every routing table and drains the `TransportMessage` channel in one +/// task. The single-owner model means the hot path has no shared state and no +/// locks — callers drive the actor by sending typed commands rather than +/// reaching into the tables directly. +pub struct TransportActor { + rx: mpsc::Receiver, + + pub path_table: PathTable, + pub link_table: LinkTable, + pub announce_table: AnnounceTable, + /// Python `held_announces`: normal queued announces temporarily displaced + /// while a known-path response occupies `announce_table`. + pub held_announces: HashMap<[u8; 16], crate::announce::AnnounceEntry>, + pub reverse_table: ReverseTable, + pub tunnel_table: TunnelTable, + pub packet_hashlist: PacketHashlist, + pub rate_table: RateTable, + pub blackhole_table: BlackholeTable, + pub traffic: TrafficCounter, + pub packet_metrics: HashMap<[u8; 32], PacketMetrics>, + pub packet_metrics_order: VecDeque<[u8; 32]>, + + pub receipt_table: HashMap<[u8; 16], PacketReceipt>, + /// Truncated packet hash → LXMF msg_id for pairing delivery proofs back + /// to their originating outbound message. + pub receipt_msg_ids: HashMap<[u8; 16], String>, + + pub interfaces: HashMap, + + pub local_destinations: HashSet<[u8; 16]>, + pub destination_channels: + HashMap<[u8; 16], mpsc::Sender>, + pub path_requests: HashMap<[u8; 16], f64>, + /// Python `discovery_path_requests`: external interfaces waiting for a + /// matching announce while this transport recursively searches elsewhere. + pub discovery_path_requests: HashMap<[u8; 16], DiscoveryPathRequest>, + /// Python `discovery_pr_tags`: destination hash plus truncated path-request tag. + pub discovery_pr_tags: HashMap, f64>, + /// External interface waiting for a path response from a local shared client. + /// Python calls this `pending_local_path_requests`. + pub pending_local_path_requests: HashMap<[u8; 16], InterfaceId>, + pub path_states: HashMap<[u8; 16], PathState>, + + /// Tasks blocked on `AwaitPath`. Each entry pairs the oneshot reply with + /// the registration timestamp so `expire_path_waiters` can bound how long + /// a caller can wait before receiving a negative result. + pub path_waiters: HashMap<[u8; 16], Vec<(tokio::sync::oneshot::Sender, f64)>>, + + last_tables_cull: f64, + last_links_check: f64, + last_receipts_check: f64, + last_announces_check: f64, + last_cache_clean: f64, + last_blackhole_check: f64, + last_rate_cull: f64, + last_held_announce_check: f64, + + pub is_transport_enabled: bool, + pub transport_identity_hash: Option<[u8; 16]>, + pub blackhole_sources: Vec<[u8; 16]>, + + /// True when connected to a shared Reticulum instance — the transport + /// defers to the shared instance for routing decisions rather than + /// originating them locally. + pub is_shared_instance: bool, + + pub storage_dir: Option, + + /// Last save (Unix seconds) — gates the periodic save tick. 0 forces an + /// initial baseline write after `SetStoragePaths`. + pub last_state_save: f64, + + /// Set when persisted-state mutates; cleared after each `save_state`. + /// Gates the periodic tick so idle devices don't spin disk uselessly. + pub state_dirty: bool, + + /// Persisted path entries waiting on their interface to re-register. + /// Drained by `drain_pending_for_interface` on `RegisterInterface`. + pub pending_path_entries: Vec, + /// Tunnel-table equivalent of `pending_path_entries`. + pub pending_tunnel_entries: Vec, + + /// Cache of recently learnt announces, keyed by dest_hash for O(1) upsert. + pub recent_announces: HashMap<[u8; 16], RecentAnnounce>, + + /// Grace window before cache cleaning runs — protects freshly restored + /// entries from being aged out before real traffic refreshes them. + startup_complete: bool, + startup_time: f64, + + /// Try_send failures into destination channels (diagnostic gauge). + pub channel_drops: u64, + + announce_handlers: Vec, + + /// Foreground/background flag shared with the app layer. Flipping to + /// background switches the maintenance tick to the long interval so the + /// actor stops burning CPU (and battery) while the app is suspended. + pub is_foreground: Arc, +} + +/// Cached announce for diagnostics + CacheRequest replay. `raw_packet` keeps +/// byte-identical replay; `retained` pins the entry against the cull sweep +/// (toggled via `RetainDestination` / `UnretainDestination`). +#[derive(Debug, Clone)] +pub struct RecentAnnounce { + pub dest_hash: [u8; 16], + pub hops: u8, + pub app_data: Option>, + pub timestamp: f64, + pub public_key: Option<[u8; 64]>, + pub ratchet: Option<[u8; 32]>, + pub raw_packet: Vec, + pub retained: bool, + /// `SHA-256(app_name)[:10]` so cache consumers can filter by aspect + /// without re-parsing `raw_packet`. Zeroed if the announce had no payload. + pub name_hash: [u8; 10], +} + +#[derive(Debug, Clone, Copy)] +pub struct DiscoveryPathRequest { + pub requesting_interface: InterfaceId, + pub timeout: f64, +} + +struct AnnounceHandlerRegistration { + aspect_filter: Option, + receive_path_responses: bool, + tx: tokio::sync::mpsc::Sender, +} + +#[derive(Debug, Clone, Copy, Default)] +pub struct PacketMetrics { + pub rssi: Option, + pub snr: Option, + pub q: Option, +} + +impl TransportActor { + pub fn new() -> (Self, mpsc::Sender) { + Self::new_with_capacity(4096, HASHLIST_MAXSIZE) + } + + /// Benchmarks at scale override both caps to avoid running the host out of + /// memory with synthetic traffic. + pub fn new_with_capacity( + channel_cap: usize, + hashlist_cap: usize, + ) -> (Self, mpsc::Sender) { + let (tx, rx) = mpsc::channel(channel_cap); + + let actor = Self { + rx, + path_table: PathTable::new(), + link_table: LinkTable::new(), + announce_table: AnnounceTable::new(), + held_announces: HashMap::new(), + reverse_table: ReverseTable::new(), + tunnel_table: TunnelTable::new(), + packet_hashlist: PacketHashlist::new_with_capacity(hashlist_cap), + rate_table: RateTable::new(), + blackhole_table: BlackholeTable::new(), + traffic: TrafficCounter::new(), + packet_metrics: HashMap::new(), + packet_metrics_order: VecDeque::new(), + receipt_table: HashMap::new(), + receipt_msg_ids: HashMap::new(), + interfaces: HashMap::new(), + local_destinations: HashSet::new(), + destination_channels: HashMap::new(), + path_requests: HashMap::new(), + discovery_path_requests: HashMap::new(), + discovery_pr_tags: HashMap::new(), + pending_local_path_requests: HashMap::new(), + path_states: HashMap::new(), + path_waiters: HashMap::new(), + last_tables_cull: 0.0, + last_links_check: 0.0, + last_receipts_check: 0.0, + last_announces_check: 0.0, + last_cache_clean: 0.0, + last_blackhole_check: 0.0, + last_rate_cull: 0.0, + last_held_announce_check: 0.0, + is_transport_enabled: false, + transport_identity_hash: None, + blackhole_sources: Vec::new(), + is_shared_instance: false, + storage_dir: None, + last_state_save: 0.0, + state_dirty: false, + pending_path_entries: Vec::new(), + pending_tunnel_entries: Vec::new(), + recent_announces: HashMap::new(), + startup_complete: false, + startup_time: 0.0, + channel_drops: 0, + announce_handlers: Vec::new(), + is_foreground: Arc::new(AtomicBool::new(true)), + }; + + (actor, tx) + } + + /// Run the actor event loop. Messages are processed sequentially so no + /// routing state is ever touched from two tasks at once. + pub async fn run(mut self) { + let mut tick_interval = tokio::time::interval(Duration::from_millis(JOB_INTERVAL_MS)); + let mut was_foreground = true; + + loop { + tokio::select! { + msg = self.rx.recv() => { + match msg { + Some(TransportMessage::Shutdown) | None => { + self.on_shutdown(); + break; + } + Some(msg) => self.handle_message(msg), + } + } + _ = tick_interval.tick() => { + let is_fg = self.is_foreground.load(std::sync::atomic::Ordering::Relaxed); + if is_fg != was_foreground { + if is_fg { + // Foreground resume: full maintenance pass now. + self.on_resume(); + } else { + // Background: flush state so an OS kill (force-quit, + // OOM) cannot lose this session's learnings. + self.save_state(); + } + #[cfg(feature = "mobile-throttle")] + { + let ms = if is_fg { JOB_INTERVAL_MS } else { JOB_INTERVAL_BG_MS }; + tick_interval = tokio::time::interval(Duration::from_millis(ms)); + tick_interval.tick().await; + } + was_foreground = is_fg; + } + self.on_tick(); + } + } + } + } + + fn handle_message(&mut self, msg: TransportMessage) { + let variant = msg_variant_name(&msg); + let _span = + tracing::span!(tracing::Level::DEBUG, "actor.handle_message", msg = variant).entered(); + match msg { + TransportMessage::Inbound(packet) => { + self.on_inbound(packet); + } + TransportMessage::Outbound(request) => { + self.on_outbound(request); + } + TransportMessage::OutboundAttached { + request, + interface_id, + } => { + self.on_outbound_attached(request, interface_id); + } + TransportMessage::Tick(_) => { + self.on_tick(); + } + TransportMessage::RegisterDestination { + hash, + app_name, + delivery_tx, + } => { + self.local_destinations.insert(hash); + if let Some(tx) = delivery_tx { + self.destination_channels.insert(hash, tx.clone()); + // On a shared-instance connection, the destination is + // brand new to the shared peer; fire an announce so it + // learns the path immediately instead of waiting for the + // next scheduled broadcast. + if self.is_shared_instance { + if let Err(e) = + tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested( + crate::link_messages::AnnounceRequest::normal(app_name.clone()), + )) + { + self.channel_drops += 1; + warn!(dest = hex::encode(hash), drops = self.channel_drops, err = %e, + "failed to send AnnounceRequested (channel full)"); + } + debug!( + dest = hex::encode(hash), + "auto-announce triggered for shared instance registration" + ); + } + } + } + TransportMessage::DeregisterDestination { hash } => { + self.local_destinations.remove(&hash); + self.destination_channels.remove(&hash); + } + TransportMessage::CacheRequest { + packet_hash, + destination_hash, + } => { + // Walk the path table by packet_hash to find the destination + // that announced this packet, then replay the cached announce + // through our own inbound path (interface_id=0 marks it as + // locally injected, not from the wire). + let local_hit = self + .path_table + .iter() + .find(|(_, entry)| entry.packet_hash == Some(packet_hash)) + .map(|(dest, _)| *dest.as_bytes()); + + if let Some(dest) = local_hit + && let Some(cached) = self.recent_announces.get(&dest) + && !cached.raw_packet.is_empty() + { + debug!(hash = %hex::encode(&packet_hash[..8]), "cache request: local hit, replaying"); + let inbound = crate::messages::InboundPacket { + raw: Bytes::copy_from_slice(&cached.raw_packet), + interface_id: 0, + rssi: None, + snr: None, + q: None, + }; + self.on_inbound(inbound); + return; + } + + // Local miss: only transport nodes forward the request + // outward — a leaf can't usefully relay a cache query. + if self.is_transport_enabled { + debug!(hash = %hex::encode(&packet_hash[..8]), "cache request: local miss, querying network"); + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash, + context: rns_wire::context::PacketContext::CacheRequest, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&packet_hash); + self.broadcast_on_interfaces(&raw, None); + } + } + TransportMessage::RequestPath { destination_hash } => { + self.on_path_request(destination_hash); + } + TransportMessage::Rpc { query, response_tx } => { + let response = self.handle_query(query); + let _ = response_tx.send(response); + } + TransportMessage::RegisterAnnounceHandler { + aspect_filter, + receive_path_responses, + callback_tx, + } => { + self.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter, + receive_path_responses, + tx: callback_tx, + }); + } + TransportMessage::DeregisterAnnounceHandler { aspect_filter } => { + // Also sweep closed channels here so deregister doubles as + // garbage-collection for handlers whose owner dropped + // without explicitly unregistering. + self.announce_handlers.retain(|registration| { + if registration.tx.is_closed() { + return false; + } + if let Some(ref target) = aspect_filter { + registration.aspect_filter.as_ref() != Some(target) + } else { + true + } + }); + } + TransportMessage::SetTransportEnabled { enabled } => { + debug!(enabled, "setting transport enabled"); + self.is_transport_enabled = enabled; + } + TransportMessage::SetTransportIdentity { identity_hash } => { + debug!( + hash = hex::encode(identity_hash), + "setting transport identity" + ); + self.transport_identity_hash = Some(identity_hash); + self.load_python_blackhole_if_ready(); + } + TransportMessage::SetBlackholeSources { sources } => { + debug!(count = sources.len(), "setting blackhole sources"); + self.blackhole_sources = sources; + self.load_python_blackhole_if_ready(); + } + TransportMessage::SharedConnectionLost => { + tracing::warn!("shared instance connection lost — suspending transport"); + self.is_shared_instance = false; + self.clear_shared_connection_state(); + } + TransportMessage::SharedConnectionRestored { interface_id } => { + tracing::info!(interface_id, "shared instance connection restored"); + self.is_shared_instance = true; + self.request_announces_from_local_destinations(); + } + TransportMessage::SynthesizeTunnel { + interface_id, + raw_packet, + } => { + debug!( + interface_id, + len = raw_packet.len(), + "sending tunnel synthesis packet" + ); + self.send_to_interface(interface_id, &raw_packet); + } + TransportMessage::RegisterInterface { id, entry } => { + let is_outbound = entry.direction.outbound; + let iface_name = entry.name.clone(); + let role = entry.role; + debug!(id, name = %iface_name, outbound = is_outbound, role = role.as_str(), "registering interface"); + self.interfaces.insert(id, entry); + if !self.startup_complete && self.startup_time == 0.0 { + self.startup_time = now_f64(); + } + // Rebind any persisted path/tunnel entries that referenced + // this interface by name. Done immediately on register so + // queries from other code (e.g. announce replay below) see + // the restored paths. + self.drain_pending_for_interface(id, &iface_name); + // Replay cached announces so a freshly connected peer learns + // the known destinations immediately. Important for relay + // topologies where announces arrived before any clients did. + if role == InterfaceRole::LocalClient && is_outbound { + self.replay_recent_announces_to_local_client(id); + } else if self.is_transport_enabled && is_outbound { + let announces: Vec> = self + .announce_table + .iter() + .map(|(_, entry)| entry.packet_raw.clone()) + .collect(); + if !announces.is_empty() { + debug!( + id, + count = announces.len(), + "replaying cached announces to new interface" + ); + for raw in &announces { + self.send_to_interface(id, raw); + } + } + } + } + TransportMessage::DeregisterInterface { id } => { + debug!(id, "deregistering interface"); + self.deregister_interface(id); + } + TransportMessage::SetStoragePaths { storage_dir } => { + debug!(path = %storage_dir.display(), "setting storage paths"); + self.storage_dir = Some(storage_dir); + self.load_state(); + } + TransportMessage::RegisterReceipt { + truncated_hash, + full_hash, + msg_id, + timeout, + } => { + let receipt = PacketReceipt::new( + full_hash, + truncated_hash, + Some(timeout.unwrap_or(std::time::Duration::from_secs(180))), + ); + self.receipt_table.insert(truncated_hash, receipt); + self.receipt_msg_ids.insert(truncated_hash, msg_id); + debug!( + trunc = hex::encode(truncated_hash), + "registered receipt for outbound LXMF message" + ); + } + TransportMessage::RegisterLink { + link_id, + destination_hash, + interface_id, + next_hop, + remaining_hops, + initiator, + } => { + // Initiators start pending (validated=false) until the proof + // arrives; non-initiators already hold a validated link. + let now = now_f64(); + let entry = crate::link_table::LinkEntry { + timestamp: now, + next_hop, + interface_id, + remaining_hops, + destination_hash, + established: !initiator, + validated: !initiator, + proof_timeout: now + 60.0, + receiving_interface: interface_id, + taken_hops: 0, + }; + self.link_table.insert(link_id, entry); + + // Link-addressed packets (LRRTT, Resource, Keepalive, …) use + // link_id as their destination_hash, not the original + // destination hash. Register link_id as a local destination + // and route it to the parent's channel; otherwise those + // packets hit the data router and get dropped as unroutable. + self.local_destinations.insert(link_id); + if let Some(tx) = self.destination_channels.get(&destination_hash) { + self.destination_channels.insert(link_id, tx.clone()); + } + + debug!(link_id = hex::encode(link_id), initiator, "registered link"); + } + TransportMessage::ActivateLink { link_id } => { + if let Some(entry) = self.link_table.get_mut(&link_id) { + entry.validated = true; + entry.established = true; + debug!(link_id = hex::encode(link_id), "activated link"); + } else { + tracing::warn!( + link_id = hex::encode(link_id), + "attempted to activate link not in pending table" + ); + } + } + TransportMessage::AwaitPath { dest, reply } => { + if self.path_table.has_path(&dest) { + let _ = reply.send(true); + } else { + let now = now_f64(); + self.path_waiters + .entry(dest) + .or_default() + .push((reply, now)); + debug!(dest = hex::encode(dest), "registered path waiter"); + } + } + TransportMessage::Shutdown => unreachable!(), + } + } + + fn is_local_client_interface(&self, id: InterfaceId) -> bool { + self.interfaces + .get(&id) + .is_some_and(|entry| entry.role == InterfaceRole::LocalClient) + } + + fn has_local_client_interfaces(&self) -> bool { + self.interfaces + .values() + .any(|entry| entry.role == InterfaceRole::LocalClient) + } + + fn local_client_interface_ids_except(&self, except: Option) -> Vec { + self.interfaces + .iter() + .filter_map(|(&id, entry)| { + if except == Some(id) || entry.role != InterfaceRole::LocalClient { + None + } else { + Some(id) + } + }) + .collect() + } + + fn clear_shared_connection_state(&mut self) { + self.path_table = PathTable::new(); + self.link_table = LinkTable::new(); + self.announce_table = AnnounceTable::new(); + self.held_announces.clear(); + self.reverse_table = ReverseTable::new(); + self.tunnel_table = TunnelTable::new(); + self.packet_metrics.clear(); + self.packet_metrics_order.clear(); + self.discovery_path_requests.clear(); + self.pending_local_path_requests.clear(); + self.state_dirty = true; + } + + fn record_packet_metrics(&mut self, packet_hash: [u8; 32], metrics: PacketMetrics) { + if metrics.rssi.is_none() && metrics.snr.is_none() && metrics.q.is_none() { + return; + } + if !self.packet_metrics.contains_key(&packet_hash) { + self.packet_metrics_order.push_back(packet_hash); + } + self.packet_metrics.insert(packet_hash, metrics); + while self.packet_metrics_order.len() > LOCAL_CLIENT_CACHE_MAXSIZE { + if let Some(old_hash) = self.packet_metrics_order.pop_front() { + self.packet_metrics.remove(&old_hash); + } + } + } + + fn request_announces_from_local_destinations(&mut self) { + let destinations: Vec<( + [u8; 16], + mpsc::Sender, + )> = self + .destination_channels + .iter() + .map(|(hash, tx)| (*hash, tx.clone())) + .collect(); + for (hash, tx) in destinations { + if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested( + crate::link_messages::AnnounceRequest::normal(String::new()), + )) { + self.channel_drops += 1; + warn!(dest = hex::encode(hash), drops = self.channel_drops, err = %e, + "failed to send AnnounceRequested after shared instance reconnect"); + } + } + } + + fn replay_recent_announces_to_local_client(&mut self, interface_id: InterfaceId) { + let announces: Vec> = self + .recent_announces + .values() + .filter(|announce| !announce.raw_packet.is_empty()) + .map(|announce| { + self.transport_announce_from_raw( + &announce.raw_packet, + announce.dest_hash, + announce.hops, + rns_wire::context::PacketContext::None, + ) + }) + .collect(); + + if !announces.is_empty() { + debug!( + interface_id, + count = announces.len(), + "replaying recent announces to local shared client" + ); + } + for raw in announces { + self.send_to_interface(interface_id, &raw); + } + } + + fn send_announce_to_local_clients( + &mut self, + cached_raw: &[u8], + destination_hash: [u8; 16], + hops: u8, + except: Option, + context: rns_wire::context::PacketContext, + ) { + let ids = self.local_client_interface_ids_except(except); + if ids.is_empty() { + return; + } + let raw = self.transport_announce_from_raw(cached_raw, destination_hash, hops, context); + for id in ids { + self.send_to_interface(id, &raw); + } + } + + fn transport_announce_from_raw( + &self, + cached_raw: &[u8], + destination_hash: [u8; 16], + hops: u8, + context: rns_wire::context::PacketContext, + ) -> Vec { + let Ok((cached_header, payload_offset)) = + rns_wire::header::PacketHeader::unpack(cached_raw) + else { + return cached_raw.to_vec(); + }; + + let Some(transport_id) = self.transport_identity_hash else { + return cached_raw.to_vec(); + }; + + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header2, + context_flag: cached_header.flags.context_flag, + transport_type: rns_wire::flags::TransportType::Transport, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }, + hops, + transport_id: Some(transport_id), + destination_hash, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&cached_raw[payload_offset..]); + raw + } + + /// Returns the number of waiters that were notified. + fn fire_path_waiters(&mut self, dest: &[u8; 16]) -> usize { + if let Some(waiters) = self.path_waiters.remove(dest) { + let n = waiters.len(); + for (reply, _created_at) in waiters { + let _ = reply.send(true); + } + debug!(dest = hex::encode(dest), count = n, "fired path waiters"); + n + } else { + 0 + } + } + + /// Pin an entry so `cleanup` never reaps it. Exposed via `RetainDestination`. + #[allow(dead_code)] + pub(super) fn retain_destination(&mut self, dest_hash: &[u8; 16]) -> bool { + if let Some(entry) = self.recent_announces.get_mut(dest_hash) { + entry.retained = true; + self.state_dirty = true; + true + } else { + false + } + } + + /// Mark a destination's cached metadata as used, matching Python's + /// `_used_destination_data` refresh semantics for shared clients. + pub(super) fn use_destination(&mut self, dest_hash: &[u8; 16]) -> bool { + if let Some(entry) = self.recent_announces.get_mut(dest_hash) { + entry.timestamp = now_f64(); + self.state_dirty = true; + true + } else { + false + } + } + + /// Release a pin set by `retain_destination`; cleanup runs by `timestamp` again. + #[allow(dead_code)] + pub(super) fn unretain_destination(&mut self, dest_hash: &[u8; 16]) -> bool { + if let Some(entry) = self.recent_announces.get_mut(dest_hash) { + entry.retained = false; + self.state_dirty = true; + true + } else { + false + } + } + + /// Send `false` to any waiter that has been parked longer than + /// `PATH_WAITER_TIMEOUT`, so a caller that lost its chance to race with + /// a learned path doesn't wait forever. + fn expire_path_waiters(&mut self, now: f64) { + const PATH_WAITER_TIMEOUT: f64 = 15.0; + + // Remove-then-reinsert dodges the simultaneous mutable borrow that + // would otherwise happen when partitioning in place. + let keys: Vec<[u8; 16]> = self.path_waiters.keys().copied().collect(); + for dest in keys { + if let Some(waiters) = self.path_waiters.remove(&dest) { + let mut kept = Vec::new(); + for (reply, created_at) in waiters { + if now - created_at >= PATH_WAITER_TIMEOUT { + let _ = reply.send(false); + } else { + kept.push((reply, created_at)); + } + } + if !kept.is_empty() { + self.path_waiters.insert(dest, kept); + } + } + } + } + + /// Drop `id` from the interface table and unwind tunnels + paths bound + /// to it. Shared by `DeregisterInterface` and the `Closed`-tx auto-drop. + fn deregister_interface(&mut self, id: InterfaceId) { + let role = self.interfaces.get(&id).map(|entry| entry.role); + self.void_tunnel_interface(id); + let dropped = self.path_table.drop_all_via(id); + if dropped > 0 { + debug!(id, dropped, "dropped paths via deregistered interface"); + } + self.pending_local_path_requests + .retain(|_, waiting_interface| *waiting_interface != id); + self.discovery_path_requests + .retain(|_, request| request.requesting_interface != id); + self.interfaces.remove(&id); + if role == Some(InterfaceRole::SharedInstancePeer) { + tracing::warn!( + interface_id = id, + "shared instance peer interface deregistered — clearing shared routing state" + ); + self.is_shared_instance = false; + self.clear_shared_connection_state(); + } + } + + /// Send raw bytes on `id`, IFAC-wrapping first if configured. + /// + /// `try_send` failures: `Full` bumps `tx_drops`; `Closed` auto-deregisters + /// (zombie interface — receiver dropped without DeregisterInterface). + #[tracing::instrument( + level = "trace", + name = "actor.send_to_interface", + skip_all, + fields(interface_id = id, raw_len = raw.len()), + )] + fn send_to_interface(&mut self, id: InterfaceId, raw: &[u8]) { + let Some(entry) = self.interfaces.get(&id) else { + return; + }; + if !entry.direction.outbound { + return; + } + let data: Bytes = if let Some(ref ifac_key) = entry.ifac_key { + Bytes::from(crate::ifac::ifac_sign(raw, ifac_key, entry.ifac_size)) + } else { + Bytes::copy_from_slice(raw) + }; + match entry.tx.try_send(data) { + Ok(()) => {} + Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => { + entry + .tx_drops + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + tracing::error!( + interface_id = id, + interface_name = %entry.name, + queue_remaining = entry.tx.capacity(), + queue_max = entry.tx.max_capacity(), + tx_drops = entry.tx_drops.load(std::sync::atomic::Ordering::Relaxed), + "PACKET DROPPED: interface TX channel full" + ); + } + Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => { + tracing::info!( + interface_id = id, + interface_name = %entry.name, + "interface TX channel closed (downstream task exited); auto-deregistering" + ); + self.deregister_interface(id); + } + } + } + + #[tracing::instrument( + level = "trace", + name = "actor.broadcast_on_interfaces", + skip_all, + fields(raw_len = raw.len()), + )] + fn broadcast_on_interfaces(&mut self, raw: &[u8], except: Option) { + // Collect ids first so the borrow on self.interfaces ends before + // send_to_interface (which may mutate it via auto-deregister) runs. + let ids: Vec = self + .interfaces + .iter() + .filter_map(|(&id, entry)| { + if except == Some(id) || !entry.direction.outbound { + None + } else { + Some(id) + } + }) + .collect(); + for id in ids { + self.send_to_interface(id, raw); + } + } + + fn interface_allows_announce( + &self, + id: InterfaceId, + destination_hash: &[u8; 16], + except: Option, + ) -> bool { + let Some(entry) = self.interfaces.get(&id) else { + return false; + }; + if except == Some(id) || !entry.direction.outbound { + return false; + } + + match entry.mode { + InterfaceMode::AccessPoint => false, + InterfaceMode::Roaming => { + if self.local_destinations.contains(destination_hash) { + return true; + } + let Some(path) = self.path_table.get(destination_hash) else { + return false; + }; + !matches!( + self.interfaces + .get(&path.interface_id) + .map(|iface| iface.mode), + Some(InterfaceMode::Roaming | InterfaceMode::Boundary) | None + ) + } + InterfaceMode::Boundary => { + if self.local_destinations.contains(destination_hash) { + return true; + } + let Some(path) = self.path_table.get(destination_hash) else { + return false; + }; + !matches!( + self.interfaces + .get(&path.interface_id) + .map(|iface| iface.mode), + Some(InterfaceMode::Roaming) | None + ) + } + InterfaceMode::Full | InterfaceMode::PointToPoint | InterfaceMode::Gateway => true, + } + } + + fn broadcast_local_announce_on_interfaces(&mut self, raw: &[u8], except: Option) { + let destination_hash = rns_wire::header::PacketHeader::unpack(raw) + .ok() + .map(|(h, _)| h.destination_hash) + .unwrap_or([0u8; 16]); + let ids: Vec = self + .interfaces + .keys() + .copied() + .filter(|id| self.interface_allows_announce(*id, &destination_hash, except)) + .collect(); + for id in ids { + self.send_to_interface(id, raw); + if let Some(entry) = self.interfaces.get_mut(&id) { + entry.ingress.sent_announce(); + } + } + } + + /// Enqueue an announce on every eligible outbound interface (except + /// optionally one). Eligibility mirrors Python's AP/roaming/boundary mode + /// gates. Enqueueing lets `process_announce_queues` apply ANNOUNCE_CAP + /// spacing and hop priority. + fn broadcast_announce_on_interfaces(&mut self, raw: &[u8], except: Option) { + let destination_hash = rns_wire::header::PacketHeader::unpack(raw) + .ok() + .map(|(h, _)| h.destination_hash) + .unwrap_or([0u8; 16]); + let hops = raw.get(1).copied().unwrap_or(0); + let now = now_f64(); + // One copy at the boundary; per-interface queue entries clone the + // shared Arc for free. + let shared = Bytes::copy_from_slice(raw); + + let ids: Vec = self + .interfaces + .keys() + .copied() + .filter(|id| self.interface_allows_announce(*id, &destination_hash, except)) + .collect(); + + for id in ids { + let Some(entry) = self.interfaces.get_mut(&id) else { + continue; + }; + entry.announce_queue.push(crate::messages::QueuedAnnounce { + destination_hash, + time: now, + hops, + raw: shared.clone(), + }); + if entry.announce_queue.len() > MAX_QUEUED_ANNOUNCES { + let excess = entry.announce_queue.len() - MAX_QUEUED_ANNOUNCES; + entry.announce_queue.drain(..excess); + } + } + } + + fn path_response_from_cached_announce( + &self, + cached_raw: &[u8], + destination_hash: [u8; 16], + hops: u8, + ) -> Vec { + let Ok((cached_header, payload_offset)) = + rns_wire::header::PacketHeader::unpack(cached_raw) + else { + return cached_raw.to_vec(); + }; + + let (header_type, transport_type, transport_id) = + if let Some(transport_id) = self.transport_identity_hash { + ( + rns_wire::flags::HeaderType::Header2, + rns_wire::flags::TransportType::Transport, + Some(transport_id), + ) + } else { + ( + cached_header.flags.header_type, + cached_header.flags.transport_type, + cached_header.transport_id, + ) + }; + + let flags = rns_wire::flags::PacketFlags { + header_type, + context_flag: cached_header.flags.context_flag, + transport_type, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id, + destination_hash, + context: rns_wire::context::PacketContext::PathResponse, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&cached_raw[payload_offset..]); + raw + } + + pub fn has_path(&self, dest_hash: &[u8; 16]) -> bool { + self.path_table.has_path(dest_hash) + } + + pub fn hops_to(&self, dest_hash: &[u8; 16]) -> Option { + self.path_table.hops_to(dest_hash) + } + + /// Test-only: flush all pending announce retransmits immediately, + /// bypassing `ANNOUNCES_CHECK_INTERVAL` and the per-entry retransmit + /// timeouts. Production code must never call this. + #[cfg(test)] + fn flush_pending_announces(&mut self) { + let far_future = now_f64() + 10.0; + let due = self.announce_table.due_for_retransmit(far_future); + for hash in due { + let send_info = self.announce_table.get(&hash).map(|e| { + ( + e.packet_raw.clone(), + e.source_interface, + e.attached_interface, + e.block_rebroadcast, + ) + }); + if let Some((raw, _source_iface, Some(attached_interface), true)) = send_info { + self.send_to_interface(attached_interface, &raw); + self.announce_table.remove(&hash); + if let Some(held_entry) = self.held_announces.remove(hash.as_bytes()) { + self.announce_table.insert(*hash.as_bytes(), held_entry); + } + continue; + } + if let Some(entry) = self.announce_table.get_mut(&hash) { + entry.retries += 1; + entry.retransmit_timeout = far_future + PATHFINDER_G + rand_window(); + } + if let Some((raw, source_iface, _, _)) = send_info { + self.broadcast_announce_on_interfaces(&raw, source_iface); + } + } + self.flush_announce_queues(); + } + + /// Test-only helper: drain every interface's announce queue synchronously, + /// bypassing the bandwidth-spacing gate. Mirrors what `process_announce_queues` + /// does but without the `now >= announce_allowed_at` check. + #[cfg(test)] + pub(crate) fn flush_announce_queues(&mut self) { + let iface_ids: Vec = self.interfaces.keys().copied().collect(); + for iface_id in iface_ids { + loop { + let next = match self.interfaces.get_mut(&iface_id) { + Some(entry) if !entry.announce_queue.is_empty() && entry.direction.outbound => { + Some(entry.announce_queue.remove(0).raw) + } + _ => None, + }; + match next { + Some(raw) => self.send_to_interface(iface_id, &raw), + None => break, + } + } + } + } +} + +fn now_f64() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64() +} + +fn announce_timebase(random_blob: &[u8; 10]) -> u64 { + let mut emitted = [0u8; 8]; + emitted[3..].copy_from_slice(&random_blob[5..10]); + u64::from_be_bytes(emitted) +} + +fn path_timebase_from_random_blobs<'a>(random_blobs: impl Iterator) -> u64 { + random_blobs.map(announce_timebase).max().unwrap_or(0) +} + +/// Random jitter in `[0, PATHFINDER_RW)` for announce rebroadcast timing. +/// The jitter avoids synchronized retransmits when many nodes learn the +/// same announce in the same tick. +fn rand_window() -> f64 { + use rand::Rng; + let mut rng = rand::thread_rng(); + let r: f64 = rng.r#gen(); + r * PATHFINDER_RW +} + +fn mode_discovers_unknown_paths(mode: InterfaceMode) -> bool { + matches!( + mode, + InterfaceMode::AccessPoint | InterfaceMode::Gateway | InterfaceMode::Roaming + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constants::InterfaceDirection; + use crate::messages::{InboundPacket, InterfaceEntry, OutboundRequest}; + + fn make_valid_announce(app_name: &str, hops: u8) -> (Bytes, [u8; 16]) { + let identity = rns_identity::identity::Identity::new(); + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let announce_data = + rns_identity::announce::AnnounceData::create(&identity, app_name, None, None).unwrap(); + let payload = announce_data.pack(); + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + (Bytes::from(raw), dest_hash) + } + + fn make_announce_for_with_random_blob( + identity: &rns_identity::identity::Identity, + app_name: &str, + hops: u8, + random_blob: [u8; 10], + ) -> (Bytes, [u8; 16]) { + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let public_key = identity.get_public_key(); + let name_hash = rns_identity::name_hash::name_hash(app_name); + let mut signed_data = Vec::new(); + signed_data.extend_from_slice(&dest_hash); + signed_data.extend_from_slice(&public_key); + signed_data.extend_from_slice(&name_hash); + signed_data.extend_from_slice(&random_blob); + let signature = identity.sign(&signed_data).unwrap(); + let announce_data = rns_identity::announce::AnnounceData { + public_key, + name_hash, + random_hash: random_blob, + ratchet: None, + signature, + app_data: None, + }; + let payload = announce_data.pack(); + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + (Bytes::from(raw), dest_hash) + } + + fn random_blob(prefix: u8, emitted: u64) -> [u8; 10] { + let mut blob = [prefix; 10]; + let emitted = emitted.to_be_bytes(); + blob[5..].copy_from_slice(&emitted[3..8]); + blob + } + + /// Dummy-payload variant with no valid signature — only for tests that + /// do not exercise announce validation. + #[allow(dead_code)] + fn make_announce_packet_for_identity( + dest_hash: [u8; 16], + hops: u8, + _identity: Option<&rns_identity::identity::Identity>, + ) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + // Add some payload to meet minimum packet requirements + raw.extend_from_slice(&[0u8; 32]); + Bytes::from(raw) + } + + fn make_data_packet(dest_hash: [u8; 16], hops: u8) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xDD; 32]); + Bytes::from(raw) + } + + fn make_link_data_packet(link_id: [u8; 16], hops: u8) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Resource, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xDA; 32]); + Bytes::from(raw) + } + + fn make_proof_packet(dest_hash: [u8; 16], hops: u8) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Proof, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xEE; 32]); + Bytes::from(raw) + } + + fn make_link_proof_packet(link_id: [u8; 16], hops: u8) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Proof, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::LinkProof, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xEF; 32]); + Bytes::from(raw) + } + + fn make_link_request_packet(dest_hash: [u8; 16], hops: u8) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::LinkRequest, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xCC; 32]); + Bytes::from(raw) + } + + fn make_test_interface(name: &str) -> (InterfaceEntry, mpsc::Receiver) { + let (tx, rx) = mpsc::channel(64); + let entry = InterfaceEntry { + name: name.to_string(), + mode: InterfaceMode::Gateway, + role: InterfaceRole::Normal, + direction: InterfaceDirection::bidirectional(), + bitrate: 115200, + mtu: 500, + tx, + ifac_key: None, + ifac_size: 0, + announce_cap: ANNOUNCE_CAP, + announce_allowed_at: 0.0, + announce_rate_target: None, + announce_rate_grace: None, + announce_rate_penalty: None, + online: None, + rxb: None, + txb: None, + tx_drops: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), + ingress: crate::ingress::IngressController::new(), + announce_queue: Vec::new(), + }; + (entry, rx) + } + + #[test] + fn test_actor_creation() { + let (actor, _tx) = TransportActor::new(); + assert!(actor.path_table.is_empty()); + assert!(actor.link_table.is_empty()); + assert!(actor.packet_hashlist.is_empty()); + } + + #[test] + fn test_register_destination() { + let (mut actor, _tx) = TransportActor::new(); + let hash = [0xAA; 16]; + actor.handle_message(TransportMessage::RegisterDestination { + hash, + app_name: "test.app".to_string(), + delivery_tx: None, + }); + assert!(actor.local_destinations.contains(&hash)); + } + + #[test] + fn test_deregister_destination() { + let (mut actor, _tx) = TransportActor::new(); + let hash = [0xAA; 16]; + actor.local_destinations.insert(hash); + actor.handle_message(TransportMessage::DeregisterDestination { hash }); + assert!(!actor.local_destinations.contains(&hash)); + } + + #[tokio::test] + async fn test_actor_shutdown() { + let (actor, tx) = TransportActor::new(); + let handle = tokio::spawn(actor.run()); + tx.send(TransportMessage::Shutdown).await.unwrap(); + handle.await.unwrap(); + } + + #[test] + fn test_register_interface() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("test_iface"); + actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry }); + assert!(actor.interfaces.contains_key(&1)); + assert_eq!(actor.interfaces.get(&1).unwrap().name, "test_iface"); + } + + #[test] + fn test_deregister_interface() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("test_iface"); + actor.interfaces.insert(1, entry); + actor.handle_message(TransportMessage::DeregisterInterface { id: 1 }); + assert!(!actor.interfaces.contains_key(&1)); + } + + #[test] + fn test_send_to_interface() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, mut rx) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry); + + let data = vec![0x01, 0x02, 0x03]; + actor.send_to_interface(1, &data); + + let received = rx.try_recv().unwrap(); + assert_eq!(received, data); + } + + #[test] + fn test_send_to_interface_inbound_only() { + let (mut actor, _tx) = TransportActor::new(); + let (mut entry, mut rx) = make_test_interface("iface_in"); + entry.direction = InterfaceDirection::inbound_only(); + actor.interfaces.insert(1, entry); + + actor.send_to_interface(1, &[0x01, 0x02]); + assert!(rx.try_recv().is_err()); // Should not have sent + } + + #[test] + fn test_broadcast_on_interfaces() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + let (entry3, mut rx3) = make_test_interface("iface3"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + actor.interfaces.insert(3, entry3); + + let data = vec![0xAA, 0xBB]; + actor.broadcast_on_interfaces(&data, Some(2)); + + // Interface 1 and 3 should receive, interface 2 (excluded) should not + assert!(rx1.try_recv().is_ok()); + assert!(rx2.try_recv().is_err()); + assert!(rx3.try_recv().is_ok()); + } + + /// Regression test for the SharedInstance zombie-interface leak + /// (investigated 2026-04-24): when an interface's tx receiver is dropped + /// without a matching `DeregisterInterface`, `send_to_interface` must + /// detect `TrySendError::Closed` on the first attempt and auto-reap the + /// entry so it can't absorb every subsequent broadcast into a dead + /// mailbox. Prior behavior logged `tx_drops` forever, accumulating tens + /// of thousands of dropped packets per minute. + #[test] + fn test_send_to_interface_auto_deregisters_closed_channel() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, rx) = make_test_interface("zombie"); + actor.interfaces.insert(7, entry); + assert!(actor.interfaces.contains_key(&7)); + + // Simulate the downstream write-loop exiting: the receiver is dropped + // while the sender (inside the interface entry) stays alive. + drop(rx); + + let data = vec![0xDE, 0xAD]; + actor.send_to_interface(7, &data); + + assert!( + !actor.interfaces.contains_key(&7), + "send_to_interface should reap entries whose tx channel is Closed" + ); + } + + /// Same scenario but via `broadcast_on_interfaces` — the collection + /// walker must tolerate self.interfaces mutation from the inner + /// auto-deregister path (we collect ids first to avoid the borrow). + #[test] + fn test_broadcast_reaps_closed_interface() { + let (mut actor, _tx) = TransportActor::new(); + let (entry_live, mut rx_live) = make_test_interface("live"); + let (entry_dead, rx_dead) = make_test_interface("dead"); + actor.interfaces.insert(1, entry_live); + actor.interfaces.insert(2, entry_dead); + drop(rx_dead); + + actor.broadcast_on_interfaces(&[0xAA], None); + + assert!(rx_live.try_recv().is_ok(), "live interface still receives"); + assert!(actor.interfaces.contains_key(&1)); + assert!( + !actor.interfaces.contains_key(&2), + "dead interface should be reaped by broadcast" + ); + } + + /// `DeregisterInterface` must be idempotent: a second message for the + /// same id (e.g. auto-deregister already fired, then an explicit + /// `DeregisterInterface { id }` arrives from the read-loop teardown in + /// `local.rs`) must not panic and must leave state untouched. + #[test] + fn test_duplicate_deregister_is_idempotent() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("twice"); + actor.interfaces.insert(9, entry); + + actor.handle_message(TransportMessage::DeregisterInterface { id: 9 }); + assert!(!actor.interfaces.contains_key(&9)); + + // Second deregister on a missing id: must be a no-op. + actor.handle_message(TransportMessage::DeregisterInterface { id: 9 }); + assert!(!actor.interfaces.contains_key(&9)); + + // And a deregister for an id that never existed. + actor.handle_message(TransportMessage::DeregisterInterface { id: 999 }); + } + + /// Deregistering an interface must cascade through every routing table + /// that points at it: paths via the interface, tunnels anchored to it, + /// and the interface entry itself all go away in one shot. + #[test] + fn test_deregister_cleans_path_and_tunnel_tables() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("doomed"); + actor.interfaces.insert(42, entry); + + // Install a path via interface 42 and a tunnel anchored on it. + let dest = [0x11; 16]; + actor.path_table.insert( + dest, + crate::path_table::PathEntry::new(None, 2, 42, InterfaceMode::Gateway), + ); + let tunnel_id = [0x22; 32]; + let mut tunnel_paths = std::collections::HashMap::new(); + tunnel_paths.insert( + dest, + crate::tunnel::TunnelPath { + timestamp: now_f64(), + hops: 2, + expires: now_f64() + 600.0, + random_blobs: vec![], + }, + ); + actor.tunnel_table.insert(crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: 42, + tunnel_paths, + expires: now_f64() + 600.0, + }); + + assert!(actor.path_table.has_path(&dest)); + assert_eq!(actor.tunnel_table.get(&tunnel_id).unwrap().interface_id, 42); + + actor.handle_message(TransportMessage::DeregisterInterface { id: 42 }); + + assert!( + !actor.interfaces.contains_key(&42), + "interface entry removed" + ); + assert!( + !actor.path_table.has_path(&dest), + "paths via the interface dropped" + ); + // Tunnel interface_id voided to 0 (matches void_tunnel_interface contract). + assert_eq!( + actor.tunnel_table.get(&tunnel_id).unwrap().interface_id, + 0, + "tunnel interface voided" + ); + } + + /// `RegisterInterface` with an id that's already in use replaces the + /// entry in place. The old `tx` is dropped, so anything still holding + /// the old `rx` observes `Closed` on the next recv. We cover this + /// deliberately because it's the failure mode if a reconnect raced a + /// deregister: the caller may have allocated a fresh id or reused one. + #[test] + fn test_register_over_existing_id_replaces_entry() { + let (mut actor, _tx) = TransportActor::new(); + let (entry_old, mut rx_old) = make_test_interface("old"); + actor.handle_message(TransportMessage::RegisterInterface { + id: 5, + entry: entry_old, + }); + + let (entry_new, mut rx_new) = make_test_interface("new"); + actor.handle_message(TransportMessage::RegisterInterface { + id: 5, + entry: entry_new, + }); + + assert_eq!(actor.interfaces.get(&5).unwrap().name, "new"); + + // A send on id=5 reaches the new receiver, not the old one. + actor.send_to_interface(5, &[0xAB]); + assert!(rx_new.try_recv().is_ok(), "new rx gets the packet"); + // Old rx sees the sender dropped — try_recv returns Disconnected. + assert!( + matches!( + rx_old.try_recv(), + Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) + ), + "old rx observes the old tx was dropped" + ); + } + + /// `on_inbound` must tolerate `InboundPacket { interface_id, .. }` where + /// `interface_id` is not in `self.interfaces`. This happens naturally + /// during teardown: a packet was enqueued by the read-loop just before + /// the deregister message fired, and arrives at the actor afterwards. + #[test] + fn test_inbound_packet_for_unknown_interface_id() { + let (mut actor, _tx) = TransportActor::new(); + // No interface registered. Fabricate a minimal packet header that + // decodes cleanly so we exercise the "unknown interface_id" path + // rather than the malformed-header path. + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: [0x33; 16], + context: rns_wire::context::PacketContext::None, + }; + let raw = header.pack(); + + let paths_before = actor.path_table.is_empty(); + let interfaces_before = actor.interfaces.len(); + + actor.on_inbound(crate::messages::InboundPacket { + interface_id: 12345, + raw: Bytes::from(raw), + rssi: None, + snr: None, + q: None, + }); + + assert_eq!( + actor.interfaces.len(), + interfaces_before, + "interface set untouched" + ); + assert_eq!( + actor.path_table.is_empty(), + paths_before, + "path table untouched" + ); + } + + #[test] + fn test_broadcast_announce_skips_access_point() { + // AccessPoint interfaces must not receive relayed announces. + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("full_iface"); + let (mut entry2, mut rx2) = make_test_interface("ap_iface"); + entry2.mode = InterfaceMode::AccessPoint; + let (entry3, mut rx3) = make_test_interface("gateway_iface"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + actor.interfaces.insert(3, entry3); + + let data = vec![0xAA, 0xBB]; + actor.broadcast_announce_on_interfaces(&data, None); + actor.flush_announce_queues(); + + // Full and Gateway should receive, AccessPoint should not + assert!(rx1.try_recv().is_ok()); + assert!(rx2.try_recv().is_err()); // AP skipped + assert!(rx3.try_recv().is_ok()); + } + + #[test] + fn test_announce_propagation() { + let (mut actor, _tx) = TransportActor::new(); + // Only transport-enabled nodes rebroadcast announces. + actor.is_transport_enabled = true; + let (entry1, mut _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let (raw, dest_hash) = make_valid_announce("test.propagation", 3); + + // Inject announce on interface 1 + actor.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Path table should have an entry + assert!(actor.path_table.has_path(&dest_hash)); + assert_eq!(actor.path_table.hops_to(&dest_hash), Some(3)); + + // Flush deferred announces (rebroadcast is now deferred via announce table) + actor.flush_pending_announces(); + + // Interface 2 should have received the rebroadcast (with hops incremented) + let rebroadcast = rx2.try_recv().unwrap(); + assert_eq!(rebroadcast[1], 4); // hops incremented from 3 to 4 + } + + #[test] + fn test_announce_not_rebroadcast_without_transport() { + let (mut actor, _tx) = TransportActor::new(); + // transport disabled (default) — should NOT rebroadcast + let (entry1, mut _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let (raw, dest_hash) = make_valid_announce("test.no_rebroadcast", 3); + + actor.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Path should still be learned + assert!(actor.path_table.has_path(&dest_hash)); + + // But announce should NOT be in announce_table for rebroadcast + actor.flush_pending_announces(); + assert!( + rx2.try_recv().is_err(), + "non-transport node should not rebroadcast announces" + ); + } + + #[test] + fn test_data_forwarding() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry1, mut _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + // Insert a path pointing to interface 2 + let dest_hash = [0x22; 16]; + let path_entry = crate::path_table::PathEntry::new( + Some([0xBB; 16]), + 2, + 2, // interface 2 + InterfaceMode::Gateway, + ); + actor.path_table.insert(dest_hash, path_entry); + + // Inject data on interface 1 + let raw = make_data_packet(dest_hash, 1); + actor.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Interface 2 should have received the forwarded packet + let forwarded = rx2.try_recv().unwrap(); + assert_eq!(forwarded[1], 2); // hops incremented from 1 to 2 + } + + #[test] + fn test_proof_routing() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; // reverse table + proof routing requires transport + + let (entry1, mut rx1) = make_test_interface("iface1"); + let (entry2, mut _rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + // Insert reverse entry: dest_hash -> interface 1 + let dest_hash = [0x33; 16]; + actor.reverse_table.insert(dest_hash, 1, 3); + + // Inject proof on interface 2 + let raw = make_proof_packet(dest_hash, 0); + actor.on_inbound(InboundPacket { + raw, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + // Interface 1 should have received the proof + let proof = rx1.try_recv().unwrap(); + assert!(!proof.is_empty()); + } + + #[test] + fn test_duplicate_rejection() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let (raw, _dest_hash) = make_valid_announce("test.duplicate", 0); + + // First inject + actor.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Drain rebroadcast + let _ = rx2.try_recv(); + + // Second inject of same packet — should be dropped as duplicate + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Interface 2 should NOT have received another rebroadcast + assert!(rx2.try_recv().is_err()); + } + + #[test] + fn test_link_request_forwarding() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + // Insert a path pointing to interface 2 + let dest_hash = [0x55; 16]; + let path_entry = + crate::path_table::PathEntry::new(Some([0xBB; 16]), 1, 2, InterfaceMode::Gateway); + actor.path_table.insert(dest_hash, path_entry); + + // Inject link request on interface 1 + let raw = make_link_request_packet(dest_hash, 0); + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Interface 2 should have received the forwarded link request + let forwarded = rx2.try_recv().unwrap(); + assert_eq!(forwarded[1], 1); // hops incremented from 0 to 1 + } + + fn make_lrproof_packet(link_id: [u8; 16], hops: u8) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Proof, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::Lrproof, + }; + let mut raw = header.pack(); + // Add fake proof data (signature + peer pubkey) + raw.extend_from_slice(&[0xAA; 96]); + Bytes::from(raw) + } + + #[test] + fn test_lrproof_routing_through_relay() { + // LRPROOF travels back up the link-table chain toward the initiator. + // A mismatch between the packet's and the entry's remaining-hops value + // silently drops the proof at the relay, so this guards that path. + // + // Scenario: Initiator → Relay → Destination (remaining_hops=1 at relay) + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("to_initiator"); + let (entry2, _rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + // Create a link_table entry as if the relay forwarded a LINKREQUEST + // from interface 1 (initiator side) to interface 2 (destination side) + let link_id = [0x77; 16]; + let link_entry = crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: Some([0xBB; 16]), + interface_id: 2, // next-hop interface (toward destination) + remaining_hops: 1, // 1 hop from relay to destination + destination_hash: [0xCC; 16], + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, // came from initiator side + taken_hops: 0, + }; + relay.link_table.insert(link_id, link_entry); + + // Destination sends LRPROOF with hops=0 (new proof, not incremented). + // Proof arrives at relay on interface 2 (the destination side). + let proof = make_lrproof_packet(link_id, 0); + relay.on_inbound(InboundPacket { + raw: proof, + interface_id: 2, // arrived from destination side + rssi: None, + snr: None, + q: None, + }); + + // Relay should route the proof back to interface 1 (initiator side) + let routed = rx1 + .try_recv() + .expect("LRPROOF should be routed to initiator interface"); + assert!(!routed.is_empty()); + // The forwarded proof should have hops incremented to 1 + assert_eq!( + routed[1], 1, + "proof hops should be incremented when forwarded" + ); + + // Link should now be validated + let entry = relay.link_table.get(&link_id).unwrap(); + assert!( + entry.validated, + "link should be marked validated after proof routing" + ); + } + + #[test] + fn test_lrproof_routing_direct_attached_destination() { + // Scenario: Initiator -> relay -> directly attached destination. + // The relay's path to the destination has remaining_hops=0, and the + // destination emits a fresh LRPROOF with hops=0. + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("to_initiator"); + let (entry2, _rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + let link_id = [0x79; 16]; + relay.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 0, + destination_hash: [0xCD; 16], + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + + let proof = make_lrproof_packet(link_id, 0); + relay.on_inbound(InboundPacket { + raw: proof, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + let routed = rx1 + .try_recv() + .expect("zero-hop LRPROOF should route back to initiator"); + assert_eq!( + routed[1], 1, + "forwarded direct-attached proof should be one hop from initiator" + ); + assert!(relay.link_table.get(&link_id).unwrap().validated); + } + + #[test] + fn test_link_data_routes_via_link_table_both_directions() { + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("to_initiator"); + let (entry2, mut rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + let link_id = [0x7A; 16]; + relay.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 0, + destination_hash: [0xCE; 16], + established: true, + validated: true, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + + relay.on_inbound(InboundPacket { + raw: make_link_data_packet(link_id, 0), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let to_destination = rx2 + .try_recv() + .expect("initiator link data should route to destination side"); + assert_eq!(to_destination[1], 1); + + relay.on_inbound(InboundPacket { + raw: make_link_data_packet(link_id, 0), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let to_initiator = rx1 + .try_recv() + .expect("destination link data should route to initiator side"); + assert_eq!(to_initiator[1], 1); + } + + #[test] + fn test_link_proof_routes_via_link_table() { + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("to_initiator"); + let (entry2, _rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + let link_id = [0x7B; 16]; + relay.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 0, + destination_hash: [0xCF; 16], + established: true, + validated: true, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + + relay.on_inbound(InboundPacket { + raw: make_link_proof_packet(link_id, 0), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + let routed = rx1 + .try_recv() + .expect("link proof should route back to initiator side"); + assert_eq!(routed[1], 1); + } + + #[test] + fn test_lrproof_routing_3hop_chain() { + // Test multi-relay chain: Initiator → RelayA → RelayB → Destination + // RelayA has remaining_hops=2, RelayB has remaining_hops=1. + + // RelayB — closer to destination. + let (mut relay_b, _tx_b) = TransportActor::new(); + relay_b.is_transport_enabled = true; + + let (entry_b1, mut rx_b1) = make_test_interface("relayB_to_relayA"); + let (entry_b2, _rx_b2) = make_test_interface("relayB_to_dest"); + relay_b.interfaces.insert(1, entry_b1); + relay_b.interfaces.insert(2, entry_b2); + + let link_id = [0x88; 16]; + relay_b.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: Some([0xDD; 16]), + interface_id: 2, // toward destination + remaining_hops: 1, + destination_hash: [0xEE; 16], + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, // from RelayA + taken_hops: 1, + }, + ); + + // RelayA — closer to initiator. + let (mut relay_a, _tx_a) = TransportActor::new(); + relay_a.is_transport_enabled = true; + + let (entry_a1, mut rx_a1) = make_test_interface("relayA_to_initiator"); + let (entry_a2, _rx_a2) = make_test_interface("relayA_to_relayB"); + relay_a.interfaces.insert(1, entry_a1); + relay_a.interfaces.insert(2, entry_a2); + + relay_a.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: Some([0xCC; 16]), + interface_id: 2, // toward RelayB + remaining_hops: 2, + destination_hash: [0xEE; 16], + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, // from Initiator + taken_hops: 0, + }, + ); + + // Proof travels back: Destination → RelayB → RelayA. + // Destination sends proof with hops=0. + let proof = make_lrproof_packet(link_id, 0); + relay_b.on_inbound(InboundPacket { + raw: proof, + interface_id: 2, // from destination + rssi: None, + snr: None, + q: None, + }); + + // RelayB should forward proof to RelayA (interface 1) with hops=1 + let forwarded_b = rx_b1 + .try_recv() + .expect("RelayB should route proof toward RelayA"); + assert_eq!(forwarded_b[1], 1, "RelayB should increment proof hops to 1"); + + // RelayA receives proof with hops=1. + relay_a.on_inbound(InboundPacket { + raw: forwarded_b, + interface_id: 2, // from RelayB + rssi: None, + snr: None, + q: None, + }); + + // RelayA should forward proof to Initiator (interface 1) with hops=2 + let forwarded_a = rx_a1 + .try_recv() + .expect("RelayA should route proof toward Initiator"); + assert_eq!(forwarded_a[1], 2, "RelayA should increment proof hops to 2"); + + // Both links should be validated + assert!(relay_b.link_table.get(&link_id).unwrap().validated); + assert!(relay_a.link_table.get(&link_id).unwrap().validated); + } + + #[test] + fn test_outbound_broadcast_plain() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + // Build a Plain/Data outbound + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Plain, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: [0x66; 16], + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xFF; 20]); + + actor.on_outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: [0x66; 16], + }); + + // Both interfaces should receive the broadcast + assert!(rx1.try_recv().is_ok()); + assert!(rx2.try_recv().is_ok()); + } + + #[test] + fn test_outbound_single_with_path() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let dest_hash = [0x77; 16]; + + // Insert path to interface 2 + let path_entry = + crate::path_table::PathEntry::new(Some([0xBB; 16]), 1, 2, InterfaceMode::Gateway); + actor.path_table.insert(dest_hash, path_entry); + + let raw = make_data_packet(dest_hash, 0); + actor.on_outbound(OutboundRequest { + raw, + destination_hash: dest_hash, + }); + + // Only interface 2 should receive (directed via path) + assert!(rx1.try_recv().is_err()); + assert!(rx2.try_recv().is_ok()); + } + + #[test] + fn test_rate_tracking() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let dest_hash = [0x88; 16]; + + // Record multiple announces from the same destination + for _ in 0..5 { + actor.rate_table.record(dest_hash); + } + + let rate = actor.rate_table.get_rate(&dest_hash); + assert!(rate > 0.0, "rate should be tracked"); + } + + #[test] + fn test_ifac_interface_send() { + let (mut actor, _tx) = TransportActor::new(); + let (mut entry, mut rx) = make_test_interface("ifac_iface"); + + // Configure IFAC on this interface + let ifac_key = rns_identity::ifac::derive_ifac_key(Some("test"), Some("pass")).unwrap(); + entry.ifac_key = Some(ifac_key); + entry.ifac_size = 4; + actor.interfaces.insert(1, entry); + + let data = vec![0x01, 0x02, 0x03, 0x04]; + actor.send_to_interface(1, &data); + + let sent = rx.try_recv().unwrap(); + // The sent data should be longer (IFAC tag prepended) + assert_eq!(sent.len(), 4 + data.len()); // ifac_size + original + + // The IFAC flag should be set on byte 0 (flags byte) + assert!(sent[0] & 0x80 != 0); + } + + #[test] + fn test_ifac_inbound_verify() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; // rebroadcast requires transport + let ifac_key = rns_identity::ifac::derive_ifac_key(Some("test"), Some("pass")).unwrap(); + let ifac_size = 4; + + let (mut entry1, _rx1) = make_test_interface("ifac_in"); + entry1.ifac_key = Some(ifac_key); + entry1.ifac_size = ifac_size; + actor.interfaces.insert(1, entry1); + + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(2, entry2); + + // Build a valid signed announce packet + let (announce, dest_hash) = make_valid_announce("test.ifac", 0); + + // Sign it with IFAC + let signed = crate::ifac::ifac_sign(&announce, &ifac_key, ifac_size); + + // Inject the signed packet + actor.on_inbound(InboundPacket { + raw: Bytes::from(signed), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Path should be learned + assert!(actor.path_table.has_path(&dest_hash)); + + // Flush deferred announces (rebroadcast is now deferred via announce table) + actor.flush_pending_announces(); + + // Rebroadcast should appear on interface 2 + assert!(rx2.try_recv().is_ok()); + } + + #[test] + fn test_ifac_inbound_reject_bad() { + let (mut actor, _tx) = TransportActor::new(); + let ifac_key = rns_identity::ifac::derive_ifac_key(Some("test"), Some("pass")).unwrap(); + let wrong_key = rns_identity::ifac::derive_ifac_key(Some("wrong"), Some("key")).unwrap(); + let ifac_size = 4; + + let (mut entry1, _rx1) = make_test_interface("ifac_in"); + entry1.ifac_key = Some(ifac_key); + entry1.ifac_size = ifac_size; + actor.interfaces.insert(1, entry1); + + // Build valid announce and sign with WRONG IFAC key + let (announce, dest_hash) = make_valid_announce("test.ifac_reject", 0); + let signed = crate::ifac::ifac_sign(&announce, &wrong_key, ifac_size); + + actor.on_inbound(InboundPacket { + raw: Bytes::from(signed), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Path should NOT be learned (IFAC verification fails) + assert!(!actor.path_table.has_path(&dest_hash)); + } + + #[test] + fn test_announce_retransmit() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let (raw, dest_hash) = make_valid_announce("test.retransmit", 0); + + // Insert an announce entry that is due for retransmit + let announce_entry = crate::announce::AnnounceEntry { + timestamp: 0.0, + retransmit_timeout: 0.0, // already due + retries: 0, + received_from: dest_hash, + hops: 0, + packet_raw: raw.to_vec(), + local_rebroadcasts: 0, + block_rebroadcast: false, + attached_interface: None, + source_interface: None, + }; + actor.announce_table.insert(dest_hash, announce_entry); + + // Trigger tick + actor.last_announces_check = 0.0; + actor.on_tick(); + + // Interface 1 should have received the retransmit + assert!(rx1.try_recv().is_ok()); + } + + #[test] + fn test_local_data_delivery() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let dest_hash = [0xCC; 16]; + actor.local_destinations.insert(dest_hash); + + let (dest_tx, mut dest_rx) = mpsc::channel(16); + actor.destination_channels.insert(dest_hash, dest_tx); + + // Inject data packet for local destination + let raw = make_data_packet(dest_hash, 0); + actor.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Should be delivered to destination channel as DestinationEvent + let delivered = dest_rx.try_recv().unwrap(); + match delivered { + crate::link_messages::DestinationEvent::InboundPacket { raw: data, .. } => { + assert_eq!(data, raw); + } + _ => panic!("expected InboundPacket event"), + } + } + + #[test] + fn test_valid_announce_accepted() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let (raw, dest_hash) = make_valid_announce("test.valid", 0); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!(actor.path_table.has_path(&dest_hash)); + } + + #[test] + fn test_header_only_announce_rejected() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let (raw, dest_hash) = make_valid_announce("test.header_only", 0); + let header_only = Bytes::copy_from_slice(&raw[..rns_wire::constants::HEADER_MINSIZE]); + + actor.on_inbound(InboundPacket { + raw: header_only, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!(!actor.path_table.has_path(&dest_hash)); + assert!(!actor.recent_announces.contains_key(&dest_hash)); + } + + #[test] + fn test_blackholed_identity_announce_rejected_but_destination_hash_entry_is_not() { + let identity = rns_identity::identity::Identity::new(); + let (raw, dest_hash) = make_announce_for(&identity, "test.blackhole.identity", 0); + assert_ne!( + dest_hash, identity.hash, + "test requires distinct destination and identity hashes" + ); + + let (mut destination_blackholed_actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + destination_blackholed_actor.interfaces.insert(1, entry1); + destination_blackholed_actor + .blackhole_table + .add_with_reason(dest_hash, None, crate::blackhole::BlackholeReason::Manual); + destination_blackholed_actor.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!(destination_blackholed_actor.path_table.has_path(&dest_hash)); + assert!( + destination_blackholed_actor + .recent_announces + .contains_key(&dest_hash) + ); + + let (mut identity_blackholed_actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + identity_blackholed_actor.interfaces.insert(1, entry1); + identity_blackholed_actor.blackhole_table.add_with_reason( + identity.hash, + None, + crate::blackhole::BlackholeReason::Manual, + ); + identity_blackholed_actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!(!identity_blackholed_actor.path_table.has_path(&dest_hash)); + assert!( + !identity_blackholed_actor + .recent_announces + .contains_key(&dest_hash) + ); + } + + #[test] + fn test_known_destination_key_mismatch_rejects_inbound_announce() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let identity = rns_identity::identity::Identity::new(); + let other_identity = rns_identity::identity::Identity::new(); + let other_public_key = other_identity.get_public_key(); + let (raw, dest_hash) = make_announce_for(&identity, "test.known_key_mismatch", 0); + actor.recent_announces.insert( + dest_hash, + RecentAnnounce { + dest_hash, + hops: 4, + app_data: Some(b"existing".to_vec()), + timestamp: 1.0, + public_key: Some(other_public_key), + ratchet: None, + raw_packet: vec![0xAA, 0xBB], + retained: false, + name_hash: [0xCC; 10], + }, + ); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!(!actor.path_table.has_path(&dest_hash)); + let cached = actor + .recent_announces + .get(&dest_hash) + .expect("existing entry must not be removed"); + assert_eq!(cached.public_key, Some(other_public_key)); + assert_eq!(cached.raw_packet, vec![0xAA, 0xBB]); + assert_eq!(cached.name_hash, [0xCC; 10]); + } + + #[test] + fn test_replayed_announce_random_blob_does_not_replace_path() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, _rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let identity = rns_identity::identity::Identity::new(); + let blob = random_blob(0xA1, 100); + let (raw_first, dest_hash) = + make_announce_for_with_random_blob(&identity, "test.replay.same", 3, blob); + let (raw_replay, _) = + make_announce_for_with_random_blob(&identity, "test.replay.same", 1, blob); + + actor.on_inbound(InboundPacket { + raw: raw_first, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + actor.on_inbound(InboundPacket { + raw: raw_replay, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(path.hops, 3); + assert_eq!(path.interface_id, 1); + assert_eq!(path.random_blobs.len(), 1); + assert!(path.has_random_blob(&blob)); + assert_eq!( + actor + .announce_table + .get(&dest_hash) + .unwrap() + .source_interface, + Some(1), + "replayed announces must not refresh rebroadcast state" + ); + } + + #[test] + fn test_newer_equal_or_higher_hop_announce_replaces_path() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, _rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let identity = rns_identity::identity::Identity::new(); + let old_blob = random_blob(0xA2, 100); + let equal_new_blob = random_blob(0xB2, 101); + let higher_new_blob = random_blob(0xC2, 102); + let (raw_first, dest_hash) = + make_announce_for_with_random_blob(&identity, "test.replay.newer", 3, old_blob); + let (raw_equal_new, _) = + make_announce_for_with_random_blob(&identity, "test.replay.newer", 3, equal_new_blob); + let (raw_higher_new, _) = + make_announce_for_with_random_blob(&identity, "test.replay.newer", 5, higher_new_blob); + + actor.on_inbound(InboundPacket { + raw: raw_first, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + actor.on_inbound(InboundPacket { + raw: raw_equal_new, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(path.hops, 3); + assert_eq!(path.interface_id, 2); + assert!(path.has_random_blob(&old_blob)); + assert!(path.has_random_blob(&equal_new_blob)); + + actor.on_inbound(InboundPacket { + raw: raw_higher_new, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(path.hops, 5); + assert_eq!(path.interface_id, 1); + assert!(path.has_random_blob(&higher_new_blob)); + } + + #[test] + fn test_older_higher_hop_announce_waits_for_expiry_or_unresponsive_path() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, _rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let identity = rns_identity::identity::Identity::new(); + let current_blob = random_blob(0xA3, 200); + let older_blob = random_blob(0xB3, 199); + let (raw_current, dest_hash) = + make_announce_for_with_random_blob(&identity, "test.replay.older", 1, current_blob); + let (raw_older, _) = + make_announce_for_with_random_blob(&identity, "test.replay.older", 5, older_blob); + + actor.on_inbound(InboundPacket { + raw: raw_current.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + actor.on_inbound(InboundPacket { + raw: raw_older.clone(), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(path.hops, 1); + assert_eq!(path.interface_id, 1); + assert!(!path.has_random_blob(&older_blob)); + + actor.path_table.get_mut(&dest_hash).unwrap().expires = 0.0; + actor.on_inbound(InboundPacket { + raw: raw_older, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(path.hops, 5); + assert_eq!(path.interface_id, 2); + assert!(path.has_random_blob(&older_blob)); + } + + #[test] + fn test_unresponsive_path_accepts_same_timebase_higher_hop_replay() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, _rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let identity = rns_identity::identity::Identity::new(); + let blob = random_blob(0xA4, 300); + let (raw_current, dest_hash) = + make_announce_for_with_random_blob(&identity, "test.replay.unresponsive", 1, blob); + let (raw_replay, _) = + make_announce_for_with_random_blob(&identity, "test.replay.unresponsive", 5, blob); + + actor.on_inbound(InboundPacket { + raw: raw_current, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + actor + .path_table + .set_state(dest_hash, crate::constants::PathState::Unresponsive); + actor.on_inbound(InboundPacket { + raw: raw_replay, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(path.hops, 5); + assert_eq!(path.interface_id, 2); + assert_eq!( + actor.path_table.get_state(&dest_hash), + crate::constants::PathState::Unknown, + "replacement path must clear stale unresponsive state" + ); + } + + #[test] + fn test_tampered_signature_rejected() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let (raw, dest_hash) = make_valid_announce("test.tamper", 0); + let mut raw = raw.to_vec(); + + // Tamper with a byte in the payload (signature area) + let last = raw.len() - 1; + raw[last] ^= 0xFF; + + actor.on_inbound(InboundPacket { + raw: Bytes::from(raw), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Path should NOT be learned due to invalid signature + assert!(!actor.path_table.has_path(&dest_hash)); + } + + #[test] + fn test_wrong_dest_hash_rejected() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + // Create a valid announce but then change the dest_hash in the header + let identity = rns_identity::identity::Identity::new(); + let app_name = "test.wrong_hash"; + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let announce_data = + rns_identity::announce::AnnounceData::create(&identity, app_name, None, None).unwrap(); + let payload = announce_data.pack(); + + // Use a WRONG dest_hash in the header + let wrong_hash = [0xFF; 16]; + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: wrong_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + + actor.on_inbound(InboundPacket { + raw: Bytes::from(raw), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Neither the wrong hash nor the real hash should be learned + assert!(!actor.path_table.has_path(&wrong_hash)); + assert!(!actor.path_table.has_path(&dest_hash)); + } + + fn make_header2_data_packet( + transport_id: [u8; 16], + dest_hash: [u8; 16], + hops: u8, + payload: &[u8], + ) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header2, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Transport, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: Some(transport_id), + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(payload); + Bytes::from(raw) + } + + fn make_header2_announce( + transport_id: [u8; 16], + app_name: &str, + hops: u8, + ) -> (Bytes, [u8; 16], rns_identity::identity::Identity) { + let identity = rns_identity::identity::Identity::new(); + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let announce_data = + rns_identity::announce::AnnounceData::create(&identity, app_name, None, None).unwrap(); + let payload = announce_data.pack(); + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header2, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Transport, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops, + transport_id: Some(transport_id), + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + (Bytes::from(raw), dest_hash, identity) + } + + #[test] + fn test_header2_data_local_delivery() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let transport_id = [0xAA; 16]; + let dest_hash = [0xBB; 16]; + actor.local_destinations.insert(dest_hash); + + let (dest_tx, mut dest_rx) = mpsc::channel(16); + actor.destination_channels.insert(dest_hash, dest_tx); + + // Build Header2 Data packet (as a transport relay would send) + let payload = b"encrypted_lxmf_data_here"; + let raw = make_header2_data_packet(transport_id, dest_hash, 2, payload); + + actor.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Should be delivered to destination channel + let delivered = dest_rx.try_recv().unwrap(); + match delivered { + crate::link_messages::DestinationEvent::InboundPacket { raw: data, .. } => { + // The raw bytes delivered include the full Header2 header + assert_eq!(data, raw); + // Verify that PacketHeader::unpack correctly extracts the payload + let (hdr, data_offset) = rns_wire::header::PacketHeader::unpack(&data).unwrap(); + assert_eq!(hdr.destination_hash, dest_hash); + assert_eq!(hdr.transport_id, Some(transport_id)); + assert_eq!(data_offset, 35); // Header2 offset + assert_eq!(&data[data_offset..], payload); + } + _ => panic!("expected InboundPacket event"), + } + } + + #[test] + fn test_header2_data_transport_forwarding() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry1, _rx1) = make_test_interface("iface_in"); + let (entry2, mut rx2) = make_test_interface("iface_out"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let transport_id = [0xAA; 16]; // hub identity + let dest_hash = [0xBB; 16]; // final destination (NOT local) + + // Set up path: dest_hash is reachable via interface 2 + let path_entry = crate::path_table::PathEntry::new( + Some([0xCC; 16]), // next_hop + 1, + 2, // interface 2 + InterfaceMode::Gateway, + ); + actor.path_table.insert(dest_hash, path_entry); + + // Inject Header2 Data + let payload = b"relay_this_data"; + let raw = make_header2_data_packet(transport_id, dest_hash, 1, payload); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Should be forwarded via interface 2 with hops incremented + let forwarded = rx2.try_recv().unwrap(); + assert_eq!(forwarded[1], 2); // hops: 1 → 2 + // Verify it's still a Header2 packet + let (hdr, offset) = rns_wire::header::PacketHeader::unpack(&forwarded).unwrap(); + assert_eq!(hdr.flags.header_type, rns_wire::flags::HeaderType::Header2); + assert_eq!(hdr.destination_hash, dest_hash); + assert_eq!(&forwarded[offset..], payload); + } + + #[test] + fn test_outbound_header1_to_header2_wrapping() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let dest_hash = [0xDD; 16]; + let next_hop = [0xEE; 16]; + + // next_hop present + hops > 1 triggers Header1 -> Header2 wrap. + // At 1 hop, only a shared-instance client wraps. + let path_entry = + crate::path_table::PathEntry::new(Some(next_hop), 2, 1, InterfaceMode::Gateway); + actor.path_table.insert(dest_hash, path_entry); + + // Build outbound Header1 Data + let payload = b"outbound_message_data"; + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(payload); + + actor.on_outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: dest_hash, + }); + + // Interface should receive Header2 with transport_id = next_hop + let sent = rx1.try_recv().unwrap(); + let (sent_hdr, sent_offset) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + assert_eq!( + sent_hdr.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!( + sent_hdr.flags.transport_type, + rns_wire::flags::TransportType::Transport + ); + assert_eq!(sent_hdr.transport_id, Some(next_hop)); + assert_eq!(sent_hdr.destination_hash, dest_hash); + assert_eq!(sent_offset, 35); + // Payload is preserved after wrapping + assert_eq!(&sent[sent_offset..], payload); + } + + #[test] + fn test_outbound_wrapping_preserves_context_and_flags() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let dest_hash = [0x11; 16]; + let next_hop = [0x22; 16]; + + let path_entry = + crate::path_table::PathEntry::new(Some(next_hop), 2, 1, InterfaceMode::Gateway); + actor.path_table.insert(dest_hash, path_entry); + + // Build Header1 with specific context and destination type + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xAB; 50]); // substantial payload + + actor.on_outbound(OutboundRequest { + raw: Bytes::from(raw.clone()), + destination_hash: dest_hash, + }); + + let sent = rx1.try_recv().unwrap(); + let (sent_hdr, offset) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + + // Packet type and destination type preserved + assert_eq!( + sent_hdr.flags.packet_type, + rns_wire::flags::PacketType::Data + ); + assert_eq!( + sent_hdr.flags.destination_type, + rns_wire::flags::DestinationType::Single + ); + assert_eq!(sent_hdr.context, rns_wire::context::PacketContext::None); + assert_eq!(sent_hdr.hops, 0); + // Payload = everything after the original 19-byte Header1 header + assert_eq!(&sent[offset..], &[0xAB; 50]); + } + + #[test] + fn test_header2_announce_learns_next_hop() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let transport_id = [0xAA; 16]; // transport relay + let (raw, dest_hash, _identity) = make_header2_announce(transport_id, "test.h2announce", 2); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Path should be learned with next_hop = transport_id + assert!(actor.path_table.has_path(&dest_hash)); + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(path.next_hop, Some(transport_id)); + assert_eq!(path.hops, 2); + assert_eq!(path.interface_id, 1); + } + + #[test] + fn test_header1_announce_learns_path_no_next_hop() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let (raw, dest_hash) = make_valid_announce("test.direct", 0); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!(actor.path_table.has_path(&dest_hash)); + let path = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!( + path.next_hop, None, + "Header1 announce should have no next_hop" + ); + assert_eq!(path.hops, 0); + } + + #[test] + fn test_announce_then_outbound_wrapping_chain() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + // Step 1: Receive Header2 announce (from dest via transport relay) + // Use hops=2 so the path records hops=2 (triggers Header2 wrapping) + let transport_id = [0xCC; 16]; + let (announce_raw, dest_hash, _identity) = + make_header2_announce(transport_id, "test.chain", 2); + + actor.on_inbound(InboundPacket { + raw: announce_raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Drain the announce rebroadcast + let _ = rx1.try_recv(); + + // Verify path learned with next_hop + assert!(actor.path_table.has_path(&dest_hash)); + assert_eq!( + actor.path_table.get(&dest_hash).unwrap().next_hop, + Some(transport_id) + ); + + // Send outbound Data to that destination. + let payload = b"hello_mesh_world"; + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(payload); + + actor.on_outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: dest_hash, + }); + + // Should be wrapped as Header2 with transport_id = transport relay + let sent = rx1.try_recv().unwrap(); + let (sent_hdr, offset) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + assert_eq!( + sent_hdr.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(sent_hdr.transport_id, Some(transport_id)); + assert_eq!(sent_hdr.destination_hash, dest_hash); + assert_eq!(&sent[offset..], payload); + } + + #[test] + fn test_header1_data_unknown_dest_no_transport_dropped() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = false; + + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let dest_hash = [0xFF; 16]; // unknown, not local, no path + let raw = make_data_packet(dest_hash, 0); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Nothing forwarded (not a transport node) + assert!(rx2.try_recv().is_err()); + } + + #[test] + fn test_header1_data_transport_enabled_forwards() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let dest_hash = [0x44; 16]; + let path_entry = crate::path_table::PathEntry::new( + None, // direct path, no next_hop + 0, + 2, + InterfaceMode::Gateway, + ); + actor.path_table.insert(dest_hash, path_entry); + + let raw = make_data_packet(dest_hash, 0); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Forwarded with hops incremented + let forwarded = rx2.try_recv().unwrap(); + assert_eq!(forwarded[1], 1); // hops 0 → 1 + } + + #[test] + fn test_outbound_no_next_hop_sends_header1() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, mut rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let dest_hash = [0x55; 16]; + let path_entry = crate::path_table::PathEntry::new( + None, // no next_hop → no wrapping + 0, + 1, + InterfaceMode::Gateway, + ); + actor.path_table.insert(dest_hash, path_entry); + + let raw = make_data_packet(dest_hash, 0); + actor.on_outbound(OutboundRequest { + raw, + destination_hash: dest_hash, + }); + + let sent = rx1.try_recv().unwrap(); + let (sent_hdr, _) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + assert_eq!( + sent_hdr.flags.header_type, + rns_wire::flags::HeaderType::Header1, + "no next_hop should send as Header1 without wrapping" + ); + assert_eq!(sent_hdr.transport_id, None); + } + + #[test] + fn test_peer_hub_client_full_relay_chain() { + let (mut peer, _peer_tx) = TransportActor::new(); + let (mut hub, _hub_tx) = TransportActor::new(); + let (mut client, _client_tx) = TransportActor::new(); + + hub.is_transport_enabled = true; // Hub is transport node + + // Wire interfaces (we'll manually relay between them) + let (peer_iface, mut peer_rx) = make_test_interface("peer_tcp"); + let (hub_iface1, mut hub_rx1) = make_test_interface("hub_tcp_to_peer"); + let (hub_iface2, mut hub_rx2) = make_test_interface("hub_tcp_to_client"); + let (client_iface, _client_rx) = make_test_interface("client_tcp"); + + peer.interfaces.insert(1, peer_iface); + hub.interfaces.insert(1, hub_iface1); + hub.interfaces.insert(2, hub_iface2); + client.interfaces.insert(1, client_iface); + + // Client announces itself. + let client_identity = rns_identity::identity::Identity::new(); + let client_dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + "lxmf.delivery", + Some(&client_identity.hash), + ); + let announce_data = rns_identity::announce::AnnounceData::create( + &client_identity, + "lxmf.delivery", + None, + None, + ) + .unwrap(); + let announce_payload = announce_data.pack(); + + // Register the client's local destination. + let (client_dest_tx, mut client_dest_rx) = mpsc::channel(16); + client.local_destinations.insert(client_dest_hash); + client + .destination_channels + .insert(client_dest_hash, client_dest_tx); + + // Client sends announce as Header1 outbound. + let announce_flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }; + let announce_header = rns_wire::header::PacketHeader { + flags: announce_flags, + hops: 0, + transport_id: None, + destination_hash: client_dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut announce_raw = announce_header.pack(); + announce_raw.extend_from_slice(&announce_payload); + + // Inject the announce into the hub. + hub.on_inbound(InboundPacket { + raw: Bytes::from(announce_raw.clone()), + interface_id: 2, // arrived from client-side interface + rssi: None, + snr: None, + q: None, + }); + + // Hub should have learned path to client_dest_hash via interface 2. + assert!(hub.path_table.has_path(&client_dest_hash)); + let hub_path = hub.path_table.get(&client_dest_hash).unwrap(); + assert_eq!(hub_path.interface_id, 2); + assert_eq!(hub_path.next_hop, None, "direct announce → no next_hop"); + + // Flush deferred announces (rebroadcast is now deferred via announce table) + hub.flush_pending_announces(); + + // Hub rebroadcasts announce on other interfaces. + let rebroadcast = hub_rx1.try_recv().unwrap(); + assert_eq!(rebroadcast[1], 1); // hops: 0 → 1 + + // Peer receives the rebroadcast. + peer.on_inbound(InboundPacket { + raw: rebroadcast, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Peer should know the path to client_dest_hash. + assert!(peer.path_table.has_path(&client_dest_hash)); + // The rebroadcast came as Header1 from the hub — no transport_id in the header + // so the peer's path has no next_hop. + + // Peer sends LXMF Data to the client. Production would encrypt and + // wrap into a Data packet; the test uses an opaque ciphertext. + let lxmf_ciphertext = b"fake_encrypted_lxmf_message_payload_with_some_data"; + + let data_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, + }; + let data_header = rns_wire::header::PacketHeader { + flags: data_flags, + hops: 0, + transport_id: None, + destination_hash: client_dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut data_raw = data_header.pack(); + data_raw.extend_from_slice(lxmf_ciphertext); + + // Peer sends outbound. + peer.on_outbound(OutboundRequest { + raw: Bytes::from(data_raw.clone()), + destination_hash: client_dest_hash, + }); + + // Peer's interface sends Header1 because the path has no next_hop from + // announce relay. + let peer_sent = peer_rx.try_recv().unwrap(); + + // Hub receives the Data from the peer. + hub.on_inbound(InboundPacket { + raw: peer_sent.clone(), + interface_id: 1, // arrived from peer side + rssi: None, + snr: None, + q: None, + }); + + // Hub is a transport node with a path to client_dest_hash via + // interface 2, so process_data() forwards it. + let hub_forwarded = hub_rx2.try_recv().unwrap(); + + // Verify hub forwarded as Header1 with hops incremented. + let (fwd_hdr, fwd_offset) = rns_wire::header::PacketHeader::unpack(&hub_forwarded).unwrap(); + assert_eq!(fwd_hdr.flags.packet_type, rns_wire::flags::PacketType::Data); + assert_eq!(fwd_hdr.destination_hash, client_dest_hash); + assert_eq!(fwd_hdr.hops, 1); // incremented from 0 + assert_eq!(&hub_forwarded[fwd_offset..], lxmf_ciphertext); + + // Client receives the forwarded Data. + client.on_inbound(InboundPacket { + raw: hub_forwarded, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // Client's local destination should have received the packet. + let delivered = client_dest_rx.try_recv().unwrap(); + match delivered { + crate::link_messages::DestinationEvent::InboundPacket { raw, .. } => { + let (d_hdr, d_offset) = rns_wire::header::PacketHeader::unpack(&raw).unwrap(); + assert_eq!(d_hdr.destination_hash, client_dest_hash); + assert_eq!( + &raw[d_offset..], + lxmf_ciphertext, + "LXMF ciphertext should arrive intact" + ); + } + _ => panic!("expected InboundPacket event"), + } + } + + #[test] + fn test_bidirectional_via_hub() { + let (mut hub, _hub_tx) = TransportActor::new(); + hub.is_transport_enabled = true; + + let (hub_iface1, mut hub_rx1) = make_test_interface("hub_to_tdeck"); + let (hub_iface2, mut hub_rx2) = make_test_interface("hub_to_rust"); + hub.interfaces.insert(1, hub_iface1); + hub.interfaces.insert(2, hub_iface2); + + // Hub knows paths to both nodes + let tdeck_dest = [0x11; 16]; + let rust_dest = [0x22; 16]; + + // Path to T-Deck: via interface 1, direct + hub.path_table.insert( + tdeck_dest, + crate::path_table::PathEntry::new(None, 0, 1, InterfaceMode::Gateway), + ); + // Path to Rust: via interface 2, direct + hub.path_table.insert( + rust_dest, + crate::path_table::PathEntry::new(None, 0, 2, InterfaceMode::Gateway), + ); + + // T-Deck → Hub → Rust + let msg_a = make_data_packet(rust_dest, 0); + hub.on_inbound(InboundPacket { + raw: msg_a, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let fwd_a = hub_rx2 + .try_recv() + .expect("should forward to Rust via iface 2"); + let (hdr_a, _) = rns_wire::header::PacketHeader::unpack(&fwd_a).unwrap(); + assert_eq!(hdr_a.destination_hash, rust_dest); + + // Rust → Hub → T-Deck + let msg_b = make_data_packet(tdeck_dest, 0); + hub.on_inbound(InboundPacket { + raw: msg_b, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let fwd_b = hub_rx1 + .try_recv() + .expect("should forward to T-Deck via iface 1"); + let (hdr_b, _) = rns_wire::header::PacketHeader::unpack(&fwd_b).unwrap(); + assert_eq!(hdr_b.destination_hash, tdeck_dest); + } + + #[test] + fn test_packet_hash_dedup_header1_then_header2() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry1, _rx1) = make_test_interface("iface1"); + let (entry2, mut rx2) = make_test_interface("iface2"); + actor.interfaces.insert(1, entry1); + actor.interfaces.insert(2, entry2); + + let dest_hash = [0x99; 16]; + actor.path_table.insert( + dest_hash, + crate::path_table::PathEntry::new(Some([0xAA; 16]), 1, 2, InterfaceMode::Gateway), + ); + + // Inject Header1 Data + let raw_h1 = make_data_packet(dest_hash, 0); + actor.on_inbound(InboundPacket { + raw: raw_h1.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + // First packet should be forwarded + assert!(rx2.try_recv().is_ok()); + + // Now inject the exact same packet again — should be deduplicated + actor.on_inbound(InboundPacket { + raw: raw_h1, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!(rx2.try_recv().is_err(), "duplicate should be dropped"); + } + + /// Dedup hash is content-stable: Header1 and its Header2-wrapped twin + /// collide so a wrapped relay cannot bypass dedup on the next hop. + #[test] + fn test_header1_header2_same_content_same_hash() { + // This validates the hash dedup design: same dest+context+payload + // produces the same hash regardless of Header1 vs Header2 wrapping + let dest = [0xBB; 16]; + let transport_id = [0xCC; 16]; + let payload = b"test_payload_data"; + + // Header1 + let raw_h1 = { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(payload); + raw + }; + + // Header2 with same dest+context+payload + let raw_h2 = { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header2, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Transport, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 3, + transport_id: Some(transport_id), + destination_hash: dest, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(payload); + raw + }; + + let hash_h1 = rns_wire::hash::packet_hash(&raw_h1, rns_wire::flags::HeaderType::Header1); + let hash_h2 = rns_wire::hash::packet_hash(&raw_h2, rns_wire::flags::HeaderType::Header2); + assert_eq!( + hash_h1, hash_h2, + "Header1 and Header2 with same content must produce same packet hash" + ); + } + + #[test] + fn test_shared_instance_wraps_at_1_hop() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_shared_instance = true; + + let (entry1, mut rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let dest_hash = [0xAA; 16]; + let next_hop = [0xBB; 16]; + + // Path with 1 hop and next_hop: should wrap on shared instance + let path_entry = + crate::path_table::PathEntry::new(Some(next_hop), 1, 1, InterfaceMode::Gateway); + actor.path_table.insert(dest_hash, path_entry); + + let raw = make_data_packet(dest_hash, 0); + actor.on_outbound(OutboundRequest { + raw, + destination_hash: dest_hash, + }); + + let sent = rx1.try_recv().unwrap(); + let (sent_hdr, _) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + assert_eq!( + sent_hdr.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(sent_hdr.transport_id, Some(next_hop)); + } + + #[test] + fn test_non_shared_instance_wraps_at_1_hop_with_next_hop() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_shared_instance = false; + + let (entry1, mut rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let dest_hash = [0xAA; 16]; + let next_hop = [0xBB; 16]; + + // Path with 1 hop and next_hop: MUST wrap even without shared instance, + // because transport nodes only forward Header2 packets. + let path_entry = + crate::path_table::PathEntry::new(Some(next_hop), 1, 1, InterfaceMode::Gateway); + actor.path_table.insert(dest_hash, path_entry); + + let raw = make_data_packet(dest_hash, 0); + actor.on_outbound(OutboundRequest { + raw, + destination_hash: dest_hash, + }); + + let sent = rx1.try_recv().unwrap(); + let (sent_hdr, _) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + assert_eq!( + sent_hdr.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(sent_hdr.transport_id, Some(next_hop)); + } + + #[test] + fn test_path_expire_force_cull() { + let mut table = PathTable::new(); + let hash = [0xCC; 16]; + table.insert( + hash, + crate::path_table::PathEntry::new(None, 0, 1, InterfaceMode::Gateway), + ); + assert!(table.has_path(&hash)); + + // expire() should set expires=0 and immediately cull + table.expire(&hash); + assert!(!table.has_path(&hash)); + } + + #[test] + fn test_announce_queue_life_culling() { + let (mut actor, _tx) = TransportActor::new(); + let (mut entry, _rx) = make_test_interface("iface1"); + // Add stale announce queue entries + entry.announce_queue.push(crate::messages::QueuedAnnounce { + destination_hash: [0x01; 16], + time: 0.0, // Very old + hops: 1, + raw: Bytes::from_static(&[0u8; 32]), + }); + entry.announce_queue.push(crate::messages::QueuedAnnounce { + destination_hash: [0x02; 16], + time: now_f64(), // Fresh + hops: 1, + raw: Bytes::from_static(&[0u8; 32]), + }); + actor.interfaces.insert(1, entry); + + // Cull at current time + actor.cull_announce_queues(now_f64()); + + // Only the fresh entry should remain + assert_eq!(actor.interfaces.get(&1).unwrap().announce_queue.len(), 1); + assert_eq!( + actor.interfaces.get(&1).unwrap().announce_queue[0].destination_hash, + [0x02; 16] + ); + } + + #[test] + fn test_register_link_initiator() { + let (mut actor, _tx) = TransportActor::new(); + let link_id = [0xAA; 16]; + + actor.handle_message(TransportMessage::RegisterLink { + link_id, + destination_hash: [0xBB; 16], + interface_id: 1, + next_hop: Some([0xCC; 16]), + remaining_hops: 3, + initiator: true, + }); + + let entry = actor.link_table.get(&link_id).unwrap(); + assert!(!entry.validated); + assert!(!entry.established); + } + + #[test] + fn test_register_link_responder() { + let (mut actor, _tx) = TransportActor::new(); + let link_id = [0xAA; 16]; + + actor.handle_message(TransportMessage::RegisterLink { + link_id, + destination_hash: [0xBB; 16], + interface_id: 1, + next_hop: None, + remaining_hops: 0, + initiator: false, + }); + + let entry = actor.link_table.get(&link_id).unwrap(); + assert!(entry.validated); + assert!(entry.established); + } + + #[test] + fn test_activate_link() { + let (mut actor, _tx) = TransportActor::new(); + let link_id = [0xAA; 16]; + + // Register as initiator (pending) + actor.handle_message(TransportMessage::RegisterLink { + link_id, + destination_hash: [0xBB; 16], + interface_id: 1, + next_hop: None, + remaining_hops: 0, + initiator: true, + }); + assert!(!actor.link_table.get(&link_id).unwrap().validated); + + // Activate + actor.handle_message(TransportMessage::ActivateLink { link_id }); + let entry = actor.link_table.get(&link_id).unwrap(); + assert!(entry.validated); + assert!(entry.established); + } + + #[test] + fn test_deferred_cache_clean() { + let (mut actor, _tx) = TransportActor::new(); + assert!(!actor.startup_complete); + + // Before any interface is registered, startup_time is 0 + assert_eq!(actor.startup_time, 0.0); + + // Register an interface to start the startup timer + let (entry, _rx) = make_test_interface("iface1"); + actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry }); + assert!(actor.startup_time > 0.0); + assert!(!actor.startup_complete); + } + + #[test] + fn test_held_announce_storage() { + let (mut actor, _tx) = TransportActor::new(); + let (mut entry, _rx) = make_test_interface("iface1"); + + let dest_hash = [0xDD; 16]; + entry.ingress.hold_announce(crate::ingress::HeldAnnounce { + raw: Bytes::from_static(&[0u8; 32]), + hops: 2, + destination_hash: dest_hash, + receiving_interface_id: 1, + }); + actor.interfaces.insert(1, entry); + + assert_eq!(actor.interfaces.get(&1).unwrap().ingress.held_count(), 1); + } + + /// Floods a fresh actor with a tight burst of *unique* announces on one + /// interface, then asserts: (a) the per-interface ingress controller + /// engaged burst mode, and (b) the controller is now holding at least + /// one of the held announces. This is the integration sibling of the + /// `IngressController` unit tests in `ingress.rs` — it pins the wiring + /// in `inbound.rs` that calls `received_announce()` and `hold_announce()`. + #[test] + fn test_inbound_announce_flood_engages_ingress_hold() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry_in, _rx_in) = make_test_interface("flooded_iface"); + let (entry_out, _rx_out) = make_test_interface("relay_iface"); + actor.interfaces.insert(1, entry_in); + actor.interfaces.insert(2, entry_out); + + // Burst many distinct announces. Each unique destination ensures the + // packet hashlist doesn't dedupe them — every one passes through the + // ingress gate on its own merits. + for _ in 0..50 { + let (raw, _dest) = make_valid_announce("test.flood", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + + let entry = actor.interfaces.get(&1).expect("inbound interface present"); + assert!( + entry.ingress.is_burst_active(), + "flood of 50 announces in a tight loop must engage burst mode" + ); + assert!( + entry.ingress.held_count() > 0, + "burst mode must result in at least one held announce (got {})", + entry.ingress.held_count() + ); + } + + /// Ingress-limit is bypassed for announces whose destination matches an + /// outstanding path request — the announce *is* the answer, so holding it + /// only delays resolution. This pins the bypass: with the interface in + /// burst-active state, an announce for a pending `path_requests` entry + /// must be processed (held_count unchanged), while one for an unknown + /// destination must still be held. + #[test] + fn test_path_request_destination_bypasses_ingress_hold() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry_in, _rx_in) = make_test_interface("path_req_iface"); + actor.interfaces.insert(1, entry_in); + + // Drive the controller into burst-active state. + for _ in 0..50 { + let (raw, _dest) = make_valid_announce("test.flood", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + assert!( + actor.interfaces.get(&1).unwrap().ingress.is_burst_active(), + "precondition: burst must be active before testing bypass" + ); + let held_before = actor.interfaces.get(&1).unwrap().ingress.held_count(); + + // Build an announce for a fresh destination, register it as an active + // path request, then send it. The bypass must let it through. + let (raw_match, dest_match) = make_valid_announce("test.path_req.match", 1); + actor.path_requests.insert(dest_match, now_f64()); + actor.on_inbound(crate::messages::InboundPacket { + raw: raw_match, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let held_after_bypass = actor.interfaces.get(&1).unwrap().ingress.held_count(); + assert_eq!( + held_after_bypass, held_before, + "an announce whose destination is in path_requests must NOT be held" + ); + + // Discovery requests on behalf of another peer use the same bypass. + let (raw_discovery, dest_discovery) = make_valid_announce("test.path_req.discovery", 1); + actor.discovery_path_requests.insert( + dest_discovery, + DiscoveryPathRequest { + requesting_interface: 1, + timeout: now_f64() + PATH_REQUEST_TIMEOUT, + }, + ); + actor.on_inbound(crate::messages::InboundPacket { + raw: raw_discovery, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let held_after_discovery = actor.interfaces.get(&1).unwrap().ingress.held_count(); + assert_eq!( + held_after_discovery, held_after_bypass, + "an announce whose destination is in discovery_path_requests must NOT be held" + ); + + // Control: an announce for an unknown destination must still be held. + let (raw_other, _dest_other) = make_valid_announce("test.path_req.other", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw: raw_other, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let held_after_other = actor.interfaces.get(&1).unwrap().ingress.held_count(); + assert!( + held_after_other > held_after_discovery, + "control: a burst-time announce without a matching path request must still be held" + ); + } + + /// `broadcast_announce_on_interfaces` must enqueue rather than send + /// directly, and `process_announce_queues` must drain one entry per + /// gate-open while pushing `announce_allowed_at` forward by the + /// `tx_time / announce_cap` formula. This test exercises both halves. + #[test] + fn test_broadcast_announce_queues_then_spaces_via_cap() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, mut rx) = make_test_interface("spaced_iface"); + actor.interfaces.insert(1, entry); + + let (raw, _dest) = make_valid_announce("test.cap", 0); + let raw_len = raw.len(); + + // Two distinct announces back-to-back. The first call must just + // enqueue (nothing on the wire yet). + actor.broadcast_announce_on_interfaces(&raw, None); + let (raw2, _dest2) = make_valid_announce("test.cap.b", 0); + actor.broadcast_announce_on_interfaces(&raw2, None); + assert!( + rx.try_recv().is_err(), + "broadcast_announce_on_interfaces must NOT send directly — it queues" + ); + assert_eq!( + actor.interfaces.get(&1).unwrap().announce_queue.len(), + 2, + "both announces must sit in the per-interface queue" + ); + + // Drain once: only the lowest-hops entry should send and the gate + // should slide forward by tx_time/announce_cap. + let now = now_f64(); + actor.process_announce_queues(now); + assert!( + rx.try_recv().is_ok(), + "process_announce_queues must release one announce on the wire" + ); + + let entry = actor.interfaces.get(&1).expect("interface still present"); + let expected_delay = + (raw_len as f64 * 8.0) / entry.bitrate.max(1) as f64 / entry.announce_cap.max(0.001); + let actual_delay = entry.announce_allowed_at - now; + assert!( + (actual_delay - expected_delay).abs() < 1e-6, + "announce_allowed_at must be pushed forward by tx_time/cap (expected {expected_delay}, got {actual_delay})" + ); + assert_eq!( + entry.announce_queue.len(), + 1, + "the second announce must remain queued behind the bandwidth gate" + ); + + // A second drain at the same `now` is gated — no further sends. + actor.process_announce_queues(now); + assert!( + rx.try_recv().is_err(), + "second drain before announce_allowed_at must not release the next entry" + ); + } + + #[test] + fn test_blackhole_rpc_operations() { + let (mut actor, _tx) = TransportActor::new(); + + // Add a blackhole via RPC + let resp = actor.handle_query(crate::messages::TransportQuery::BlackholeIdentity { + hash: [0xAA; 16], + ttl: None, + reason: crate::blackhole::BlackholeReason::Manual, + reason_label: None, + }); + assert!(matches!(resp, crate::messages::TransportQueryResponse::Ok)); + assert!(actor.blackhole_table.is_blackholed(&[0xAA; 16])); + + // Remove via RPC — returns BoolResult(true) when something was removed. + let resp = actor.handle_query(crate::messages::TransportQuery::UnblackholeIdentity { + hash: [0xAA; 16], + }); + assert!(matches!( + resp, + crate::messages::TransportQueryResponse::BoolResult(true) + )); + assert!(!actor.blackhole_table.is_blackholed(&[0xAA; 16])); + + // Removing a non-existent hash returns BoolResult(false). + let resp = actor.handle_query(crate::messages::TransportQuery::UnblackholeIdentity { + hash: [0xAA; 16], + }); + assert!(matches!( + resp, + crate::messages::TransportQueryResponse::BoolResult(false) + )); + + // IsBlackholed query + actor.blackhole_table.add_with_reason( + [0xBB; 16], + None, + crate::blackhole::BlackholeReason::Malformed, + ); + let resp = + actor.handle_query(crate::messages::TransportQuery::IsBlackholed { hash: [0xBB; 16] }); + assert!(matches!( + resp, + crate::messages::TransportQueryResponse::BoolResult(true) + )); + let resp = + actor.handle_query(crate::messages::TransportQuery::IsBlackholed { hash: [0xCC; 16] }); + assert!(matches!( + resp, + crate::messages::TransportQueryResponse::BoolResult(false) + )); + + // ClearSystemBlackholes drops Malformed/RateLimit/ProtocolViolation but + // leaves Manual entries intact. + actor.blackhole_table.add_with_reason( + [0xDD; 16], + None, + crate::blackhole::BlackholeReason::Manual, + ); + actor.blackhole_table.add_with_reason( + [0xEE; 16], + None, + crate::blackhole::BlackholeReason::RateLimit, + ); + let resp = actor.handle_query(crate::messages::TransportQuery::ClearSystemBlackholes); + let cleared = match resp { + crate::messages::TransportQueryResponse::IntResult(n) => n, + other => panic!("expected IntResult, got {other:?}"), + }; + assert_eq!(cleared, 2); + assert!(actor.blackhole_table.is_blackholed(&[0xDD; 16])); + assert!(!actor.blackhole_table.is_blackholed(&[0xBB; 16])); + assert!(!actor.blackhole_table.is_blackholed(&[0xEE; 16])); + + let payload = + match actor.handle_query(crate::messages::TransportQuery::BuildBlackholeManifest { + publisher: [0x99; 16], + }) { + crate::messages::TransportQueryResponse::Data(payload) => payload, + other => panic!("expected Data manifest, got {other:?}"), + }; + let decoded = crate::discovery::decode_manifest(&payload).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].0, [0xDD; 16]); + assert_eq!(decoded[0].1.source.as_bytes(), &[0x99; 16]); + + let (mut subscriber, _tx) = TransportActor::new(); + let applied = match subscriber + .handle_query(crate::messages::TransportQuery::ApplyBlackholeManifest { payload }) + { + crate::messages::TransportQueryResponse::IntResult(n) => n, + other => panic!("expected IntResult, got {other:?}"), + }; + assert_eq!(applied, 1); + assert!(subscriber.blackhole_table.is_blackholed(&[0xDD; 16])); + } + + #[test] + fn test_announce_cache_persistence_roundtrip() { + use crate::persistence::*; + + let announces = vec![RecentAnnounce { + dest_hash: [0xAA; 16], + hops: 2, + app_data: Some(vec![1, 2, 3]), + timestamp: 1234567890.0, + public_key: Some([0x42; 64]), + ratchet: None, + raw_packet: vec![0x55; 48], + retained: false, + name_hash: [0x77; 10], + }]; + + let dir = std::env::temp_dir().join("reticulum_rs_test_announce_cache"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("announce_cache.msgpack"); + + save_announce_cache(&announces, &path).unwrap(); + let loaded = load_announce_cache(&path).unwrap(); + + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].destination_hash, [0xAA; 16].to_vec()); + assert_eq!(loaded[0].hops, 2); + assert_eq!(loaded[0].app_data, Some(vec![1, 2, 3])); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_void_tunnel_on_interface_disconnect() { + let (mut actor, _tx) = TransportActor::new(); + + // Create a tunnel on interface 1 + let tunnel_id = [0xFF; 32]; + let dest_hash = [0xAA; 16]; + + let mut tunnel_paths = std::collections::HashMap::new(); + tunnel_paths.insert( + dest_hash, + crate::tunnel::TunnelPath { + timestamp: now_f64(), + hops: 2, + expires: now_f64() + 600.0, + random_blobs: vec![], + }, + ); + + actor.tunnel_table.insert(crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: 1, + tunnel_paths, + expires: now_f64() + 600.0, + }); + + // Also add a path for this dest through the tunnel + let path_entry = crate::path_table::PathEntry::new(None, 2, 1, InterfaceMode::Gateway); + actor.path_table.insert(dest_hash, path_entry); + assert!(actor.path_table.has_path(&dest_hash)); + + // Void the interface + actor.void_tunnel_interface(1); + + // Path should be removed + assert!(!actor.path_table.has_path(&dest_hash)); + + // Tunnel interface should be voided (set to 0) + assert_eq!(actor.tunnel_table.get(&tunnel_id).unwrap().interface_id, 0); + } + + #[test] + fn test_cache_request_handler() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; // cache request broadcast requires transport + + // Register an outbound interface to receive the replayed announce + let (iface, mut rx) = make_test_interface("out1"); + actor.interfaces.insert(1, iface); + + // Create and inject a valid announce + let (announce_raw, dest_hash) = make_valid_announce("test.cache", 0); + + // Compute the packet hash (this is what the cache request will contain) + let packet_hash = + rns_wire::hash::packet_hash(&announce_raw, rns_wire::flags::HeaderType::Header1); + + // Process the announce through inbound — populates path_table + recent_announces + let inbound = crate::messages::InboundPacket { + raw: announce_raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }; + actor.on_inbound(inbound); + + // Verify announce was cached with raw bytes + assert_eq!(actor.recent_announces.len(), 1); + let cached = actor + .recent_announces + .get(&dest_hash) + .expect("announce should be cached under its dest_hash"); + assert!(!cached.raw_packet.is_empty()); + + // Verify path_table has the packet_hash + let path_entry = actor.path_table.get(&dest_hash); + assert!(path_entry.is_some()); + assert_eq!(path_entry.unwrap().packet_hash, Some(packet_hash)); + + // Build a CacheRequest: Data packet with context=CacheRequest, payload=32-byte packet hash + let cr_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, + }; + let cr_header = rns_wire::header::PacketHeader { + flags: cr_flags, + hops: 0, + transport_id: None, + destination_hash: [0x00; 16], // CacheRequest dest doesn't matter for lookup + context: rns_wire::context::PacketContext::CacheRequest, + }; + let mut cr_raw = cr_header.pack(); + cr_raw.extend_from_slice(&packet_hash); // 32-byte payload + + // Process the cache request + actor.handle_cache_request(&cr_raw, &cr_header, 1); + actor.flush_announce_queues(); + + // The output interface should have received the replayed announce + let replayed = rx.try_recv(); + assert!( + replayed.is_ok(), + "expected replayed announce on output interface" + ); + assert_eq!(replayed.unwrap(), announce_raw); + } + + #[test] + fn test_cache_request_miss() { + let (mut actor, _tx) = TransportActor::new(); + + let cr_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, + }; + let cr_header = rns_wire::header::PacketHeader { + flags: cr_flags, + hops: 0, + transport_id: None, + destination_hash: [0x00; 16], + context: rns_wire::context::PacketContext::CacheRequest, + }; + let mut cr_raw = cr_header.pack(); + cr_raw.extend_from_slice(&[0xFF; 32]); + + actor.handle_cache_request(&cr_raw, &cr_header, 1); + } + + #[test] + fn test_cache_request_invalid_payload_length() { + let (mut actor, _tx) = TransportActor::new(); + + let cr_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, + }; + let cr_header = rns_wire::header::PacketHeader { + flags: cr_flags, + hops: 0, + transport_id: None, + destination_hash: [0x00; 16], + context: rns_wire::context::PacketContext::CacheRequest, + }; + let mut cr_raw = cr_header.pack(); + cr_raw.extend_from_slice(&[0xFF; 16]); + + actor.handle_cache_request(&cr_raw, &cr_header, 1); + } + + #[test] + fn load_state_drops_expired_paths_and_stages_others() { + let dir = std::env::temp_dir().join("rns_load_drop_expired"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // Pre-populate with a fresh + an expired entry, both bound to the + // same logical interface name. + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs_f64(); + let mut table = crate::path_table::PathTable::new(); + table.insert( + [0xAA; 16], + crate::path_table::PathEntry::new(None, 1, 7, InterfaceMode::Gateway), + ); + // expired entry — manually construct so we can backdate `expires`. + table.insert( + [0xBB; 16], + crate::path_table::PathEntry { + timestamp: now - 86400.0, + next_hop: None, + hops: 1, + expires: now - 1.0, + random_blobs: Default::default(), + interface_id: 7, + packet_hash: None, + }, + ); + + let mut names = std::collections::HashMap::new(); + names.insert(7u64, "tcp_backbone".to_string()); + let path = dir.join("path_table.msgpack"); + crate::persistence::save_path_table(&table, &names, &path).unwrap(); + + let (mut actor, _tx) = TransportActor::new(); + actor.storage_dir = Some(dir.clone()); + actor.load_state(); + + // Expired entry dropped, fresh entry staged for rebind. + assert_eq!(actor.pending_path_entries.len(), 1); + assert_eq!( + actor.pending_path_entries[0].interface_name.as_deref(), + Some("tcp_backbone") + ); + // Live path table is still empty until RegisterInterface arrives. + assert!(!actor.path_table.has_path(&[0xAA; 16])); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn register_interface_rebinds_pending_paths_to_new_id() { + let dir = std::env::temp_dir().join("rns_rebind_paths"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // Save with interface_id=7 → name "tcp_backbone". + let mut table = crate::path_table::PathTable::new(); + table.insert( + [0xAA; 16], + crate::path_table::PathEntry::new(None, 1, 7, InterfaceMode::Gateway), + ); + let mut names = std::collections::HashMap::new(); + names.insert(7u64, "tcp_backbone".to_string()); + crate::persistence::save_path_table(&table, &names, &dir.join("path_table.msgpack")) + .unwrap(); + + // Fresh actor → load → register interface under a *different* id. + let (mut actor, _tx) = TransportActor::new(); + actor.storage_dir = Some(dir.clone()); + actor.load_state(); + assert_eq!(actor.pending_path_entries.len(), 1); + + let (entry, _rx) = make_test_interface("tcp_backbone"); + actor.handle_message(TransportMessage::RegisterInterface { id: 42, entry }); + + // Path is now in the live table, bound to the new id. + assert!(actor.path_table.has_path(&[0xAA; 16])); + let bound = actor.path_table.iter().next().unwrap().1; + assert_eq!(bound.interface_id, 42); + // Pending list drained. + assert!(actor.pending_path_entries.is_empty()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn legacy_v2_path_snapshot_is_dropped_on_load() { + // v2 had no `interface_name`; entries can't be rebound, so they + // must not leak into pending or the live table. + use serde::Serialize; + #[derive(Serialize)] + struct V2Entry { + destination_hash: Vec, + timestamp: f64, + next_hop: Option>, + hops: u8, + expires: f64, + random_blobs: Vec>, + interface_id: u64, + } + #[derive(Serialize)] + struct V2Table { + entries: Vec, + version: u32, + } + + let dir = std::env::temp_dir().join("rns_legacy_v2_drop"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let v2 = V2Table { + entries: vec![V2Entry { + destination_hash: vec![0xAA; 16], + timestamp: 1.0, + next_hop: None, + hops: 1, + expires: 9999999999.0, + random_blobs: vec![], + interface_id: 1, + }], + version: 2, + }; + let bytes = rmp_serde::to_vec(&v2).unwrap(); + std::fs::write(dir.join("path_table.msgpack"), &bytes).unwrap(); + + let (mut actor, _tx) = TransportActor::new(); + actor.storage_dir = Some(dir.clone()); + actor.load_state(); + assert!(actor.pending_path_entries.is_empty()); + assert_eq!(actor.path_table.iter().count(), 0); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn save_then_load_round_trips_interface_name() { + // Same actor lifecycle, on every platform: save with iface name + // populated, load, register interface under a fresh id, assert the + // entry rebinds. + let dir = std::env::temp_dir().join("rns_round_trip_iface_name"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // First lifecycle: register iface, insert path, shutdown saves. + { + let (mut actor, _tx) = TransportActor::new(); + actor.storage_dir = Some(dir.clone()); + let (entry, _rx) = make_test_interface("ble_peer"); + actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry }); + actor.path_table.insert( + [0xCC; 16], + crate::path_table::PathEntry::new(None, 2, 1, InterfaceMode::Gateway), + ); + actor.on_shutdown(); + } + + // Second lifecycle: load, register iface under a different id, expect rebind. + let (mut actor2, _tx2) = TransportActor::new(); + actor2.storage_dir = Some(dir.clone()); + actor2.load_state(); + assert_eq!(actor2.pending_path_entries.len(), 1); + + let (entry, _rx) = make_test_interface("ble_peer"); + actor2.handle_message(TransportMessage::RegisterInterface { id: 99, entry }); + assert!(actor2.path_table.has_path(&[0xCC; 16])); + assert_eq!(actor2.path_table.iter().next().unwrap().1.interface_id, 99); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn periodic_save_writes_path_table_when_dirty() { + let dir = std::env::temp_dir().join("rns_periodic_save_dirty"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let (mut actor, _tx) = TransportActor::new(); + actor.storage_dir = Some(dir.clone()); + let (entry, _rx) = make_test_interface("tcp_backbone"); + actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry }); + actor.path_table.insert( + [0xAA; 16], + crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Gateway), + ); + // Bypass the actor message path → manually flag dirty (production + // mutation sites do this themselves). + actor.state_dirty = true; + + // Backdate so the save trigger fires; push last_tables_cull forward + // so the cull paths (which also flag dirty as a defensive + // false-positive) don't run this tick and re-dirty the flag. + let n = now_f64(); + actor.last_state_save = n - STATE_SAVE_INTERVAL_SECS - 1.0; + actor.last_tables_cull = n; + actor.last_blackhole_check = n; + + let path = dir.join("path_table.msgpack"); + assert!(!path.exists(), "no save yet — file shouldn't exist"); + + actor.on_tick(); + + assert!(path.exists(), "dirty + interval elapsed must save"); + assert!(!actor.state_dirty, "save should clear dirty flag"); + let entries = crate::persistence::load_path_table(&path).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].destination_hash, [0xAA; 16].to_vec()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn periodic_save_skipped_when_clean() { + // Dirty gate: an idle device with no mutations since last save + // shouldn't spin disk every 10 s. + let dir = std::env::temp_dir().join("rns_periodic_save_clean"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let (mut actor, _tx) = TransportActor::new(); + actor.storage_dir = Some(dir.clone()); + let (entry, _rx) = make_test_interface("tcp_backbone"); + actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry }); + + // Backdate to make the interval check pass — but state_dirty stays + // false, so no save should happen. + actor.last_state_save = now_f64() - STATE_SAVE_INTERVAL_SECS - 1.0; + actor.state_dirty = false; + let path = dir.join("path_table.msgpack"); + + actor.on_tick(); + + assert!(!path.exists(), "clean state must not trigger periodic save"); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn announce_marks_state_dirty() { + // Sanity check that the hot path — receiving an announce that + // inserts a path_table entry — actually flips the dirty flag. + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + let (entry, _rx) = make_test_interface("test_iface"); + actor.interfaces.insert(1, entry); + assert!(!actor.state_dirty); + + let (raw, _dest) = make_valid_announce("test.dirty", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!(actor.state_dirty, "inbound announce should set state_dirty"); + } + + #[test] + fn foreground_to_background_triggers_save() { + // The run loop owns its interval; exercise the save path directly. + let dir = std::env::temp_dir().join("rns_fg_to_bg_save"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let (mut actor, _tx) = TransportActor::new(); + actor.storage_dir = Some(dir.clone()); + let (entry, _rx) = make_test_interface("tcp_backbone"); + actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry }); + actor.path_table.insert( + [0xBB; 16], + crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Gateway), + ); + + let path = dir.join("path_table.msgpack"); + assert!(!path.exists()); + + // Same call site the falling edge in `run` makes. + actor.save_state(); + + assert!(path.exists(), "falling-edge save must write path_table"); + assert!( + actor.last_state_save > 0.0, + "save should bump last_state_save" + ); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn outbound_announce_respects_access_point_mode() { + let (mut actor, _tx) = TransportActor::new(); + let (mut ap, mut ap_rx) = make_test_interface("ap"); + ap.mode = InterfaceMode::AccessPoint; + actor.interfaces.insert(1, ap); + let (gw, mut gw_rx) = make_test_interface("gateway"); + actor.interfaces.insert(2, gw); + + let (raw, dest) = make_valid_announce("test.outbound.ap", 0); + actor.handle_message(TransportMessage::Outbound(OutboundRequest { + raw, + destination_hash: dest, + })); + + assert!( + ap_rx.try_recv().is_err(), + "AP-mode interfaces must not receive general announce broadcasts" + ); + assert!( + gw_rx.try_recv().is_ok(), + "gateway-mode interface should carry the announce" + ); + } + + #[test] + fn announce_mode_rules_match_roaming_and_boundary_policy() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (mut via_roaming, _rx1) = make_test_interface("via_roaming"); + via_roaming.mode = InterfaceMode::Roaming; + actor.interfaces.insert(1, via_roaming); + let (mut gateway, _rx2) = make_test_interface("gateway"); + gateway.mode = InterfaceMode::Gateway; + actor.interfaces.insert(2, gateway); + let (mut roaming, _rx3) = make_test_interface("roaming"); + roaming.mode = InterfaceMode::Roaming; + actor.interfaces.insert(3, roaming); + let (mut boundary, _rx4) = make_test_interface("boundary"); + boundary.mode = InterfaceMode::Boundary; + actor.interfaces.insert(4, boundary); + + let (raw, dest) = make_valid_announce("test.mode.roaming", 1); + actor.path_table.insert( + dest, + crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Roaming), + ); + + actor.broadcast_announce_on_interfaces(&raw, None); + + assert_eq!( + actor.interfaces.get(&2).unwrap().announce_queue.len(), + 1, + "gateway should rebroadcast a path learned from roaming" + ); + assert_eq!( + actor.interfaces.get(&3).unwrap().announce_queue.len(), + 0, + "roaming should not rebroadcast a path learned from roaming" + ); + assert_eq!( + actor.interfaces.get(&4).unwrap().announce_queue.len(), + 0, + "boundary should not rebroadcast a path learned from roaming" + ); + + let (raw2, dest2) = make_valid_announce("test.mode.gateway", 1); + actor.path_table.insert( + dest2, + crate::path_table::PathEntry::new(None, 1, 2, InterfaceMode::Gateway), + ); + actor.broadcast_announce_on_interfaces(&raw2, None); + + assert_eq!( + actor.interfaces.get(&3).unwrap().announce_queue.len(), + 1, + "roaming may rebroadcast paths learned from gateway/full-style interfaces" + ); + assert_eq!( + actor.interfaces.get(&4).unwrap().announce_queue.len(), + 1, + "boundary may rebroadcast paths learned from gateway/full-style interfaces" + ); + } + + fn make_path_request_payload( + destination_hash: [u8; 16], + requestor_transport_id: Option<[u8; 16]>, + ) -> Vec { + make_path_request_payload_with_tag(destination_hash, requestor_transport_id, [0xA5; 16]) + } + + fn make_path_request_payload_with_tag( + destination_hash: [u8; 16], + requestor_transport_id: Option<[u8; 16]>, + tag: [u8; 16], + ) -> Vec { + let mut payload = Vec::new(); + payload.extend_from_slice(&destination_hash); + if let Some(id) = requestor_transport_id { + payload.extend_from_slice(&id); + } + payload.extend_from_slice(&tag); + payload + } + + #[test] + fn path_request_payloads_use_python_default_lengths() { + let destination = [0x11; 16]; + let requestor = [0x22; 16]; + + let leaf = make_path_request_payload(destination, None); + assert_eq!(leaf.len(), 32); + assert_eq!(&leaf[..16], &destination); + assert_eq!(&leaf[16..], &[0xA5; 16]); + + let transport = make_path_request_payload(destination, Some(requestor)); + assert_eq!(transport.len(), 48); + assert_eq!(&transport[..16], &destination); + assert_eq!(&transport[16..32], &requestor); + assert_eq!(&transport[32..], &[0xA5; 16]); + } + + #[test] + fn on_path_request_broadcasts_python_sized_leaf_payload() { + let (mut actor, _tx) = TransportActor::new(); + let (gateway, mut gateway_rx) = make_test_interface("gateway"); + actor.interfaces.insert(1, gateway); + + let requested = [0x33; 16]; + actor.on_path_request(requested); + + let raw = gateway_rx + .try_recv() + .expect("path request should broadcast on outbound interface"); + let (header, offset) = rns_wire::header::PacketHeader::unpack(&raw).unwrap(); + assert_eq!( + header.destination_hash, + rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.path.request", + None + ) + ); + let payload = &raw[offset..]; + assert_eq!(payload.len(), 32); + assert_eq!(&payload[..16], &requested); + } + + #[test] + fn transport_path_request_includes_identity_and_sixteen_byte_tag() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + actor.transport_identity_hash = Some([0x44; 16]); + let (gateway, mut gateway_rx) = make_test_interface("gateway"); + actor.interfaces.insert(1, gateway); + + let requested = [0x55; 16]; + actor.on_path_request(requested); + + let raw = gateway_rx + .try_recv() + .expect("transport path request should broadcast on outbound interface"); + let (_, offset) = rns_wire::header::PacketHeader::unpack(&raw).unwrap(); + let payload = &raw[offset..]; + assert_eq!(payload.len(), 48); + assert_eq!(&payload[..16], &requested); + assert_eq!(&payload[16..32], &[0x44; 16]); + } + + #[test] + fn unknown_path_request_only_forwards_from_discovery_modes() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (mut boundary, mut boundary_rx) = make_test_interface("boundary"); + boundary.mode = InterfaceMode::Boundary; + actor.interfaces.insert(1, boundary); + let (mut gateway, mut gateway_rx) = make_test_interface("gateway"); + gateway.mode = InterfaceMode::Gateway; + actor.interfaces.insert(2, gateway); + + actor.handle_inbound_path_request(&make_path_request_payload([0x11; 16], None), 1); + assert!( + gateway_rx.try_recv().is_err(), + "boundary interfaces should not trigger recursive unknown path discovery" + ); + + actor.handle_inbound_path_request(&make_path_request_payload([0x22; 16], None), 2); + assert!( + boundary_rx.try_recv().is_ok(), + "gateway interfaces should forward recursive unknown path discovery" + ); + } + + #[test] + fn inbound_tagless_path_request_is_ignored() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (mut gateway, _gateway_rx) = make_test_interface("gateway"); + gateway.mode = InterfaceMode::Gateway; + actor.interfaces.insert(1, gateway); + let (mut boundary, mut boundary_rx) = make_test_interface("boundary"); + boundary.mode = InterfaceMode::Boundary; + actor.interfaces.insert(2, boundary); + + let requested = [0xD1; 16]; + actor.handle_inbound_path_request(&requested, 1); + + assert!(boundary_rx.try_recv().is_err()); + assert!(actor.discovery_pr_tags.is_empty()); + assert!(!actor.path_requests.contains_key(&requested)); + } + + #[test] + fn inbound_path_request_dedupes_by_destination_and_tag() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (mut gateway, _gateway_rx) = make_test_interface("gateway"); + gateway.mode = InterfaceMode::Gateway; + actor.interfaces.insert(1, gateway); + let (mut boundary, mut boundary_rx) = make_test_interface("boundary"); + boundary.mode = InterfaceMode::Boundary; + actor.interfaces.insert(2, boundary); + + let requested = [0xD2; 16]; + let first = make_path_request_payload_with_tag(requested, None, [0xA5; 16]); + actor.handle_inbound_path_request(&first, 1); + boundary_rx + .try_recv() + .expect("first tagged request should be forwarded"); + + actor.handle_inbound_path_request(&first, 1); + assert!( + boundary_rx.try_recv().is_err(), + "duplicate destination+tag should be suppressed" + ); + + let second_tag = make_path_request_payload_with_tag(requested, None, [0xB6; 16]); + actor.handle_inbound_path_request(&second_tag, 1); + assert!( + boundary_rx.try_recv().is_err(), + "same destination with a new tag should not forward while discovery is already waiting" + ); + assert_eq!( + actor.discovery_pr_tags.len(), + 2, + "Python remembers the new tag even when the waiting destination suppresses forwarding" + ); + + actor + .discovery_path_requests + .get_mut(&requested) + .expect("first forwarded request should create a waiting discovery entry") + .timeout = 0.0; + actor.on_tick(); + + let third_tag = make_path_request_payload_with_tag(requested, None, [0xC7; 16]); + actor.handle_inbound_path_request(&third_tag, 1); + boundary_rx.try_recv().expect( + "same destination should forward again after the waiting discovery entry expires", + ); + assert_eq!(actor.discovery_pr_tags.len(), 3); + } + + #[test] + fn recursive_path_request_rewrites_requestor_transport_id() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + actor.transport_identity_hash = Some([0x44; 16]); + + let (mut gateway, _gateway_rx) = make_test_interface("gateway"); + gateway.mode = InterfaceMode::Gateway; + actor.interfaces.insert(1, gateway); + let (mut boundary, mut boundary_rx) = make_test_interface("boundary"); + boundary.mode = InterfaceMode::Boundary; + actor.interfaces.insert(2, boundary); + + let requested = [0xD3; 16]; + let original_requestor = [0x99; 16]; + let tag = [0xC7; 16]; + let incoming = make_path_request_payload_with_tag(requested, Some(original_requestor), tag); + actor.handle_inbound_path_request(&incoming, 1); + + let forwarded = boundary_rx + .try_recv() + .expect("recursive path request should be forwarded"); + let (_header, offset) = rns_wire::header::PacketHeader::unpack(&forwarded).unwrap(); + let payload = &forwarded[offset..]; + assert_eq!(payload.len(), 48); + assert_eq!(&payload[..16], &requested); + assert_eq!( + &payload[16..32], + &[0x44; 16], + "recursive request must advertise this transport as requester" + ); + assert_eq!(&payload[32..48], &tag); + } + + #[test] + fn local_destination_path_request_preserves_response_context() { + let (mut actor, _tx) = TransportActor::new(); + let (requestor, _requestor_rx) = make_test_interface("requestor"); + actor.interfaces.insert(1, requestor); + + let dest = [0xDA; 16]; + let (event_tx, mut event_rx) = mpsc::channel(4); + actor.local_destinations.insert(dest); + actor.destination_channels.insert(dest, event_tx); + + let tag = [0xDB; 16]; + actor.handle_inbound_path_request(&make_path_request_payload_with_tag(dest, None, tag), 1); + + let event = event_rx + .try_recv() + .expect("local path request should ask the destination to announce"); + let crate::link_messages::DestinationEvent::AnnounceRequested(request) = event else { + panic!("expected AnnounceRequested event"); + }; + assert!(request.path_response); + assert_eq!(request.tag.as_deref(), Some(&tag[..])); + assert_eq!(request.attached_interface, Some(1)); + } + + #[test] + fn outbound_attached_sends_only_to_target_interface() { + let (mut actor, _tx) = TransportActor::new(); + let (iface_a, mut rx_a) = make_test_interface("a"); + actor.interfaces.insert(1, iface_a); + let (iface_b, mut rx_b) = make_test_interface("b"); + actor.interfaces.insert(2, iface_b); + + let (raw, dest) = make_valid_announce("test.path_response.attached", 0); + actor.handle_message(TransportMessage::OutboundAttached { + request: OutboundRequest { + raw: raw.clone(), + destination_hash: dest, + }, + interface_id: 2, + }); + + assert!( + rx_a.try_recv().is_err(), + "attached outbound packets must not broadcast to other interfaces" + ); + assert_eq!( + rx_b.try_recv() + .expect("target interface should receive packet"), + raw + ); + } + + #[test] + fn discovery_path_request_is_answered_by_later_matching_announce() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + actor.transport_identity_hash = Some([0x44; 16]); + + let (mut requestor, mut requestor_rx) = make_test_interface("requestor"); + requestor.mode = InterfaceMode::Gateway; + actor.interfaces.insert(1, requestor); + let (mut boundary, mut boundary_rx) = make_test_interface("boundary"); + boundary.mode = InterfaceMode::Boundary; + actor.interfaces.insert(2, boundary); + + let (announce_raw, dest) = make_valid_announce("test.discovery_path.later_announce", 1); + let tag = [0xD8; 16]; + actor.handle_inbound_path_request(&make_path_request_payload_with_tag(dest, None, tag), 1); + + assert!( + actor.discovery_path_requests.contains_key(&dest), + "unknown recursive path requests must remember the requesting interface" + ); + let forwarded = boundary_rx + .try_recv() + .expect("transport should recursively forward the path request"); + let (_forwarded_header, forwarded_offset) = + rns_wire::header::PacketHeader::unpack(&forwarded).unwrap(); + assert_eq!(&forwarded[forwarded_offset..forwarded_offset + 16], &dest); + + actor.on_inbound(crate::messages::InboundPacket { + raw: announce_raw.clone(), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + let response = requestor_rx + .try_recv() + .expect("matching announce should be returned to the original requester"); + let (response_header, response_offset) = + rns_wire::header::PacketHeader::unpack(&response).unwrap(); + assert_eq!(response_header.destination_hash, dest); + assert_eq!( + response_header.context, + rns_wire::context::PacketContext::PathResponse + ); + assert_eq!( + response_header.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(response_header.transport_id, Some([0x44; 16])); + + let (_announce_header, announce_offset) = + rns_wire::header::PacketHeader::unpack(&announce_raw).unwrap(); + assert_eq!( + &response[response_offset..], + &announce_raw[announce_offset..] + ); + assert!( + actor.discovery_path_requests.contains_key(&dest), + "Python leaves discovery_path_requests in place until timeout cleanup" + ); + } + + #[test] + fn discovery_path_requests_expire_on_maintenance_tick() { + let (mut actor, _tx) = TransportActor::new(); + let requested = [0xD9; 16]; + actor.discovery_path_requests.insert( + requested, + DiscoveryPathRequest { + requesting_interface: 1, + timeout: 0.0, + }, + ); + + actor.on_tick(); + + assert!( + !actor.discovery_path_requests.contains_key(&requested), + "waiting discovery path requests should expire after PATH_REQUEST_TIMEOUT" + ); + } + + #[test] + fn known_path_request_does_not_answer_requestor_next_hop() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + actor.transport_identity_hash = Some([0x44; 16]); + + let (requestor, mut requestor_rx) = make_test_interface("requestor"); + actor.interfaces.insert(1, requestor); + let (next_hop_iface, _rx2) = make_test_interface("next_hop_iface"); + actor.interfaces.insert(2, next_hop_iface); + + let next_hop = [0xAB; 16]; + let (raw, dest) = make_valid_announce("test.path.request.next_hop", 1); + let mut path_entry = + crate::path_table::PathEntry::new(Some(next_hop), 2, 2, InterfaceMode::Gateway); + path_entry.packet_hash = Some(rns_wire::hash::packet_hash( + &raw, + rns_wire::flags::HeaderType::Header1, + )); + actor.path_table.insert(dest, path_entry); + actor.recent_announces.insert( + dest, + RecentAnnounce { + dest_hash: dest, + hops: 2, + app_data: None, + timestamp: now_f64(), + public_key: None, + ratchet: None, + raw_packet: raw.to_vec(), + retained: false, + name_hash: [0u8; 10], + }, + ); + + actor.handle_inbound_path_request(&make_path_request_payload(dest, Some(next_hop)), 1); + assert!( + requestor_rx.try_recv().is_err(), + "must not answer a path request when the requestor is our next hop" + ); + + actor.handle_inbound_path_request( + &make_path_request_payload_with_tag(dest, Some([0xCD; 16]), [0xB6; 16]), + 1, + ); + assert!( + requestor_rx.try_recv().is_err(), + "known path responses should be grace-queued, not sent immediately" + ); + let queued = actor + .announce_table + .get(&dest) + .expect("known path response should be queued"); + assert!(queued.block_rebroadcast); + assert_eq!(queued.attached_interface, Some(1)); + + actor.flush_pending_announces(); + let response = requestor_rx + .try_recv() + .expect("non-looping requestor should receive a path response"); + assert!(actor.announce_table.get(&dest).is_none()); + let (header, _) = rns_wire::header::PacketHeader::unpack(&response).unwrap(); + assert_eq!( + header.context, + rns_wire::context::PacketContext::PathResponse + ); + assert_eq!( + header.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(header.transport_id, Some([0x44; 16])); + } + + #[test] + fn known_path_response_restores_displaced_announce() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + actor.transport_identity_hash = Some([0x44; 16]); + + let (requestor, mut requestor_rx) = make_test_interface("requestor"); + actor.interfaces.insert(1, requestor); + let (next_hop_iface, _rx2) = make_test_interface("next_hop_iface"); + actor.interfaces.insert(2, next_hop_iface); + + let (raw, dest) = make_valid_announce("test.path.request.held", 1); + let mut path_entry = + crate::path_table::PathEntry::new(Some([0xAB; 16]), 2, 2, InterfaceMode::Gateway); + path_entry.packet_hash = Some(rns_wire::hash::packet_hash( + &raw, + rns_wire::flags::HeaderType::Header1, + )); + actor.path_table.insert(dest, path_entry); + actor.recent_announces.insert( + dest, + RecentAnnounce { + dest_hash: dest, + hops: 2, + app_data: None, + timestamp: now_f64(), + public_key: None, + ratchet: None, + raw_packet: raw.to_vec(), + retained: false, + name_hash: [0u8; 10], + }, + ); + + let held_raw = vec![0xAA, 0xBB, 0xCC]; + actor.announce_table.insert( + dest, + crate::announce::AnnounceEntry { + timestamp: now_f64(), + retransmit_timeout: now_f64() + 10.0, + retries: 0, + received_from: [0x22; 16], + hops: 1, + packet_raw: held_raw.clone(), + local_rebroadcasts: 0, + block_rebroadcast: false, + attached_interface: None, + source_interface: Some(2), + }, + ); + + actor.handle_inbound_path_request(&make_path_request_payload(dest, None), 1); + + let queued_response = actor + .announce_table + .get(&dest) + .expect("path response should temporarily occupy announce table"); + assert!(queued_response.block_rebroadcast); + assert_eq!(queued_response.attached_interface, Some(1)); + assert!( + actor.held_announces.contains_key(&dest), + "normal queued announce should be held while path response is served" + ); + + actor.flush_pending_announces(); + requestor_rx + .try_recv() + .expect("requestor should receive queued path response"); + + let restored = actor + .announce_table + .get(&dest) + .expect("held normal announce should be restored after path response send"); + assert!(!restored.block_rebroadcast); + assert_eq!(restored.packet_raw, held_raw); + assert!(!actor.held_announces.contains_key(&dest)); + } + + #[test] + fn known_path_request_not_answered_on_same_roaming_interface() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (mut roaming, mut roaming_rx) = make_test_interface("roaming"); + roaming.mode = InterfaceMode::Roaming; + actor.interfaces.insert(1, roaming); + + let (raw, dest) = make_valid_announce("test.path.request.roaming", 1); + actor.path_table.insert( + dest, + crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Roaming), + ); + actor.recent_announces.insert( + dest, + RecentAnnounce { + dest_hash: dest, + hops: 1, + app_data: None, + timestamp: now_f64(), + public_key: None, + ratchet: None, + raw_packet: raw.to_vec(), + retained: false, + name_hash: [0u8; 10], + }, + ); + + actor.handle_inbound_path_request(&make_path_request_payload(dest, None), 1); + assert!( + roaming_rx.try_recv().is_err(), + "roaming interface should not answer with a path learned on itself" + ); + } + + #[test] + fn local_client_announce_rebroadcasts_without_transport_mode() { + let (mut actor, _tx) = TransportActor::new(); + actor.transport_identity_hash = Some([0x44; 16]); + + let (mut local_client, mut local_rx) = make_test_interface("SharedInstanceServer/client_2"); + local_client.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, local_client); + let (gateway, mut gateway_rx) = make_test_interface("gateway"); + actor.interfaces.insert(2, gateway); + + let (raw, _dest) = make_valid_announce("test.shared.local_announce", 0); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + actor.on_tick(); + + assert!( + local_rx.try_recv().is_err(), + "local-client announce must not echo back to its origin" + ); + let forwarded = gateway_rx + .try_recv() + .expect("local-client announce should be sent to external interfaces"); + let (header, _) = rns_wire::header::PacketHeader::unpack(&forwarded).unwrap(); + assert_eq!( + header.flags.packet_type, + rns_wire::flags::PacketType::Announce + ); + assert_eq!(header.hops, 1); + } + + #[test] + fn external_announce_replays_to_local_client_with_transport_identity() { + let (mut actor, _tx) = TransportActor::new(); + actor.transport_identity_hash = Some([0x55; 16]); + + let (external, _external_rx) = make_test_interface("external"); + actor.interfaces.insert(1, external); + let (mut local_client, mut local_rx) = make_test_interface("SharedInstanceServer/client_3"); + local_client.role = InterfaceRole::LocalClient; + actor.interfaces.insert(2, local_client); + + let (raw, dest) = make_valid_announce("test.shared.external_announce", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + let replay = local_rx + .try_recv() + .expect("external announce should be replayed to local clients"); + let (header, _) = rns_wire::header::PacketHeader::unpack(&replay).unwrap(); + assert_eq!(header.destination_hash, dest); + assert_eq!( + header.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(header.transport_id, Some([0x55; 16])); + assert_eq!(header.context, rns_wire::context::PacketContext::None); + } + + #[test] + fn local_client_path_request_forwards_without_transport_mode() { + let (mut actor, _tx) = TransportActor::new(); + let (mut local_client, _local_rx) = make_test_interface("SharedInstanceServer/client_4"); + local_client.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, local_client); + let (gateway, mut gateway_rx) = make_test_interface("gateway"); + actor.interfaces.insert(2, gateway); + + let requested = [0x33; 16]; + actor.handle_inbound_path_request(&make_path_request_payload(requested, None), 1); + + let forwarded = gateway_rx + .try_recv() + .expect("shared instance must forward local-client path requests"); + let (header, offset) = rns_wire::header::PacketHeader::unpack(&forwarded).unwrap(); + assert_eq!( + header.destination_hash, + rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.path.request", + None + ) + ); + assert_eq!(&forwarded[offset..offset + 16], &requested); + } + + #[test] + fn external_path_request_for_local_client_round_trips_path_response() { + let (mut actor, _tx) = TransportActor::new(); + actor.transport_identity_hash = Some([0x66; 16]); + + let (mut local_client, mut local_rx) = make_test_interface("SharedInstanceServer/client_5"); + local_client.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, local_client); + let (external, mut external_rx) = make_test_interface("external"); + actor.interfaces.insert(2, external); + + let (raw, dest) = make_valid_announce("test.shared.local_path_response", 0); + actor.path_table.insert( + dest, + crate::path_table::PathEntry::new(None, 0, 1, InterfaceMode::Gateway), + ); + + actor.handle_inbound_path_request(&make_path_request_payload(dest, None), 2); + assert!( + actor.pending_local_path_requests.contains_key(&dest), + "external request for a local-client destination should be tracked" + ); + assert!( + local_rx.try_recv().is_ok(), + "external path request should be forwarded to local clients" + ); + + let mut response_raw = raw.to_vec(); + response_raw[rns_wire::constants::HEADER_MINSIZE - 1] = + rns_wire::context::PacketContext::PathResponse.to_byte(); + actor.on_inbound(crate::messages::InboundPacket { + raw: Bytes::from(response_raw), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + let response = external_rx + .try_recv() + .expect("local-client path response should be returned to the external requester"); + let (header, _) = rns_wire::header::PacketHeader::unpack(&response).unwrap(); + assert_eq!(header.destination_hash, dest); + assert_eq!( + header.context, + rns_wire::context::PacketContext::PathResponse + ); + assert_eq!( + header.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(header.transport_id, Some([0x66; 16])); + } + + #[test] + fn shared_instance_peer_deregister_clears_shared_route_state() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_shared_instance = true; + + let (mut shared_peer, _rx) = make_test_interface("SharedInstanceClient"); + shared_peer.role = InterfaceRole::SharedInstancePeer; + actor.interfaces.insert(1, shared_peer); + actor.path_table.insert( + [0x11; 16], + crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Gateway), + ); + actor.reverse_table.insert([0x22; 16], 1, 1); + actor.pending_local_path_requests.insert([0x33; 16], 1); + + actor.handle_message(TransportMessage::DeregisterInterface { id: 1 }); + + assert!(!actor.is_shared_instance); + assert!(actor.path_table.is_empty()); + assert!(actor.reverse_table.is_empty()); + assert!(actor.pending_local_path_requests.is_empty()); + } + + /// Build a valid announce on `app_name` from the supplied identity. Returns + /// `(raw_packet, dest_hash)`. Used by the aspect-filter dispatch tests so + /// one identity can announce under several aspects within a single test. + fn make_announce_for( + identity: &rns_identity::identity::Identity, + app_name: &str, + hops: u8, + ) -> (Bytes, [u8; 16]) { + make_announce_for_context( + identity, + app_name, + hops, + rns_wire::context::PacketContext::None, + ) + } + + fn make_announce_for_context( + identity: &rns_identity::identity::Identity, + app_name: &str, + hops: u8, + context: rns_wire::context::PacketContext, + ) -> (Bytes, [u8; 16]) { + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + app_name, + Some(&identity.hash), + ); + let announce_data = + rns_identity::announce::AnnounceData::create(identity, app_name, None, None).unwrap(); + let payload = announce_data.pack(); + + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Announce, + }, + hops, + transport_id: None, + destination_hash: dest_hash, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + (Bytes::from(raw), dest_hash) + } + + #[test] + fn dispatch_with_no_filter_receives_all() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("test_iface"); + actor.interfaces.insert(1, entry); + + let (htx, mut hrx) = mpsc::channel(8); + actor.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter: None, + receive_path_responses: false, + tx: htx, + }); + + let identity = rns_identity::identity::Identity::new(); + for aspect in &["lxmf.delivery", "lxmf.propagation", "nomadnetwork.node"] { + let (raw, _dh) = make_announce_for(&identity, aspect, 1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + + let mut received = 0; + while hrx.try_recv().is_ok() { + received += 1; + } + assert_eq!(received, 3, "None-filter handler must receive all aspects"); + } + + #[test] + fn dispatch_with_filter_only_matching_aspect() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("test_iface"); + actor.interfaces.insert(1, entry); + + let (htx, mut hrx) = mpsc::channel(8); + actor.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter: Some("lxmf.delivery".to_string()), + receive_path_responses: false, + tx: htx, + }); + + let identity = rns_identity::identity::Identity::new(); + let (raw_delivery, dh_delivery) = make_announce_for(&identity, "lxmf.delivery", 1); + let (raw_prop, _) = make_announce_for(&identity, "lxmf.propagation", 1); + let (raw_nomad, _) = make_announce_for(&identity, "nomadnetwork.node", 1); + + for raw in [raw_delivery, raw_prop, raw_nomad] { + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + + let mut events = Vec::new(); + while let Ok(ev) = hrx.try_recv() { + events.push(ev); + } + assert_eq!( + events.len(), + 1, + "filtered handler must only receive matching aspect" + ); + assert_eq!(events[0].destination_hash, dh_delivery); + assert_eq!( + events[0].name_hash, + rns_identity::name_hash::name_hash("lxmf.delivery") + ); + } + + #[test] + fn multiple_handlers_independent_filters() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("test_iface"); + actor.interfaces.insert(1, entry); + + let (h_del_tx, mut h_del_rx) = mpsc::channel(8); + let (h_prop_tx, mut h_prop_rx) = mpsc::channel(8); + actor.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter: Some("lxmf.delivery".to_string()), + receive_path_responses: false, + tx: h_del_tx, + }); + actor.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter: Some("lxmf.propagation".to_string()), + receive_path_responses: false, + tx: h_prop_tx, + }); + + let identity = rns_identity::identity::Identity::new(); + let (raw_delivery, dh_delivery) = make_announce_for(&identity, "lxmf.delivery", 1); + let (raw_prop, dh_prop) = make_announce_for(&identity, "lxmf.propagation", 1); + + for raw in [raw_delivery, raw_prop] { + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + + let del_events: Vec<_> = std::iter::from_fn(|| h_del_rx.try_recv().ok()).collect(); + let prop_events: Vec<_> = std::iter::from_fn(|| h_prop_rx.try_recv().ok()).collect(); + + assert_eq!(del_events.len(), 1, "delivery handler sees one event"); + assert_eq!(del_events[0].destination_hash, dh_delivery); + assert_eq!(prop_events.len(), 1, "propagation handler sees one event"); + assert_eq!(prop_events[0].destination_hash, dh_prop); + } + + #[test] + fn path_response_handler_requires_opt_in() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("test_iface"); + actor.interfaces.insert(1, entry); + + let (default_tx, mut default_rx) = mpsc::channel(8); + actor.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter: None, + receive_path_responses: false, + tx: default_tx, + }); + let (opt_in_tx, mut opt_in_rx) = mpsc::channel(8); + actor.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter: None, + receive_path_responses: true, + tx: opt_in_tx, + }); + + let identity = rns_identity::identity::Identity::new(); + let (raw, dest_hash) = make_announce_for_context( + &identity, + "test.path_response.handler", + 1, + rns_wire::context::PacketContext::PathResponse, + ); + let expected_hash = rns_wire::hash::packet_hash(&raw, rns_wire::flags::HeaderType::Header1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!( + default_rx.try_recv().is_err(), + "path responses must not reach default handlers" + ); + let event = opt_in_rx + .try_recv() + .expect("opt-in handler should receive path response"); + assert_eq!(event.destination_hash, dest_hash); + assert_eq!(event.announce_packet_hash, expected_hash); + assert!(event.is_path_response); + } + + #[test] + fn path_response_bypasses_announce_rate_limit() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (mut entry, _rx) = make_test_interface("limited_iface"); + entry.announce_rate_target = Some(999.0); + entry.announce_rate_grace = Some(0); + entry.announce_rate_penalty = Some(60.0); + actor.interfaces.insert(1, entry); + + let (handler_tx, mut handler_rx) = mpsc::channel(8); + actor.announce_handlers.push(AnnounceHandlerRegistration { + aspect_filter: None, + receive_path_responses: true, + tx: handler_tx, + }); + + let identity = rns_identity::identity::Identity::new(); + let (raw, dest_hash) = make_announce_for_context( + &identity, + "test.path_response.rate", + 1, + rns_wire::context::PacketContext::PathResponse, + ); + assert!( + !actor + .rate_table + .check_interface_rate(dest_hash, 999.0, 0, 60.0) + ); + assert!( + actor + .rate_table + .check_interface_rate(dest_hash, 999.0, 0, 60.0), + "precondition: destination is rate-blocked before path response arrives" + ); + + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!( + actor.path_table.has_path(&dest_hash), + "path response must still teach the path while rate-blocked" + ); + assert!( + actor.recent_announces.contains_key(&dest_hash), + "path response must still update announce cache while rate-blocked" + ); + assert!( + actor.announce_table.get(&dest_hash).is_none(), + "path responses are not queued for normal rebroadcast" + ); + assert!( + handler_rx.try_recv().unwrap().is_path_response, + "opt-in handlers still receive rate-blocked path responses" + ); + } + + #[test] + fn rate_limited_live_announce_still_learns_but_does_not_rebroadcast() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (mut entry, _rx) = make_test_interface("limited_iface"); + entry.announce_rate_target = Some(999.0); + entry.announce_rate_grace = Some(0); + entry.announce_rate_penalty = Some(60.0); + actor.interfaces.insert(1, entry); + + let identity = rns_identity::identity::Identity::new(); + let (first_raw, dest_hash) = + make_announce_for_with_random_blob(&identity, "test.live.rate", 1, random_blob(1, 1)); + actor.on_inbound(crate::messages::InboundPacket { + raw: first_raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + actor.announce_table.remove(&dest_hash); + + let (second_raw, _) = + make_announce_for_with_random_blob(&identity, "test.live.rate", 1, random_blob(2, 2)); + actor.on_inbound(crate::messages::InboundPacket { + raw: second_raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert!( + actor.path_table.has_path(&dest_hash), + "rate-blocked live announce must still update path state" + ); + assert!( + actor.recent_announces.contains_key(&dest_hash), + "rate-blocked live announce must still update recent announce state" + ); + assert!( + actor.announce_table.get(&dest_hash).is_none(), + "rate-blocked live announce must not be queued for rebroadcast" + ); + } + + #[test] + fn recent_announces_carry_name_hash() { + let (mut actor, _tx) = TransportActor::new(); + let (entry, _rx) = make_test_interface("test_iface"); + actor.interfaces.insert(1, entry); + + let identity = rns_identity::identity::Identity::new(); + let (raw, dh) = make_announce_for(&identity, "lxmf.delivery", 2); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + let entry = actor + .recent_announces + .get(&dh) + .expect("announce must be cached"); + assert_eq!( + entry.name_hash, + rns_identity::name_hash::name_hash("lxmf.delivery"), + "RecentAnnounce.name_hash must match SHA-256(app_name)[:10]" + ); + } +} diff --git a/crates/rns-transport/src/actor/outbound.rs b/crates/rns-transport/src/actor/outbound.rs new file mode 100644 index 0000000..27b1104 --- /dev/null +++ b/crates/rns-transport/src/actor/outbound.rs @@ -0,0 +1,677 @@ +use super::*; + +impl TransportActor { + pub(super) fn on_outbound(&mut self, request: crate::messages::OutboundRequest) { + self.traffic.record_tx(0, request.raw.len() as u64); // interface 0 = local + + let parsed = match rns_wire::header::PacketHeader::unpack(&request.raw) { + Ok((header, _)) => header, + Err(_) => return, + }; + + // Seed the dedup set with our own packet hash so echoes looped back + // from the fabric aren't re-processed. + let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type); + self.packet_hashlist.insert(pkt_hash); + + // Generate a general-purpose receipt for every outbound Data packet to a + // non-Plain destination so callers can observe delivery / timeout. + // Link- and resource-level contexts manage their own receipts. + if parsed.flags.packet_type == rns_wire::flags::PacketType::Data + && parsed.flags.destination_type != rns_wire::flags::DestinationType::Plain + { + let trunc_hash = + rns_wire::hash::truncated_packet_hash(&request.raw, parsed.flags.header_type); + if let std::collections::hash_map::Entry::Vacant(e) = + self.receipt_table.entry(trunc_hash) + { + let full_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type); + let receipt = PacketReceipt::new( + full_hash, + trunc_hash, + Some(std::time::Duration::from_secs(180)), + ); + e.insert(receipt); + trace!( + trunc = hex::encode(trunc_hash), + "generated receipt for outbound packet" + ); + } + } + + tracing::info!( + pkt_type = ?parsed.flags.packet_type, + dest = %hex::encode(request.destination_hash), + has_path = self.path_table.has_path(&request.destination_hash), + num_interfaces = self.interfaces.len(), + "outbound packet routing" + ); + + if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce { + self.broadcast_local_announce_on_interfaces(&request.raw, None); + return; + } + + match parsed.flags.destination_type { + rns_wire::flags::DestinationType::Plain | rns_wire::flags::DestinationType::Group => { + self.broadcast_on_interfaces(&request.raw, None); + } + rns_wire::flags::DestinationType::Single | rns_wire::flags::DestinationType::Link => { + if let Some(path) = self.path_table.get(&request.destination_hash) { + let target_interface = path.interface_id; + let path_hops = path.hops; + let path_next_hop = path.next_hop; + let iface_name = self + .interfaces + .get(&target_interface) + .map(|e| e.name.as_str()) + .unwrap_or("unknown"); + tracing::info!( + dest = %hex::encode(request.destination_hash), + interface_id = target_interface, + interface_name = %iface_name, + hops = path_hops, + next_hop = ?path_next_hop.map(hex::encode), + "outbound: routed via path" + ); + + // Transport nodes only forward Header2 packets whose transport_id + // matches their identity — Python hubs silently drop Header1 — + // so every directed send through a relay must be wrapped. + if let Some(next_hop) = path_next_hop { + if parsed.flags.header_type == rns_wire::flags::HeaderType::Header1 { + let new_flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header2, + transport_type: rns_wire::flags::TransportType::Transport, + ..parsed.flags + }; + let new_header = rns_wire::header::PacketHeader { + flags: new_flags, + hops: parsed.hops, + transport_id: Some(next_hop), + destination_hash: parsed.destination_hash, + context: parsed.context, + }; + let mut new_raw = new_header.pack(); + new_raw.extend_from_slice( + &request.raw[rns_wire::constants::HEADER_MINSIZE..], + ); + tracing::debug!( + original_len = request.raw.len(), + new_len = new_raw.len(), + transport_id = %hex::encode(next_hop), + "outbound: wrapped Header1 -> Header2 for transport" + ); + self.send_to_interface(target_interface, &new_raw); + } else { + self.send_to_interface(target_interface, &request.raw); + } + } else { + self.send_to_interface(target_interface, &request.raw); + } + + // Touch the path so an actively-used route isn't culled + // for staleness while traffic is still flowing on it. + if let Some(path) = self.path_table.get_mut(&request.destination_hash) { + path.timestamp = now_f64(); + } + } else { + let iface_names: Vec<&str> = self + .interfaces + .values() + .filter(|e| e.direction.outbound) + .map(|e| e.name.as_str()) + .collect(); + tracing::info!( + dest = %hex::encode(request.destination_hash), + broadcast_to = ?iface_names, + "outbound: no path, broadcasting" + ); + self.broadcast_on_interfaces(&request.raw, None); + self.on_path_request(request.destination_hash); + } + } + } + } + + pub(super) fn on_outbound_attached( + &mut self, + request: crate::messages::OutboundRequest, + interface_id: InterfaceId, + ) { + self.traffic.record_tx(0, request.raw.len() as u64); + + if let Ok((parsed, _)) = rns_wire::header::PacketHeader::unpack(&request.raw) { + let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type); + self.packet_hashlist.insert(pkt_hash); + self.send_to_interface(interface_id, &request.raw); + if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce + && let Some(entry) = self.interfaces.get_mut(&interface_id) + { + entry.ingress.sent_announce(); + } + } + } + + /// Payload is a 32-byte packet hash identifying a cached announce. Look + /// up the destination via `path_table.packet_hash`, fetch the stored raw + /// announce in `recent_announces`, and rebroadcast it so the requester + /// can resume an interrupted route. + pub(super) fn handle_cache_request( + &mut self, + raw: &[u8], + header: &rns_wire::header::PacketHeader, + _interface_id: InterfaceId, + ) { + let payload_start = match self.data_payload_offset(raw, header) { + Some(offset) => offset, + None => { + trace!("cache request: packet too short for header"); + return; + } + }; + let payload = &raw[payload_start..]; + + if payload.len() != 32 { + trace!( + len = payload.len(), + "cache request: payload is not 32 bytes (expected packet hash), ignoring" + ); + return; + } + + let mut requested_hash = [0u8; 32]; + requested_hash.copy_from_slice(payload); + + let dest_hash: Option<[u8; 16]> = self + .path_table + .iter() + .find(|(_, entry)| entry.packet_hash == Some(requested_hash)) + .map(|(dest, _)| *dest.as_bytes()); + + let Some(dest) = dest_hash else { + trace!( + hash = %hex::encode(requested_hash), + "cache request miss — no path entry with matching packet hash" + ); + return; + }; + + let (cached_raw, cached_hops) = match self.recent_announces.get(&dest) { + Some(cached) => (cached.raw_packet.clone(), cached.hops), + None => { + trace!( + dest = %hex::encode(dest), + "cache request: path entry found but no cached announce for destination" + ); + return; + } + }; + + if cached_raw.is_empty() { + trace!( + dest = %hex::encode(dest), + "cache request: announce cached but no raw packet (v1 persistence), ignoring" + ); + return; + } + + debug!( + dest = %hex::encode(dest), + hops = cached_hops, + hash = %hex::encode(requested_hash), + "cache request hit — replaying cached announce" + ); + if self.is_transport_enabled { + self.broadcast_announce_on_interfaces(&cached_raw, None); + } + } + + pub(super) fn data_payload_offset( + &self, + raw: &[u8], + header: &rns_wire::header::PacketHeader, + ) -> Option { + let offset = match header.flags.header_type { + rns_wire::flags::HeaderType::Header1 => rns_wire::constants::HEADER_MINSIZE, // 19 + rns_wire::flags::HeaderType::Header2 => rns_wire::constants::HEADER_MAXSIZE, // 35 + }; + if offset <= raw.len() { + Some(offset) + } else { + None + } + } + + /// Local destination -> fire waiters so the owner re-announces. + /// Known path + transport enabled -> replay the cached announce. + /// Otherwise, on a transport node, forward the request on other interfaces. + pub(super) fn handle_inbound_path_request(&mut self, data: &[u8], interface_id: InterfaceId) { + if data.len() < 16 { + return; + } + + let is_from_local_client = self.is_local_client_interface(interface_id); + + let mut requested_dest = [0u8; 16]; + requested_dest.copy_from_slice(&data[..16]); + + // Python transport nodes send destination(16) + requestor transport + // id(16) + tag(16). Leaf nodes normally send destination(16) + tag(16). + // On receive, Python treats payloads longer than 32 bytes as transport + // requests and truncates any remaining tag bytes to 16. + let requestor_transport_id = if data.len() > 32 { + let mut id = [0u8; 16]; + id.copy_from_slice(&data[16..32]); + Some(id) + } else { + None + }; + let tag_bytes = if data.len() > 32 { + Some(&data[32..data.len().min(48)]) + } else if data.len() > 16 { + Some(&data[16..data.len().min(32)]) + } else { + None + }; + + let Some(tag) = tag_bytes else { + trace!( + dest = %hex::encode(requested_dest), + "ignoring tagless path request" + ); + return; + }; + + let now = now_f64(); + let mut unique_tag = Vec::with_capacity(32); + unique_tag.extend_from_slice(&requested_dest); + unique_tag.extend_from_slice(tag); + if let Some(last) = self.discovery_pr_tags.get(&unique_tag) + && now - last < PATH_REQUEST_GATE_TIMEOUT + { + trace!(dest = %hex::encode(requested_dest), "ignoring duplicate path request"); + return; + } + self.discovery_pr_tags.insert(unique_tag, now); + + if self.local_destinations.contains(&requested_dest) { + debug!( + dest = %hex::encode(requested_dest), + "answering path request — destination is local" + ); + if let Some(tx) = self.destination_channels.get(&requested_dest) + && let Err(e) = + tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested( + crate::link_messages::AnnounceRequest { + app_name: String::new(), + path_response: true, + tag: Some(tag.to_vec()), + attached_interface: Some(interface_id), + }, + )) + { + self.channel_drops += 1; + warn!(dest = hex::encode(requested_dest), drops = self.channel_drops, err = %e, + "failed to send AnnounceRequested for local path request"); + } + self.fire_path_waiters(&requested_dest); + return; + } + + if !is_from_local_client + && let Some(path) = self.path_table.get(&requested_dest) + && self.is_local_client_interface(path.interface_id) + { + self.pending_local_path_requests + .insert(requested_dest, interface_id); + } + + // Python Transport.py: local shared clients are allowed to use the + // shared instance's path cache even when the instance is not a transport + // node. Ordinary peers still require transport mode. + if (self.is_transport_enabled || is_from_local_client) + && let Some(path) = self.path_table.get(&requested_dest) + { + let requestor_is_next_hop = + requestor_transport_id.is_some_and(|requestor| path.next_hop == Some(requestor)); + let same_roaming_interface = self + .interfaces + .get(&interface_id) + .is_some_and(|iface| iface.mode == InterfaceMode::Roaming) + && path.interface_id == interface_id; + + if requestor_is_next_hop { + debug!( + dest = %hex::encode(requested_dest), + "not answering path request — requester is our next hop" + ); + return; + } + if same_roaming_interface { + debug!( + dest = %hex::encode(requested_dest), + "not answering path request on roaming interface learned from same interface" + ); + return; + } + + let cached_raw: Option<(u8, Vec)> = + self.recent_announces.get(&requested_dest).and_then(|a| { + if a.raw_packet.is_empty() { + None + } else { + Some((path.hops, a.raw_packet.clone())) + } + }); + if let Some((hops, raw)) = cached_raw { + debug!( + dest = %hex::encode(requested_dest), + hops, + "answering path request — path is known, queueing path response" + ); + let response = self.path_response_from_cached_announce(&raw, requested_dest, hops); + let now = now_f64(); + let path_on_local_client = self.is_local_client_interface(path.interface_id); + let response_delay = if is_from_local_client || path_on_local_client { + 0.0 + } else { + let roaming_extra = if self + .interfaces + .get(&interface_id) + .is_some_and(|iface| iface.mode == InterfaceMode::Roaming) + { + PATH_REQUEST_RG + } else { + 0.0 + }; + PATH_REQUEST_GRACE + roaming_extra + }; + if let Some(held_entry) = self.announce_table.remove(&requested_dest) { + self.held_announces.insert(requested_dest, held_entry); + } + self.announce_table.insert( + requested_dest, + crate::announce::AnnounceEntry { + timestamp: now, + retransmit_timeout: now + response_delay, + retries: 0, + received_from: requestor_transport_id.unwrap_or([0; 16]), + hops, + packet_raw: response, + local_rebroadcasts: 0, + block_rebroadcast: true, + attached_interface: Some(interface_id), + source_interface: None, + }, + ); + return; + } + } + + let should_search_unknown = self + .interfaces + .get(&interface_id) + .is_some_and(|iface| mode_discovers_unknown_paths(iface.mode)); + + if is_from_local_client { + debug!( + dest = %hex::encode(requested_dest), + "forwarding path request from local shared client" + ); + self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, false); + } else if self.is_transport_enabled && should_search_unknown { + let should_forward = match self.discovery_path_requests.entry(requested_dest) { + std::collections::hash_map::Entry::Occupied(_) => { + debug!( + dest = %hex::encode(requested_dest), + "not forwarding path request — discovery request is already waiting" + ); + false + } + std::collections::hash_map::Entry::Vacant(entry) => { + debug!( + dest = %hex::encode(requested_dest), + "forwarding path request on other interfaces" + ); + entry.insert(DiscoveryPathRequest { + requesting_interface: interface_id, + timeout: now + PATH_REQUEST_TIMEOUT, + }); + true + } + }; + if should_forward { + self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true); + } + } else if self.has_local_client_interfaces() { + debug!( + dest = %hex::encode(requested_dest), + "forwarding path request to local shared clients" + ); + for local_id in self.local_client_interface_ids_except(Some(interface_id)) { + self.send_path_request(requested_dest, local_id, None, false); + } + } else { + debug!( + dest = %hex::encode(requested_dest), + interface_id, + "ignoring unknown path request on non-discovery interface" + ); + } + } + + fn build_path_request_packet(&self, destination_hash: [u8; 16], tag: Option<&[u8]>) -> Vec { + let mut request_data = Vec::with_capacity(48); + request_data.extend_from_slice(&destination_hash); + if self.is_transport_enabled + && let Some(identity_hash) = self.transport_identity_hash + { + request_data.extend_from_slice(&identity_hash); + } + if let Some(tag) = tag { + request_data.extend_from_slice(&tag[..tag.len().min(16)]); + } else { + request_data.extend_from_slice(&rns_crypto::random::random_bytes(16)); + } + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Plain, + packet_type: rns_wire::flags::PacketType::Data, + }; + let pr_dest = rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.path.request", + None, + ); + let pr_header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: pr_dest, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = pr_header.pack(); + raw.extend_from_slice(&request_data); + raw + } + + fn send_path_request( + &mut self, + destination_hash: [u8; 16], + interface_id: InterfaceId, + tag: Option<&[u8]>, + _recursive: bool, + ) { + let raw = self.build_path_request_packet(destination_hash, tag); + self.send_to_interface(interface_id, &raw); + self.path_requests.insert(destination_hash, now_f64()); + } + + fn forward_path_request( + &mut self, + destination_hash: [u8; 16], + except: Option, + tag: Option<&[u8]>, + recursive: bool, + ) { + let ids: Vec = self + .interfaces + .iter() + .filter_map(|(&id, entry)| { + if except == Some(id) || !entry.direction.outbound { + None + } else { + Some(id) + } + }) + .collect(); + for id in ids { + self.send_path_request(destination_hash, id, tag, recursive); + } + } + + pub(super) fn on_path_request(&mut self, destination_hash: [u8; 16]) { + let now = now_f64(); + + if let Some(last) = self.path_requests.get(&destination_hash) + && now - last < PATH_REQUEST_MI + { + return; + } + + self.path_requests.insert(destination_hash, now); + + if self.path_table.has_path(&destination_hash) { + return; + } + + // Python Transport.request_path sends a PLAIN packet to the + // rnstransport.path.request destination. The payload is the requested + // destination hash, optionally followed by the transport identity hash, + // and a random tag used for request deduplication. + let mut request_tag = [0u8; 16]; + { + use rand::RngCore; + rand::thread_rng().fill_bytes(&mut request_tag); + } + + let mut request_data = Vec::with_capacity(48); + request_data.extend_from_slice(&destination_hash); + if self.is_transport_enabled + && let Some(identity_hash) = self.transport_identity_hash + { + request_data.extend_from_slice(&identity_hash); + } + request_data.extend_from_slice(&request_tag); + + let path_request_dest = rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.path.request", + None, + ); + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Plain, + packet_type: rns_wire::flags::PacketType::Data, + }; + let path_request_header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: path_request_dest, + context: rns_wire::context::PacketContext::None, + }; + let mut request_raw = path_request_header.pack(); + request_raw.extend_from_slice(&request_data); + self.broadcast_on_interfaces(&request_raw, None); + + debug!( + dest = hex::encode(destination_hash), + "path request broadcast" + ); + } + + /// On tunnel reappearance, reinstall any still-valid cached paths into the + /// path table so in-flight routes survive a link flap. Paths already + /// superseded by a shorter live route, or expired, are discarded. + pub(super) fn restore_tunnel_paths(&mut self, tunnel_id: &[u8; 32], interface_id: InterfaceId) { + let now = now_f64(); + let mut deprecated_paths: Vec<[u8; 16]> = Vec::new(); + + let paths: Vec<([u8; 16], crate::tunnel::TunnelPath)> = + if let Some(tunnel) = self.tunnel_table.get(tunnel_id) { + tunnel + .tunnel_paths + .iter() + .map(|(dest, tp)| (*dest, tp.clone())) + .collect() + } else { + return; + }; + + for (dest_hash, tunnel_path) in &paths { + let mut should_add = false; + + if let Some(existing) = self.path_table.get(dest_hash) { + let old_hops = existing.hops; + let old_expires = existing.expires; + // Only overwrite a live path if the tunnel copy is at least + // as short, or the live entry is already stale. + if tunnel_path.hops <= old_hops || now > old_expires { + should_add = true; + } else { + debug!( + dest = hex::encode(dest_hash), + "did not restore tunnel path: newer path with fewer hops exists" + ); + } + } else if now < tunnel_path.expires { + should_add = true; + } else { + debug!( + dest = hex::encode(dest_hash), + "did not restore tunnel path: expired" + ); + } + + if should_add { + let entry = crate::path_table::PathEntry { + timestamp: now, + next_hop: None, + hops: tunnel_path.hops, + expires: tunnel_path.expires, + random_blobs: tunnel_path.random_blobs.iter().copied().collect(), + interface_id, + packet_hash: None, + }; + self.path_table.insert(*dest_hash, entry); + self.state_dirty = true; + self.fire_path_waiters(dest_hash); + debug!( + dest = hex::encode(dest_hash), + hops = tunnel_path.hops, + "restored tunnel path" + ); + } else { + deprecated_paths.push(*dest_hash); + } + } + + if !deprecated_paths.is_empty() + && let Some(tunnel) = self.tunnel_table.get_mut(tunnel_id) + { + for dest_hash in &deprecated_paths { + tunnel.tunnel_paths.remove(dest_hash); + debug!( + dest = hex::encode(dest_hash), + tunnel = hex::encode(&tunnel_id[..16]), + "removed deprecated path from tunnel" + ); + } + } + } +} diff --git a/crates/rns-transport/src/actor/persistence.rs b/crates/rns-transport/src/actor/persistence.rs new file mode 100644 index 0000000..186bceb --- /dev/null +++ b/crates/rns-transport/src/actor/persistence.rs @@ -0,0 +1,593 @@ +use super::*; +use tracing::info; + +/// Wall-clock helper kept here so tests can inject a fake clock without +/// dragging it through the actor. +fn now() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0) +} + +impl TransportActor { + /// Flush the small/critical routing-state files: path_table, + /// announce_cache, blackhole_table, tunnel_table. Hashlist is excluded — + /// it can be multiple MB and is rebuildable from in-flight traffic, so + /// we save it only on shutdown / falling-edge via `save_state`. + /// Called from the periodic `on_tick` save (every + /// `STATE_SAVE_INTERVAL_SECS`, gated on `state_dirty`). Clears + /// `state_dirty` and bumps `last_state_save` so the periodic trigger + /// doesn't double-fire. + pub(super) fn save_routing_state(&mut self) { + if let Some(ref dir) = self.storage_dir { + let interface_names: std::collections::HashMap = self + .interfaces + .iter() + .map(|(&id, entry)| (id, entry.name.clone())) + .collect(); + + let path_table_path = dir.join("path_table.msgpack"); + if let Err(e) = crate::persistence::save_path_table( + &self.path_table, + &interface_names, + &path_table_path, + ) { + trace!("failed to save path table: {}", e); + } else { + debug!("saved path table ({} entries)", self.path_table.len()); + } + + let destination_table_path = dir.join("destination_table"); + if let Err(e) = crate::persistence::save_python_destination_table( + &self.path_table, + &interface_names, + &destination_table_path, + ) { + trace!("failed to save Python destination_table: {}", e); + } + + let blackhole_path = dir.join("blackhole_table.msgpack"); + if let Err(e) = + crate::persistence::save_blackhole_table(&self.blackhole_table, &blackhole_path) + { + trace!("failed to save blackhole table: {}", e); + } else { + debug!( + "saved blackhole table ({} entries)", + self.blackhole_table.len() + ); + } + + if let Some(local_identity_hash) = self.transport_identity_hash { + let blackhole_dir = dir.join("blackhole"); + if let Err(e) = crate::persistence::save_python_blackhole_files( + &self.blackhole_table, + local_identity_hash, + &blackhole_dir, + ) { + trace!("failed to save Python blackhole files: {}", e); + } + } + + let announce_path = dir.join("announce_cache.msgpack"); + if let Err(e) = crate::persistence::save_announce_cache( + self.recent_announces.values(), + &announce_path, + ) { + trace!("failed to save announce cache: {}", e); + } else { + debug!( + "saved announce cache ({} entries)", + self.recent_announces.len() + ); + } + + let announce_cache_dir = dir.join("cache").join("announces"); + if let Err(e) = crate::persistence::save_python_announce_cache_for_paths( + &self.path_table, + self.recent_announces.values(), + &interface_names, + &announce_cache_dir, + ) { + trace!("failed to save Python announce cache files: {}", e); + } + + let tunnel_path = dir.join("tunnel_table.msgpack"); + if let Err(e) = crate::persistence::save_tunnel_table( + &self.tunnel_table, + &interface_names, + &tunnel_path, + ) { + trace!("failed to save tunnel table: {}", e); + } else { + debug!("saved tunnel table ({} entries)", self.tunnel_table.len()); + } + + // Single-line summary for diagnosing periodic routing-state saves + // without surfacing normal flushes at default log levels. + debug!( + paths = self.path_table.len(), + announces = self.recent_announces.len(), + tunnels = self.tunnel_table.len(), + blackhole = self.blackhole_table.len(), + "flushed routing state" + ); + } + self.state_dirty = false; + self.last_state_save = now(); + } + + /// Flush every persisted table including the (potentially large) packet + /// hashlist. Called on `on_shutdown` and the foreground→background + /// falling edge — both are infrequent and worth the full snapshot. + pub(super) fn save_state(&mut self) { + // Routing state first so the order matches the periodic-save shape. + self.save_routing_state(); + + if let Some(ref dir) = self.storage_dir { + let hashlist_path = dir.join("packet_hashlist"); + if let Err(e) = crate::persistence::save_hashlist(&self.packet_hashlist, &hashlist_path) + { + trace!("failed to save hashlist: {}", e); + } else { + info!(entries = self.packet_hashlist.len(), "flushed hashlist"); + } + } + } + + pub(super) fn on_shutdown(&mut self) { + self.save_state(); + } + + /// Restore on-disk transport state. Entries can't bind to a concrete + /// `interface_id` until the matching interface re-registers, so they're + /// staged in `pending_path_entries` / `pending_tunnel_entries` and + /// drained by `RegisterInterface`. Entries lacking `interface_name` + /// (pre-v3) are dropped — `interface_id` is volatile across boots. + pub(super) fn load_state(&mut self) { + let Some(dir) = self.storage_dir.clone() else { + return; + }; + let now_ts = now(); + + // packet_hashlist — Python-compatible canonical shape. Fall back to + // the old Rust sidecar so existing local development state still loads. + let hashlist_path = dir.join("packet_hashlist"); + let legacy_hashlist_path = dir.join("hashlist.msgpack"); + let hashlist_path = if hashlist_path.exists() { + Some(hashlist_path) + } else if legacy_hashlist_path.exists() { + Some(legacy_hashlist_path) + } else { + None + }; + if let Some(hashlist_path) = hashlist_path { + match crate::persistence::load_hashlist(&hashlist_path) { + Ok(hashes) => { + let count = hashes.len(); + self.packet_hashlist.load_from(hashes); + debug!(count, "loaded packet hashlist from disk"); + } + Err(e) => { + trace!("failed to load packet hashlist: {}", e); + } + } + } + + // Python destination_table — canonical interop shape. Defer interface + // hash remap until matching interfaces register. + let destination_table_path = dir.join("destination_table"); + let loaded_python_destination_table = if destination_table_path.exists() { + match crate::persistence::load_python_destination_table(&destination_table_path) { + Ok(entries) => { + let total = entries.len(); + let mut expired = 0usize; + let mut missing_cache = 0usize; + let mut pending = 0usize; + let announce_cache_dir = dir.join("cache").join("announces"); + for pe in entries { + if pe.expires <= now_ts { + expired += 1; + continue; + } + let cached = match crate::persistence::load_python_cached_announce( + &announce_cache_dir, + &pe.packet_hash, + ) { + Ok(Some(cached)) => cached, + Ok(None) => { + missing_cache += 1; + continue; + } + Err(_) => { + missing_cache += 1; + continue; + } + }; + let next_hop = if pe.received_from == pe.destination_hash { + None + } else { + Some(pe.received_from.to_vec()) + }; + self.pending_path_entries + .push(crate::persistence::PersistedPathEntry { + destination_hash: pe.destination_hash.to_vec(), + timestamp: pe.timestamp, + next_hop, + hops: pe.hops, + expires: pe.expires, + random_blobs: pe + .random_blobs + .iter() + .map(|blob| blob.to_vec()) + .collect(), + interface_id: 0, + interface_name: cached.interface_reference.clone(), + interface_hash: Some(pe.interface_hash.to_vec()), + packet_hash: Some(pe.packet_hash.to_vec()), + }); + self.recent_announces + .entry(pe.destination_hash) + .or_insert_with(|| RecentAnnounce { + dest_hash: pe.destination_hash, + hops: pe.hops, + app_data: None, + timestamp: pe.timestamp, + public_key: None, + ratchet: None, + raw_packet: cached.raw_packet, + retained: false, + name_hash: [0u8; 10], + }); + pending += 1; + } + debug!( + total, + pending, expired, missing_cache, "staged Python destination_table entries" + ); + pending > 0 + } + Err(e) => { + trace!("failed to load Python destination_table: {}", e); + false + } + } + } else { + false + }; + + // path_table — legacy Rust sidecar fallback, defer remap. + let path_table_path = dir.join("path_table.msgpack"); + if !loaded_python_destination_table && path_table_path.exists() { + match crate::persistence::load_path_table(&path_table_path) { + Ok(entries) => { + let total = entries.len(); + let mut expired = 0usize; + let mut legacy = 0usize; + let mut pending = 0usize; + for pe in entries { + if pe.destination_hash.len() != 16 { + continue; + } + if pe.expires <= now_ts { + expired += 1; + continue; + } + if pe.interface_name.is_none() && pe.interface_hash.is_none() { + legacy += 1; + continue; + } + self.pending_path_entries.push(pe); + pending += 1; + } + debug!( + total, + pending, expired, legacy, "staged path entries from disk" + ); + } + Err(e) => { + trace!("failed to load path table: {}", e); + } + } + } + + // blackhole_table — bind directly, no interface dependency. + let blackhole_path = dir.join("blackhole_table.msgpack"); + if blackhole_path.exists() { + match crate::persistence::load_blackhole_table(&blackhole_path) { + Ok(entries) => { + let count = entries.len(); + for be in entries { + if be.identity_hash.len() == 16 { + let mut hash = [0u8; 16]; + hash.copy_from_slice(&be.identity_hash); + self.blackhole_table.insert_entry( + hash, + crate::blackhole::BlackholeEntry { + created: be.created, + ttl: be.ttl, + reason: be.reason, + reason_label: be.reason_label, + source: None, + }, + ); + } + } + debug!("loaded {} blackhole entries from disk", count); + } + Err(e) => { + trace!("failed to load blackhole table: {}", e); + } + } + } + self.load_python_blackhole_if_ready(); + + // tunnel_table — defer remap. + let tunnel_path = dir.join("tunnel_table.msgpack"); + if tunnel_path.exists() { + match crate::persistence::load_tunnel_table(&tunnel_path) { + Ok(entries) => { + let total = entries.len(); + let mut expired = 0usize; + let mut legacy = 0usize; + let mut pending = 0usize; + for te in entries { + if te.tunnel_id.len() != 32 { + continue; + } + if te.expires <= now_ts { + expired += 1; + continue; + } + if te.interface_name.is_none() { + legacy += 1; + continue; + } + self.pending_tunnel_entries.push(te); + pending += 1; + } + debug!( + total, + pending, expired, legacy, "staged tunnel entries from disk" + ); + } + Err(e) => { + trace!("failed to load tunnel table: {}", e); + } + } + } + + // announce_cache — no interface dependency, bind directly. + let announce_path = dir.join("announce_cache.msgpack"); + if announce_path.exists() { + match crate::persistence::load_announce_cache(&announce_path) { + Ok(entries) => { + let count = entries.len(); + for ae in entries { + if ae.destination_hash.len() == 16 { + let mut hash = [0u8; 16]; + hash.copy_from_slice(&ae.destination_hash); + let public_key = ae.public_key.and_then(|k| { + if k.len() == 64 { + let mut arr = [0u8; 64]; + arr.copy_from_slice(&k); + Some(arr) + } else { + None + } + }); + let ratchet = ae.ratchet.and_then(|r| { + if r.len() == 32 { + let mut arr = [0u8; 32]; + arr.copy_from_slice(&r); + Some(arr) + } else { + None + } + }); + let name_hash = if ae.name_hash.len() == 10 { + let mut nh = [0u8; 10]; + nh.copy_from_slice(&ae.name_hash); + nh + } else { + [0u8; 10] + }; + self.recent_announces + .entry(hash) + .or_insert_with(|| RecentAnnounce { + dest_hash: hash, + hops: ae.hops, + app_data: ae.app_data, + timestamp: ae.timestamp, + public_key, + ratchet, + raw_packet: ae.raw_packet, + retained: ae.retained, + name_hash, + }); + } + } + debug!("loaded {} announce cache entries from disk", count); + } + Err(e) => { + trace!("failed to load announce cache: {}", e); + } + } + } + } + + pub(super) fn load_python_blackhole_if_ready(&mut self) { + let (Some(dir), Some(local_identity_hash)) = + (self.storage_dir.as_ref(), self.transport_identity_hash) + else { + return; + }; + let blackhole_dir = dir.join("blackhole"); + match crate::persistence::load_python_blackhole_dir( + &blackhole_dir, + local_identity_hash, + &self.blackhole_sources, + now(), + ) { + Ok(entries) => { + let count = entries.len(); + for entry in entries { + let source = if entry.source == local_identity_hash { + None + } else { + Some(entry.source.into()) + }; + self.blackhole_table.insert_entry( + entry.identity_hash, + crate::blackhole::BlackholeEntry { + created: entry.created, + ttl: entry.ttl, + reason: entry.reason, + reason_label: entry.reason_label, + source, + }, + ); + } + if count > 0 { + debug!(count, "loaded Python blackhole files"); + } + } + Err(e) => { + trace!("failed to load Python blackhole files: {}", e); + } + } + } + + /// Drain pending path/tunnel entries whose `interface_name` matches the + /// just-registered interface. Bound to `RegisterInterface` so each entry + /// rebinds to whatever `interface_id` the runtime allocated this boot. + pub(super) fn drain_pending_for_interface(&mut self, id: InterfaceId, name: &str) { + if !self.pending_path_entries.is_empty() { + let mut promoted = 0usize; + self.pending_path_entries.retain(|pe| { + let name_matches = pe.interface_name.as_deref() == Some(name); + let hash_matches = pe.interface_hash.as_deref().is_some_and(|hash| { + hash == crate::persistence::interface_hash_from_name(name).as_slice() + }); + if !name_matches && !hash_matches { + return true; + } + if pe.destination_hash.len() != 16 { + return false; + } + let mut hash = [0u8; 16]; + hash.copy_from_slice(&pe.destination_hash); + let next_hop = pe.next_hop.as_ref().and_then(|h| { + if h.len() == 16 { + let mut arr = [0u8; 16]; + arr.copy_from_slice(h); + Some(arr) + } else { + None + } + }); + let entry = crate::path_table::PathEntry { + timestamp: pe.timestamp, + next_hop, + hops: pe.hops, + expires: pe.expires, + random_blobs: pe + .random_blobs + .iter() + .filter_map(|b| { + if b.len() == 10 { + let mut arr = [0u8; 10]; + arr.copy_from_slice(b); + Some(arr) + } else { + None + } + }) + .collect(), + interface_id: id, + packet_hash: pe.packet_hash.as_ref().and_then(|h| { + if h.len() == 32 { + let mut arr = [0u8; 32]; + arr.copy_from_slice(h); + Some(arr) + } else { + None + } + }), + }; + if !self.path_table.has_path(&hash) { + self.path_table.insert(hash, entry); + promoted += 1; + } + false + }); + if promoted > 0 { + debug!( + interface_id = id, + name = %name, + promoted, + "rebound persisted path entries to live interface" + ); + } + } + + if !self.pending_tunnel_entries.is_empty() { + let mut promoted = 0usize; + self.pending_tunnel_entries.retain(|te| { + if te.interface_name.as_deref() != Some(name) { + return true; + } + if te.tunnel_id.len() != 32 { + return false; + } + let mut tunnel_id = [0u8; 32]; + tunnel_id.copy_from_slice(&te.tunnel_id); + let mut tunnel_paths = std::collections::HashMap::new(); + for tp in &te.paths { + if tp.destination_hash.len() == 16 { + let mut dest = [0u8; 16]; + dest.copy_from_slice(&tp.destination_hash); + tunnel_paths.insert( + dest, + crate::tunnel::TunnelPath { + timestamp: tp.timestamp, + hops: tp.hops, + expires: tp.expires, + random_blobs: vec![], + }, + ); + } + } + let entry = crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: id, + tunnel_paths, + expires: te.expires, + }; + self.tunnel_table.insert(entry); + promoted += 1; + false + }); + if promoted > 0 { + debug!( + interface_id = id, + name = %name, + promoted, + "rebound persisted tunnel entries to live interface" + ); + } + } + + // Path waiters that were registered before the rebind can now fire. + let loaded_dests: Vec<[u8; 16]> = self + .path_waiters + .keys() + .filter(|dest| self.path_table.has_path(dest)) + .copied() + .collect(); + for dest in loaded_dests { + self.fire_path_waiters(&dest); + } + } +} diff --git a/crates/rns-transport/src/actor/rpc.rs b/crates/rns-transport/src/actor/rpc.rs new file mode 100644 index 0000000..7fbc540 --- /dev/null +++ b/crates/rns-transport/src/actor/rpc.rs @@ -0,0 +1,410 @@ +use super::*; + +impl TransportActor { + pub(super) fn handle_query( + &mut self, + query: crate::messages::TransportQuery, + ) -> crate::messages::TransportQueryResponse { + use crate::messages::*; + match query { + TransportQuery::GetPathTable => { + let entries: Vec = self + .path_table + .iter() + .map(|(hash, entry)| { + let iface_name = self + .interfaces + .get(&entry.interface_id) + .map(|e| e.name.clone()) + .unwrap_or_else(|| format!("interface_{}", entry.interface_id)); + PathTableRpcEntry { + hash: hash.into_bytes(), + timestamp: entry.timestamp, + via: entry.next_hop, + hops: entry.hops, + expires: entry.expires, + interface: iface_name, + } + }) + .collect(); + TransportQueryResponse::PathTable(entries) + } + TransportQuery::GetInterfaceStats => { + let stats: Vec = self + .interfaces + .iter() + .map(|(&iface_id, entry)| { + let online = entry + .online + .as_ref() + .map(|o| o.load(std::sync::atomic::Ordering::Relaxed)) + .unwrap_or(true); + let rx_bytes = entry + .rxb + .as_ref() + .map(|c| c.load(std::sync::atomic::Ordering::Relaxed)) + .unwrap_or(0); + let tx_bytes = entry + .txb + .as_ref() + .map(|c| c.load(std::sync::atomic::Ordering::Relaxed)) + .unwrap_or(0); + InterfaceStatRpcEntry { + id: iface_id, + name: entry.name.clone(), + rx_bytes, + tx_bytes, + rx_rate: 0, + tx_rate: 0, + online, + bitrate: entry.bitrate, + mtu: entry.mtu, + mode: format!("{:?}", entry.mode), + role: entry.role.as_str().to_string(), + announce_queue: Some(entry.announce_queue.len() as u64), + held_announces: entry.ingress.held_count() as u64, + incoming_announce_frequency: entry + .ingress + .incoming_announce_frequency(), + outgoing_announce_frequency: 0.0, + clients: None, + announce_rate_target: entry.announce_rate_target, + announce_rate_grace: entry.announce_rate_grace, + announce_rate_penalty: entry.announce_rate_penalty, + announce_cap: entry.announce_cap, + ifac_size: entry.ifac_size, + tx_drops: entry.tx_drops.load(std::sync::atomic::Ordering::Relaxed), + } + }) + .collect(); + TransportQueryResponse::InterfaceStats(stats) + } + TransportQuery::GetRateTable => { + let entries: Vec = self + .rate_table + .iter() + .map(|(hash, entry)| RateTableRpcEntry { + hash: hash.into_bytes(), + rate: entry.rate, + last: entry.last, + rate_violations: entry.violations, + blocked_until: entry.blocked_until, + timestamps: entry.timestamps.clone(), + }) + .collect(); + TransportQueryResponse::RateTable(entries) + } + TransportQuery::GetLinkCount => { + TransportQueryResponse::IntResult(self.link_table.len() as i64) + } + TransportQuery::GetRecentAnnounces => { + let mut entries: Vec = self + .recent_announces + .values() + .map(|a| AnnounceRpcEntry { + dest_hash: a.dest_hash, + hops: a.hops, + app_data: a.app_data.clone(), + timestamp: a.timestamp, + public_key: a.public_key, + ratchet: a.ratchet, + retained: a.retained, + }) + .collect(); + // HashMap iteration order is unspecified; sort newest-first + // so the wire response is deterministic for consumers that + // may key off ordering. + entries.sort_by(|a, b| { + b.timestamp + .partial_cmp(&a.timestamp) + .unwrap_or(std::cmp::Ordering::Equal) + }); + TransportQueryResponse::Announces(entries) + } + TransportQuery::GetNextHop { dest } => { + let next_hop = self.path_table.get(&dest).and_then(|e| e.next_hop); + TransportQueryResponse::HashResult(next_hop) + } + TransportQuery::GetNextHopIfName { dest } => { + let name = self + .path_table + .get(&dest) + .and_then(|e| self.interfaces.get(&e.interface_id).map(|i| i.name.clone())); + TransportQueryResponse::StringResult(name) + } + TransportQuery::GetPacketRssi { packet_hash } => TransportQueryResponse::FloatResult( + self.packet_metrics + .get(&packet_hash) + .and_then(|m| m.rssi) + .map(|v| v as f64), + ), + TransportQuery::GetPacketSnr { packet_hash } => TransportQueryResponse::FloatResult( + self.packet_metrics + .get(&packet_hash) + .and_then(|m| m.snr) + .map(|v| v as f64), + ), + TransportQuery::GetPacketQ { packet_hash } => TransportQueryResponse::FloatResult( + self.packet_metrics + .get(&packet_hash) + .and_then(|m| m.q) + .map(|v| v as f64), + ), + TransportQuery::DropPath { dest } => { + // expire() forces immediate cull — plain `remove` would leave + // observers racing against the next maintenance tick. + self.path_table.expire(&dest); + self.state_dirty = true; + TransportQueryResponse::Ok + } + TransportQuery::DropAnnounceQueues => { + for entry in self.interfaces.values_mut() { + entry.announce_queue.clear(); + } + TransportQueryResponse::Ok + } + TransportQuery::GetBlackholedIdentities => { + let entries: Vec = self + .blackhole_table + .iter_entries() + .map(|(hash, entry)| BlackholeRpcEntry { + identity_hash: hash.into_bytes(), + source: entry + .source + .map(|source| source.into_bytes()) + .or(self.transport_identity_hash), + created: entry.created, + ttl: entry.ttl, + reason: entry.reason, + reason_label: entry.reason_label.clone(), + }) + .collect(); + TransportQueryResponse::BlackholeList(entries) + } + TransportQuery::BlackholeIdentity { + hash, + ttl, + reason, + reason_label, + } => { + self.blackhole_table + .add_with_reason_label(hash, ttl, reason, reason_label); + self.state_dirty = true; + TransportQueryResponse::Ok + } + TransportQuery::UnblackholeIdentity { hash } => { + let removed = self.blackhole_table.remove(&hash); + if removed { + self.state_dirty = true; + } + TransportQueryResponse::BoolResult(removed) + } + TransportQuery::IsBlackholed { hash } => { + TransportQueryResponse::BoolResult(self.blackhole_table.is_blackholed(&hash)) + } + TransportQuery::ClearSystemBlackholes => { + let cleared = self.blackhole_table.clear_system_entries(); + if cleared > 0 { + self.state_dirty = true; + } + TransportQueryResponse::IntResult(cleared as i64) + } + TransportQuery::BuildBlackholeManifest { publisher } => { + match crate::discovery::build_local_manifest( + &self.blackhole_table, + publisher.into(), + ) { + Ok(payload) => TransportQueryResponse::Data(payload), + Err(e) => TransportQueryResponse::Error(e.to_string()), + } + } + TransportQuery::ApplyBlackholeManifest { payload } => { + match crate::discovery::decode_manifest(&payload) { + Ok(manifest) => { + let applied = crate::discovery::apply_manifest( + &mut self.blackhole_table, + &manifest, + now_f64(), + ); + if applied > 0 { + self.state_dirty = true; + } + TransportQueryResponse::IntResult(applied as i64) + } + Err(e) => TransportQueryResponse::Error(e.to_string()), + } + } + TransportQuery::RemoteStatus { include_link_count } => { + // Wire shape: `(interface_stats,)` or `(interface_stats, link_count)` — + // a tuple so the msgpack decoder on the other side sees a fixed arity. + let stats: Vec> = self + .interfaces + .values() + .map(|entry| { + let online = entry + .online + .as_ref() + .map(|o| o.load(std::sync::atomic::Ordering::Relaxed)) + .unwrap_or(true); + let rx = entry + .rxb + .as_ref() + .map(|c| c.load(std::sync::atomic::Ordering::Relaxed)) + .unwrap_or(0); + let tx = entry + .txb + .as_ref() + .map(|c| c.load(std::sync::atomic::Ordering::Relaxed)) + .unwrap_or(0); + vec![ + ("name".to_string(), entry.name.clone()), + ("online".to_string(), online.to_string()), + ("rxb".to_string(), rx.to_string()), + ("txb".to_string(), tx.to_string()), + ("bitrate".to_string(), entry.bitrate.to_string()), + ] + }) + .collect(); + let response = if include_link_count { + let link_count = self.link_table.len(); + rmp_serde::to_vec(&(stats, link_count)).unwrap_or_default() + } else { + rmp_serde::to_vec(&(stats,)).unwrap_or_default() + }; + TransportQueryResponse::Data(response) + } + TransportQuery::RemotePath { + command: _, + destination, + max_hops, + } => { + let entries: Vec<_> = self + .path_table + .iter() + .filter(|(hash, _)| { + if let Some(dest) = destination { + *hash.as_bytes() == dest + } else { + true + } + }) + .filter(|(_, entry)| { + if let Some(max) = max_hops { + entry.hops <= max + } else { + true + } + }) + .map(|(hash, entry)| { + let iface = self + .interfaces + .get(&entry.interface_id) + .map(|e| e.name.clone()) + .unwrap_or_default(); + ( + hex::encode(hash.as_bytes()), + entry.hops, + entry.timestamp, + iface, + ) + }) + .collect(); + let response = rmp_serde::to_vec(&entries).unwrap_or_default(); + TransportQueryResponse::Data(response) + } + TransportQuery::HaltInterface { id } => { + if let Some(entry) = self.interfaces.get_mut(&id) { + if let Some(ref online) = entry.online { + online.store(false, std::sync::atomic::Ordering::Relaxed); + } + debug!(id, "interface halted via RPC"); + TransportQueryResponse::Ok + } else { + TransportQueryResponse::Error(format!("interface {} not found", id)) + } + } + TransportQuery::ResumeInterface { id } => { + if let Some(entry) = self.interfaces.get_mut(&id) { + if let Some(ref online) = entry.online { + online.store(true, std::sync::atomic::Ordering::Relaxed); + } + debug!(id, "interface resumed via RPC"); + TransportQueryResponse::Ok + } else { + TransportQueryResponse::Error(format!("interface {} not found", id)) + } + } + TransportQuery::DropAllVia { next_hop } => { + let dropped = self.path_table.drop_all_via_next_hop(&next_hop); + debug!(next_hop = %hex::encode(next_hop), dropped, "dropped paths via next hop"); + TransportQueryResponse::IntResult(dropped as i64) + } + TransportQuery::GetNextHopBitrate { dest } => { + let bitrate = self + .path_table + .get(&dest) + .and_then(|e| self.interfaces.get(&e.interface_id)) + .map(|iface| iface.bitrate as f64); + TransportQueryResponse::FloatResult(bitrate) + } + TransportQuery::GetNextHopInterfaceId { dest } => { + let id = self.path_table.get(&dest).map(|e| e.interface_id as i64); + TransportQueryResponse::IntResult(id.unwrap_or(-1)) + } + TransportQuery::FirstHopTimeout { dest } => { + let timeout = self + .path_table + .get(&dest) + .and_then(|e| self.interfaces.get(&e.interface_id)) + .map(|iface| { + let per_byte_latency = 8.0 / iface.bitrate as f64; + rns_wire::constants::MTU as f64 * per_byte_latency + + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT + }) + .unwrap_or(rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT); + TransportQueryResponse::FloatResult(Some(timeout)) + } + TransportQuery::ExtraLinkProofTimeout { interface_id } => { + let timeout = self + .interfaces + .get(&interface_id) + .map(|iface| { + let per_byte_latency = 8.0 / iface.bitrate as f64; + rns_wire::constants::MTU as f64 * per_byte_latency + }) + .unwrap_or(0.0); + TransportQueryResponse::FloatResult(Some(timeout)) + } + TransportQuery::SetPathState { dest, state } => { + if self.path_table.has_path(&dest) { + self.path_table.set_state(dest, state); + TransportQueryResponse::BoolResult(true) + } else { + TransportQueryResponse::BoolResult(false) + } + } + TransportQuery::GetPathState { dest } => { + let state = self.path_table.get_state(&dest); + TransportQueryResponse::PathStateResult(state) + } + TransportQuery::PathIsUnresponsive { dest } => { + let is_unresponsive = + self.path_table.get_state(&dest) == crate::constants::PathState::Unresponsive; + TransportQueryResponse::BoolResult(is_unresponsive) + } + TransportQuery::RetainDestination { dest } => { + TransportQueryResponse::BoolResult(self.retain_destination(&dest)) + } + TransportQuery::UseDestination { dest } => { + TransportQueryResponse::BoolResult(self.use_destination(&dest)) + } + TransportQuery::UnretainDestination { dest } => { + TransportQueryResponse::BoolResult(self.unretain_destination(&dest)) + } + TransportQuery::CleanKnownDestinations => { + self.cleanup_known_destinations(crate::actor::now_f64()); + TransportQueryResponse::IntResult(self.recent_announces.len() as i64) + } + } + } +} diff --git a/crates/rns-transport/src/announce.rs b/crates/rns-transport/src/announce.rs new file mode 100644 index 0000000..b994fa3 --- /dev/null +++ b/crates/rns-transport/src/announce.rs @@ -0,0 +1,161 @@ +use std::collections::HashMap; + +use crate::messages::InterfaceId; +use rns_wire::types::DestHash; + +/// Rebroadcast state for a single announce. +#[derive(Debug, Clone)] +pub struct AnnounceEntry { + /// Receive time (Unix seconds). + pub timestamp: f64, + /// Next retransmit time (Unix seconds). + pub retransmit_timeout: f64, + pub retries: u8, + /// Transport ID or destination hash that delivered this announce to us. + pub received_from: [u8; 16], + /// Hop count as observed on receipt. + pub hops: u8, + /// Outbound packet bytes with the hop count already incremented. + pub packet_raw: Vec, + /// Count of duplicate rebroadcasts heard from neighbours — used to suppress flooding. + pub local_rebroadcasts: u32, + pub block_rebroadcast: bool, + /// Restrict rebroadcast to one interface; `None` broadcasts on all. + pub attached_interface: Option, + /// Interface the announce arrived on; excluded from rebroadcast to avoid echo. + pub source_interface: Option, +} + +/// Table of pending announce rebroadcasts, keyed by destination hash. +pub struct AnnounceTable { + entries: HashMap, +} + +impl AnnounceTable { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + } + } + + pub fn insert(&mut self, dest_hash: impl Into, entry: AnnounceEntry) { + self.entries.insert(dest_hash.into(), entry); + } + + pub fn get(&self, dest_hash: &[u8; 16]) -> Option<&AnnounceEntry> { + self.entries.get(dest_hash) + } + + pub fn get_mut(&mut self, dest_hash: &[u8; 16]) -> Option<&mut AnnounceEntry> { + self.entries.get_mut(dest_hash) + } + + pub fn remove(&mut self, dest_hash: &[u8; 16]) -> Option { + self.entries.remove(dest_hash) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Destination hashes whose retransmit_timeout has elapsed and whose + /// rebroadcast is not blocked. + pub fn due_for_retransmit(&self, now: f64) -> Vec { + self.entries + .iter() + .filter(|(_, entry)| { + (!entry.block_rebroadcast || entry.attached_interface.is_some()) + && now >= entry.retransmit_timeout + }) + .map(|(hash, _)| *hash) + .collect() + } + + pub fn iter(&self) -> impl Iterator { + self.entries.iter() + } + + /// Remove entries whose retry count exceeds `max_retries`; returns the number dropped. + pub fn cull_exhausted(&mut self, max_retries: u8) -> usize { + let before = self.entries.len(); + self.entries.retain(|_, entry| entry.retries <= max_retries); + before - self.entries.len() + } +} + +impl Default for AnnounceTable { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_announce_table_basic() { + let mut table = AnnounceTable::new(); + let hash = [0xAA; 16]; + table.insert( + hash, + AnnounceEntry { + timestamp: 1000.0, + retransmit_timeout: 1005.0, + retries: 0, + received_from: [0xBB; 16], + hops: 2, + packet_raw: vec![0x01, 0x02], + local_rebroadcasts: 0, + block_rebroadcast: false, + attached_interface: None, + source_interface: None, + }, + ); + assert_eq!(table.len(), 1); + assert!(table.get(&hash).is_some()); + } + + #[test] + fn test_due_for_retransmit() { + let mut table = AnnounceTable::new(); + table.insert( + [0x01; 16], + AnnounceEntry { + timestamp: 1000.0, + retransmit_timeout: 1005.0, + retries: 0, + received_from: [0; 16], + hops: 0, + packet_raw: vec![], + local_rebroadcasts: 0, + block_rebroadcast: false, + attached_interface: None, + source_interface: None, + }, + ); + table.insert( + [0x02; 16], + AnnounceEntry { + timestamp: 1000.0, + retransmit_timeout: 1010.0, + retries: 0, + received_from: [0; 16], + hops: 0, + packet_raw: vec![], + local_rebroadcasts: 0, + block_rebroadcast: false, + attached_interface: None, + source_interface: None, + }, + ); + + let due = table.due_for_retransmit(1006.0); + assert_eq!(due.len(), 1); + assert_eq!(due[0], DestHash::from([0x01; 16])); + } +} diff --git a/crates/rns-transport/src/await_path.rs b/crates/rns-transport/src/await_path.rs new file mode 100644 index 0000000..8aab49a --- /dev/null +++ b/crates/rns-transport/src/await_path.rs @@ -0,0 +1,131 @@ +//! Wait for a destination's path to be learned (or time out). +//! +//! Mirrors Python `Transport.await_path(destination_hash, timeout=None)` +//! (RNS/Transport.py:2524). The helper sends an [`AwaitPath`] actor +//! message and races the oneshot reply against a caller-supplied timeout. +//! +//! [`AwaitPath`]: crate::messages::TransportMessage::AwaitPath + +use std::time::Duration; +use thiserror::Error; +use tokio::sync::{mpsc, oneshot}; + +use crate::messages::TransportMessage; + +/// Error returned by [`await_path`] when the path cannot be resolved. +#[derive(Debug, Error, PartialEq)] +pub enum AwaitPathError { + /// The transport actor's receive channel closed before we could + /// submit the request — the actor has shut down. + #[error("transport actor is not running")] + TransportDown, + /// The caller's timeout fired before the actor answered, or the + /// actor's internal 15s sweep expired the waiter first (returns + /// `Ok(false)` on the reply channel). + #[error("timed out waiting for path")] + Timeout, +} + +/// Wait up to `timeout` for the transport actor to resolve (or already +/// know) a path to `destination_hash`. +/// +/// Returns `Ok(())` as soon as the actor confirms the path exists. A +/// dropped reply sender without a preceding `true` is indistinguishable +/// from a timeout, so both surface as `Err(Timeout)`. +pub async fn await_path( + tx: &mpsc::Sender, + destination_hash: [u8; 16], + timeout: Duration, +) -> Result<(), AwaitPathError> { + let (reply_tx, reply_rx) = oneshot::channel(); + tx.send(TransportMessage::AwaitPath { + dest: destination_hash, + reply: reply_tx, + }) + .await + .map_err(|_| AwaitPathError::TransportDown)?; + + match tokio::time::timeout(timeout, reply_rx).await { + Ok(Ok(true)) => Ok(()), + // Actor responded `false` → its own internal timer expired. + Ok(Ok(false)) => Err(AwaitPathError::Timeout), + // Actor dropped the reply sender without replying — treat as timeout. + Ok(Err(_)) => Err(AwaitPathError::Timeout), + // Caller timeout fired first. + Err(_) => Err(AwaitPathError::Timeout), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::sync::mpsc; + + #[tokio::test] + async fn resolves_when_actor_replies_true() { + let (tx, mut rx) = mpsc::channel::(4); + tokio::spawn(async move { + match rx.recv().await { + Some(TransportMessage::AwaitPath { dest: _, reply }) => { + let _ = reply.send(true); + } + other => panic!("unexpected message: {:?}", other), + } + }); + + let out = await_path(&tx, [0x11; 16], Duration::from_secs(1)).await; + assert!(out.is_ok()); + } + + #[tokio::test] + async fn timeouts_when_actor_replies_false() { + let (tx, mut rx) = mpsc::channel::(4); + tokio::spawn(async move { + if let Some(TransportMessage::AwaitPath { reply, .. }) = rx.recv().await { + let _ = reply.send(false); + } + }); + + let out = await_path(&tx, [0x22; 16], Duration::from_secs(1)).await; + assert_eq!(out, Err(AwaitPathError::Timeout)); + } + + #[tokio::test] + async fn timeouts_when_caller_deadline_fires() { + let (tx, mut rx) = mpsc::channel::(4); + // Drain the message but never reply — caller's tokio::time::timeout + // must fire. + tokio::spawn(async move { + let _ = rx.recv().await; + // Hold the reply sender forever by moving it into a never-ending + // task. + std::future::pending::<()>().await; + }); + + let out = await_path(&tx, [0x33; 16], Duration::from_millis(50)).await; + assert_eq!(out, Err(AwaitPathError::Timeout)); + } + + #[tokio::test] + async fn transport_down_when_channel_closed() { + let (tx, rx) = mpsc::channel::(1); + drop(rx); + let out = await_path(&tx, [0x44; 16], Duration::from_millis(50)).await; + assert_eq!(out, Err(AwaitPathError::TransportDown)); + } + + #[tokio::test] + async fn treats_dropped_reply_sender_as_timeout() { + let (tx, mut rx) = mpsc::channel::(4); + tokio::spawn(async move { + // Consume the AwaitPath message, then drop the reply sender + // without sending anything. + if let Some(TransportMessage::AwaitPath { reply, .. }) = rx.recv().await { + drop(reply); + } + }); + + let out = await_path(&tx, [0x55; 16], Duration::from_millis(200)).await; + assert_eq!(out, Err(AwaitPathError::Timeout)); + } +} diff --git a/crates/rns-transport/src/blackhole.rs b/crates/rns-transport/src/blackhole.rs new file mode 100644 index 0000000..3adf7aa --- /dev/null +++ b/crates/rns-transport/src/blackhole.rs @@ -0,0 +1,293 @@ +use std::collections::HashMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rns_wire::types::IdentityHash; +use serde::{Deserialize, Serialize}; + +/// Why an identity ended up in the blackhole table. `Manual` is an operator +/// add; the other variants are system-populated. UIs distinguish operator +/// blocks from automatic defences. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +pub enum BlackholeReason { + #[default] + Manual, + Malformed, + RateLimit, + ProtocolViolation, +} + +impl BlackholeReason { + /// Stable string identifier for RPC/wire payloads. + pub fn as_str(&self) -> &'static str { + match self { + Self::Manual => "manual", + Self::Malformed => "malformed", + Self::RateLimit => "rate_limit", + Self::ProtocolViolation => "protocol_violation", + } + } + + /// Parse the stable identifier (case-insensitive). Unknown values fall back + /// to `Manual`; never silently promote to a system reason that would hide + /// the entry from an operator view. + pub fn parse(s: &str) -> Self { + match s.to_ascii_lowercase().as_str() { + "malformed" => Self::Malformed, + "rate_limit" | "ratelimit" => Self::RateLimit, + "protocol_violation" | "protocolviolation" => Self::ProtocolViolation, + _ => Self::Manual, + } + } +} + +#[derive(Debug, Clone)] +pub struct BlackholeEntry { + /// Insertion time (Unix seconds). + pub created: f64, + /// Lifetime relative to `created`; `None` is permanent. + pub ttl: Option, + pub reason: BlackholeReason, + /// Original operator/source reason string when it is more specific than + /// the internal reason enum. Python preserves arbitrary reason labels. + pub reason_label: Option, + /// Identity hash of the publisher that issued this entry; `None` if local. + /// The distributed blackhole updater uses it to filter locally-issued + /// entries for publication and to key remote entries on ingest. + pub source: Option, +} + +impl BlackholeEntry { + pub fn reason_str(&self) -> &str { + self.reason_label + .as_deref() + .unwrap_or_else(|| self.reason.as_str()) + } +} + +pub struct BlackholeTable { + entries: HashMap, +} + +impl BlackholeTable { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + } + } + + /// Add a manually-issued blackhole entry. System-populated drops should + /// use [`BlackholeTable::add_with_reason`]. + pub fn add(&mut self, identity_hash: impl Into, ttl: Option) { + self.add_with_reason(identity_hash, ttl, BlackholeReason::Manual); + } + + pub fn add_with_reason( + &mut self, + identity_hash: impl Into, + ttl: Option, + reason: BlackholeReason, + ) { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + self.entries.insert( + identity_hash.into(), + BlackholeEntry { + created: now, + ttl, + reason, + reason_label: None, + source: None, + }, + ); + } + + pub fn add_with_reason_label( + &mut self, + identity_hash: impl Into, + ttl: Option, + reason: BlackholeReason, + reason_label: Option, + ) { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + self.entries.insert( + identity_hash.into(), + BlackholeEntry { + created: now, + ttl, + reason, + reason_label, + source: None, + }, + ); + } + + /// Add an entry that was pulled from a remote blackhole source. The + /// `source` field is retained so local publication filters it out of + /// our own manifest (parity with Python `Transport.persist_blackhole` + /// which only persists entries whose source matches the local + /// identity, Discovery.py:3253-3258). + pub fn add_from_source( + &mut self, + identity_hash: impl Into, + ttl: Option, + reason: BlackholeReason, + source: IdentityHash, + created: f64, + ) { + self.entries.insert( + identity_hash.into(), + BlackholeEntry { + created, + ttl, + reason, + reason_label: None, + source: Some(source), + }, + ); + } + + /// Insert a pre-built entry, preserving its `created`/`ttl`/`reason`. + /// Used when rehydrating the table from persistence. + pub fn insert_entry(&mut self, identity_hash: impl Into, entry: BlackholeEntry) { + self.entries.insert(identity_hash.into(), entry); + } + + pub fn is_blackholed(&self, identity_hash: &[u8; 16]) -> bool { + match self.entries.get(identity_hash) { + Some(entry) => { + if let Some(ttl) = entry.ttl { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + now - entry.created < ttl + } else { + true + } + } + None => false, + } + } + + /// Remove an entry; returns `true` if one was present. + pub fn remove(&mut self, identity_hash: &[u8; 16]) -> bool { + self.entries.remove(identity_hash).is_some() + } + + /// Drop entries whose TTL has elapsed; returns the number removed. + pub fn cull_expired(&mut self) -> usize { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let before = self.entries.len(); + self.entries + .retain(|_, entry| entry.ttl.is_none_or(|ttl| now - entry.created < ttl)); + before - self.entries.len() + } + + /// Drop every entry whose reason is not `Manual`; returns the number removed. + pub fn clear_system_entries(&mut self) -> usize { + let before = self.entries.len(); + self.entries + .retain(|_, entry| matches!(entry.reason, BlackholeReason::Manual)); + before - self.entries.len() + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.entries.keys() + } + + pub fn iter_entries(&self) -> impl Iterator { + self.entries.iter() + } +} + +impl Default for BlackholeTable { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_blackhole_permanent() { + let mut bh = BlackholeTable::new(); + let hash = [0xAA; 16]; + bh.add(hash, None); + assert!(bh.is_blackholed(&hash)); + } + + #[test] + fn test_not_blackholed() { + let bh = BlackholeTable::new(); + assert!(!bh.is_blackholed(&[0xBB; 16])); + } + + #[test] + fn test_remove() { + let mut bh = BlackholeTable::new(); + let hash = [0xAA; 16]; + bh.add(hash, None); + assert!(bh.remove(&hash)); + assert!(!bh.is_blackholed(&hash)); + assert!(!bh.remove(&hash)); + } + + #[test] + fn test_default_reason_is_manual() { + let mut bh = BlackholeTable::new(); + let hash = [0xCC; 16]; + bh.add(hash, None); + let entry = bh.iter_entries().next().unwrap().1; + assert_eq!(entry.reason, BlackholeReason::Manual); + } + + #[test] + fn test_clear_system_entries_keeps_manual() { + let mut bh = BlackholeTable::new(); + bh.add_with_reason([0xAA; 16], None, BlackholeReason::Manual); + bh.add_with_reason([0xBB; 16], None, BlackholeReason::Malformed); + bh.add_with_reason([0xCC; 16], None, BlackholeReason::RateLimit); + bh.add_with_reason([0xDD; 16], None, BlackholeReason::ProtocolViolation); + + let cleared = bh.clear_system_entries(); + assert_eq!(cleared, 3); + assert!(bh.is_blackholed(&[0xAA; 16])); + assert!(!bh.is_blackholed(&[0xBB; 16])); + assert!(!bh.is_blackholed(&[0xCC; 16])); + assert!(!bh.is_blackholed(&[0xDD; 16])); + } + + #[test] + fn test_reason_round_trip() { + for r in [ + BlackholeReason::Manual, + BlackholeReason::Malformed, + BlackholeReason::RateLimit, + BlackholeReason::ProtocolViolation, + ] { + assert_eq!(BlackholeReason::parse(r.as_str()), r); + } + assert_eq!(BlackholeReason::parse("bogus"), BlackholeReason::Manual); + } +} diff --git a/crates/rns-transport/src/constants.rs b/crates/rns-transport/src/constants.rs new file mode 100644 index 0000000..0cdc775 --- /dev/null +++ b/crates/rns-transport/src/constants.rs @@ -0,0 +1,247 @@ +/// Maximum hop count. Announces and forwarded packets exceeding this are +/// dropped at the inbound boundary. Mirrors Python `Transport.PATHFINDER_M`. +pub const PATHFINDER_M: u8 = 128; + +/// Number of retransmit retries for announces. +pub const PATHFINDER_R: u8 = 1; + +/// Grace period (seconds) before announce retry. +pub const PATHFINDER_G: f64 = 5.0; + +/// Random window for announce rebroadcast jitter. +pub const PATHFINDER_RW: f64 = 0.5; + +/// Default path expiry (7 days, in seconds). +pub const PATHFINDER_E: u64 = 604_800; + +/// Access Point path expiry (24 hours). +pub const AP_PATH_TIME: u64 = 86_400; + +/// Roaming path expiry (6 hours). +pub const ROAMING_PATH_TIME: u64 = 21_600; + +/// Default destination timeout (7 days). Matches Python +/// `Transport.DESTINATION_TIMEOUT`. Drives both `path_table` and +/// `recent_announces` eviction. +pub const DESTINATION_TIMEOUT: u64 = 604_800; + +/// Transport link-table timeout for validated links (15 min). +/// Equals `Link::STALE_TIME (720s) * 1.25`. +pub const LINK_TIMEOUT: f64 = 900.0; + +/// Reverse table entry timeout (8 minutes). +pub const REVERSE_TIMEOUT: u64 = 480; + +/// Maximum packet receipts tracked. +pub const MAX_RECEIPTS: usize = 1024; + +/// Rate timestamps per destination. +pub const MAX_RATE_TIMESTAMPS: usize = 16; + +/// Random blobs saved to disk per destination. +pub const PERSIST_RANDOM_BLOBS: usize = 32; + +/// Random blobs kept in memory per destination. +pub const MAX_RANDOM_BLOBS: usize = 64; + +/// Max local rebroadcasts before stopping. +pub const LOCAL_REBROADCASTS_MAX: u32 = 2; + +/// Path request timeout (seconds). +pub const PATH_REQUEST_TIMEOUT: f64 = 15.0; + +/// Duplicate inbound path request tag retention (seconds). +pub const PATH_REQUEST_GATE_TIMEOUT: f64 = 120.0; + +/// Grace before path response (seconds). +pub const PATH_REQUEST_GRACE: f64 = 0.4; + +/// Extra grace for roaming interfaces (seconds). +pub const PATH_REQUEST_RG: f64 = 1.5; + +/// Minimum interval between path requests (seconds). +pub const PATH_REQUEST_MI: f64 = 20.0; + +/// Maximum packet hashes before rotation. Set to 2M with rotation at +/// `maxsize/2` so effective history matches Python's 1M-no-rotation window. +pub const HASHLIST_MAXSIZE: usize = 2_000_000; + +/// Job loop period (250ms). +pub const JOB_INTERVAL_MS: u64 = 250; + +/// Job loop period in background mode (2s). Inbound packet processing is +/// unaffected — it runs on the channel branch at full speed. +pub const JOB_INTERVAL_BG_MS: u64 = 2000; + +/// Cadence at which `on_tick` flushes routing-state files (path_table, +/// announce_cache, blackhole, tunnel_table) when dirty. Hashlist is excluded +/// (multi-MB on busy hubs); it saves on shutdown + foreground→background. +pub const STATE_SAVE_INTERVAL_SECS: f64 = 10.0; + +/// Link table check interval. +pub const LINKS_CHECK_INTERVAL: f64 = 1.0; + +/// Receipt timeout check interval. +pub const RECEIPTS_CHECK_INTERVAL: f64 = 1.0; + +/// Announce rebroadcast check interval. +pub const ANNOUNCES_CHECK_INTERVAL: f64 = 1.0; + +/// Pending path request cleanup interval. +pub const PENDING_PRS_CHECK_INTERVAL: f64 = 30.0; + +/// Cache cleanup interval (5 minutes). +pub const CACHE_CLEAN_INTERVAL: f64 = 300.0; + +/// Table culling interval. +pub const TABLES_CULL_INTERVAL: f64 = 5.0; + +/// Interface job processing interval. +pub const INTERFACE_JOBS_INTERVAL: f64 = 5.0; + +/// Management announce interval (2 hours). +pub const MGMT_ANNOUNCE_INTERVAL: f64 = 7200.0; + +/// Blackhole expiry check interval. +pub const BLACKHOLE_CHECK_INTERVAL: f64 = 60.0; + +/// Announce bandwidth cap as a fraction of interface bitrate (2%). +/// +/// The Python reference stores `ANNOUNCE_CAP = 2` and divides by 100 at use +/// sites; we store the fraction directly. UIs may show the percentage. +pub const ANNOUNCE_CAP: f64 = 0.02; + +/// Maximum ingress-limited announces to hold per interface. +/// Matches Python `Interface.MAX_HELD_ANNOUNCES = 256`. +pub const MAX_HELD_ANNOUNCES: usize = 256; + +/// Held announce release interval (seconds). +/// Matches Python 1.1.6 `Interface.IC_HELD_RELEASE_INTERVAL = 2`. +pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0; + +/// Incoming announce frequency window samples. +/// Matches Python 1.1.6 `Interface.IA_FREQ_SAMPLES = 128`. +pub const IA_FREQ_SAMPLES: usize = 128; + +/// Outgoing announce frequency window samples. +/// Matches Python 1.1.6 `Interface.OA_FREQ_SAMPLES = 128`. +pub const OA_FREQ_SAMPLES: usize = 128; + +/// Minimum samples required before frequency is considered defined. +/// Matches Python 1.1.6 `Interface.IC_DEQUE_MIN_SAMPLE = 32`. +pub const IC_DEQUE_MIN_SAMPLE: usize = 32; + +/// Duration interface is treated as "new" (seconds). +/// Matches Python `Interface.IC_NEW_TIME = 2*60*60`. +pub const IC_NEW_TIME: f64 = 7200.0; + +/// Burst threshold for new interfaces (announces/sec). +/// Matches Python 1.1.6 `Interface.IC_BURST_FREQ_NEW = 6`. +pub const IC_BURST_FREQ_NEW: f64 = 6.0; + +/// Burst threshold for established interfaces (announces/sec). +/// Matches Python 1.1.6 `Interface.IC_BURST_FREQ = 35`. +pub const IC_BURST_FREQ: f64 = 35.0; + +/// Burst detection active duration (seconds). +/// Matches Python `Interface.IC_BURST_HOLD = 1*60`. +pub const IC_BURST_HOLD: f64 = 60.0; + +/// Burst penalty delay (seconds). +/// Matches Python 1.1.6 `Interface.IC_BURST_PENALTY = 15`. +pub const IC_BURST_PENALTY: f64 = 15.0; + +/// Tunnel timeout (8 hours, in seconds). +/// Matches Python 1.1.6 `Transport.TUNNEL_TIMEOUT = 60*60*8`. +pub const TUNNEL_TIMEOUT: u64 = 28_800; + +/// Tunnel path timeout (8 hours, in seconds). +/// Matches Python 1.1.6 `Transport.TUNNEL_PATH_TIMEOUT = 60*60*8`. +pub const TUNNEL_PATH_TIMEOUT: u64 = 28_800; + +/// Announce queue processing interval (seconds). +pub const ANNOUNCE_QUEUE_INTERVAL: f64 = 1.0; + +/// Local client cache max size. +pub const LOCAL_CLIENT_CACHE_MAXSIZE: usize = 512; + +/// Maximum lifetime for queued announces (24 hours, in seconds). +/// Matches Python `Reticulum.QUEUED_ANNOUNCE_LIFE = 60*60*24`. +pub const QUEUED_ANNOUNCE_LIFE: f64 = 86_400.0; + +/// Maximum number of queued announces per interface. +/// Matches Python `Reticulum.MAX_QUEUED_ANNOUNCES = 16384`. +pub const MAX_QUEUED_ANNOUNCES: usize = 16_384; + +/// Startup grace period (seconds) before cache cleaning runs. +/// Allows interfaces to come online before pruning stale cache entries. +pub const STARTUP_GRACE_PERIOD: f64 = 3.0; + +/// Wire transport mode carried in the packet header. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum TransportMode { + Broadcast = 0x00, + Transport = 0x01, + Relay = 0x02, + Tunnel = 0x03, +} + +/// Reachability state recorded for a destination. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Reachability { + Unreachable = 0x00, + Direct = 0x01, + Transport = 0x02, +} + +/// Liveness state for a known path. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum PathState { + Unknown = 0x00, + Unresponsive = 0x01, + Responsive = 0x02, +} + +/// Configured operating mode for an interface. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InterfaceMode { + Full, + PointToPoint, + Gateway, + AccessPoint, + Roaming, + Boundary, +} + +/// Which directions an interface carries traffic in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InterfaceDirection { + pub inbound: bool, + pub outbound: bool, +} + +impl InterfaceDirection { + pub fn bidirectional() -> Self { + Self { + inbound: true, + outbound: true, + } + } + + pub fn inbound_only() -> Self { + Self { + inbound: true, + outbound: false, + } + } + + pub fn outbound_only() -> Self { + Self { + inbound: false, + outbound: true, + } + } +} diff --git a/crates/rns-transport/src/discovery/announcer.rs b/crates/rns-transport/src/discovery/announcer.rs new file mode 100644 index 0000000..2062718 --- /dev/null +++ b/crates/rns-transport/src/discovery/announcer.rs @@ -0,0 +1,564 @@ +//! Periodic discovery announce scheduler. Pure-data: `tick(now)` returns +//! one [`AnnounceRequest`] per due interface; the runtime owns the timer + +//! identity-signed emit. Memoises `(infohash, stamp)` per interface so an +//! unchanged info doesn't redo PoW. + +use std::collections::HashMap; +use std::sync::Arc; + +use tracing::{debug, trace}; + +use crate::messages::InterfaceId; + +use super::app_data::{self, DiscoveryInfo, Encoded}; +use super::constants::{ + ANNOUNCE_JOB_INTERVAL_SECS, DEFAULT_STAMP_VALUE, DISCOVERABLE_INTERFACE_TYPES, STAMP_SIZE, +}; +use super::stamper::DiscoveryStamper; + +/// Per-interface configuration that drives discovery announces. +#[derive(Debug, Clone)] +pub struct DiscoveryInterfaceConfig { + /// Interface type — must be in [`DISCOVERABLE_INTERFACE_TYPES`]. + pub interface_type: String, + pub discoverable: bool, + /// Name advertised in the announce. + pub name: String, + pub transport_enabled: bool, + /// Seconds between announces; defaults to [`ANNOUNCE_JOB_INTERVAL_SECS`]. + pub announce_interval_secs: u64, + /// Stamp target value required by the receiver; defaults to [`DEFAULT_STAMP_VALUE`]. + pub stamp_value: u8, + /// Endpoint address (IP / host / I2P b32) — optional. + pub reachable_on: Option, + /// TCP/Backbone bind port, if applicable. + pub port: Option, + /// IFAC virtual-network overlay (name / key). + pub ifac_netname: Option, + pub ifac_netkey: Option, + /// Radio-link parameters for RNode / KISS / Weave. + pub frequency: Option, + pub bandwidth: Option, + pub spreading_factor: Option, + pub coding_rate: Option, + pub modulation: Option, + pub channel: Option, + /// Geolocation (defaults to 0/0/0). + pub latitude: f64, + pub longitude: f64, + pub height: f64, + /// Set the `FLAG_ENCRYPTED` bit; caller supplies `encrypt` closure at + /// announce time via [`AnnounceRequest::assemble`]. + pub encrypt: bool, + /// Set the `FLAG_SIGNED` bit (independent of `encrypt`). + pub signed: bool, +} + +impl DiscoveryInterfaceConfig { + /// Minimal config: discoverable backbone interface with default + /// stamp + interval. + pub fn backbone(name: String, reachable_on: String, port: u16) -> Self { + Self { + interface_type: "BackboneInterface".into(), + discoverable: true, + name, + transport_enabled: true, + announce_interval_secs: ANNOUNCE_JOB_INTERVAL_SECS, + stamp_value: DEFAULT_STAMP_VALUE, + reachable_on: Some(reachable_on), + port: Some(port), + ifac_netname: None, + ifac_netkey: None, + frequency: None, + bandwidth: None, + spreading_factor: None, + coding_rate: None, + modulation: None, + channel: None, + latitude: 0.0, + longitude: 0.0, + height: 0.0, + encrypt: false, + signed: true, + } + } + + /// True iff `interface_type` is in [`DISCOVERABLE_INTERFACE_TYPES`]. + pub fn is_advertisable(&self) -> bool { + DISCOVERABLE_INTERFACE_TYPES + .iter() + .any(|t| *t == self.interface_type) + } +} + +/// Per-interface running state (last-announce timestamp + stamp cache). +#[derive(Debug, Clone)] +struct InterfaceAnnounceState { + config: DiscoveryInterfaceConfig, + transport_id: [u8; 16], + last_announce_at: f64, + /// Cached `(infohash, stamp)` pair so a repeat announce doesn't + /// redo proof-of-work when the info map is unchanged. + stamp_cache: Option<([u8; 32], Vec)>, +} + +/// One "interface wants to announce now" output from [`Announcer::tick`]. +#[derive(Debug, Clone)] +pub struct AnnounceRequest { + pub interface_id: InterfaceId, + /// Fully-assembled `app_data` bytes (flags || [encrypted] body). + pub app_data: Vec, + /// Stamp value actually achieved — useful for logging. + pub stamp_value: u8, +} + +/// Why an interface was skipped on a given tick. +#[derive(Debug, Clone, PartialEq)] +pub enum SkipReason { + /// `discoverable = false`. + NotDiscoverable, + /// Interface type not in [`DISCOVERABLE_INTERFACE_TYPES`]. + TypeNotAdvertisable, + /// Too soon after the last announce. + RateLimited { remaining_secs: u64 }, + /// Stamper refused to generate (LXStamper cancelled or missing key). + StampGenerationFailed, + /// `FLAG_ENCRYPTED` requested but no encryptor supplied to `tick`. + EncryptorMissing, + /// Encryptor returned `None` for this payload. + EncryptionFailed, +} + +/// Optional encryptor closure; the announcer holds no identity material. +pub type EncryptFn<'a> = &'a dyn Fn(&[u8]) -> Option>; + +/// Pure-data scheduler. Not async, holds no timer — drive via `tick`. +pub struct Announcer { + stamper: Arc, + interfaces: HashMap, +} + +impl Announcer { + pub fn new(stamper: Arc) -> Self { + Self { + stamper, + interfaces: HashMap::new(), + } + } + + /// Register (or replace) an interface's discovery config. + /// `transport_id` = 16-byte identity hash carried in `TRANSPORT_ID`. + pub fn register( + &mut self, + interface_id: InterfaceId, + transport_id: [u8; 16], + config: DiscoveryInterfaceConfig, + ) { + self.interfaces.insert( + interface_id, + InterfaceAnnounceState { + config, + transport_id, + last_announce_at: 0.0, + stamp_cache: None, + }, + ); + } + + /// Drop an interface from the announcer (called on deregister). + pub fn deregister(&mut self, interface_id: InterfaceId) { + self.interfaces.remove(&interface_id); + } + + /// Inspect registered interfaces (for tests / introspection). + pub fn len(&self) -> usize { + self.interfaces.len() + } + + pub fn is_empty(&self) -> bool { + self.interfaces.is_empty() + } + + /// Return announces due at `now` plus the skip list (so tests can + /// assert on both). `encrypt` is required only when a config has `encrypt=true`. + pub fn tick( + &mut self, + now: f64, + encrypt: Option>, + ) -> (Vec, Vec<(InterfaceId, SkipReason)>) { + let mut out = Vec::new(); + let mut skips = Vec::new(); + + for (id, state) in self.interfaces.iter_mut() { + if !state.config.discoverable { + skips.push((*id, SkipReason::NotDiscoverable)); + continue; + } + if !state.config.is_advertisable() { + skips.push((*id, SkipReason::TypeNotAdvertisable)); + continue; + } + + let interval = state.config.announce_interval_secs as f64; + let elapsed = now - state.last_announce_at; + if state.last_announce_at > 0.0 && elapsed < interval { + let remaining_secs = (interval - elapsed).max(0.0) as u64; + skips.push((*id, SkipReason::RateLimited { remaining_secs })); + continue; + } + + let info = config_to_info(&state.config, state.transport_id); + let Ok(Encoded { packed, infohash }) = app_data::encode_info(&info) else { + skips.push((*id, SkipReason::StampGenerationFailed)); + continue; + }; + + // Reuse cached stamp if the infohash is unchanged. + let stamp = match &state.stamp_cache { + Some((cached_ih, cached_stamp)) if cached_ih == &infohash => cached_stamp.clone(), + _ => match self.stamper.generate(&infohash, state.config.stamp_value) { + Some(s) if s.len() == STAMP_SIZE => s, + _ => { + skips.push((*id, SkipReason::StampGenerationFailed)); + continue; + } + }, + }; + + let encoded = Encoded { + packed: packed.clone(), + infohash, + }; + let flag_encrypted = state.config.encrypt; + let flag_signed = state.config.signed; + let blob = if flag_encrypted { + let Some(enc) = encrypt else { + skips.push((*id, SkipReason::EncryptorMissing)); + continue; + }; + match encoded.assemble(&stamp, true, flag_signed, Some(enc)) { + Some(b) => b, + None => { + skips.push((*id, SkipReason::EncryptionFailed)); + continue; + } + } + } else { + match encoded.assemble(&stamp, false, flag_signed, None) { + Some(b) => b, + None => { + skips.push((*id, SkipReason::StampGenerationFailed)); + continue; + } + } + }; + + let stamp_value = self.stamper.value(&infohash, &stamp); + state.last_announce_at = now; + state.stamp_cache = Some((infohash, stamp)); + + trace!( + interface_id = id, + name = %state.config.name, + stamp_value, + "discovery announce prepared" + ); + + out.push(AnnounceRequest { + interface_id: *id, + app_data: blob, + stamp_value, + }); + } + + debug!( + due = out.len(), + skipped = skips.len(), + registered = self.interfaces.len(), + "discovery announcer tick" + ); + (out, skips) + } +} + +fn config_to_info(cfg: &DiscoveryInterfaceConfig, transport_id: [u8; 16]) -> DiscoveryInfo { + DiscoveryInfo { + name: cfg.name.clone(), + transport_id, + interface_type: cfg.interface_type.clone(), + transport_enabled: cfg.transport_enabled, + reachable_on: cfg.reachable_on.clone(), + latitude: cfg.latitude, + longitude: cfg.longitude, + height: cfg.height, + port: cfg.port, + ifac_netname: cfg.ifac_netname.clone(), + ifac_netkey: cfg.ifac_netkey.clone(), + frequency: cfg.frequency, + bandwidth: cfg.bandwidth, + spreading_factor: cfg.spreading_factor, + coding_rate: cfg.coding_rate, + modulation: cfg.modulation.clone(), + channel: cfg.channel, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::discovery::constants::{FLAG_ENCRYPTED, FLAG_SIGNED}; + + struct StaticStamper { + stamp: Vec, + value: u8, + } + + impl DiscoveryStamper for StaticStamper { + fn generate(&self, _: &[u8; 32], _: u8) -> Option> { + Some(self.stamp.clone()) + } + fn value(&self, _: &[u8; 32], _: &[u8]) -> u8 { + self.value + } + fn valid(&self, _: &[u8; 32], _: &[u8], required: u8) -> bool { + self.value >= required + } + } + + struct RefusingStamper; + impl DiscoveryStamper for RefusingStamper { + fn generate(&self, _: &[u8; 32], _: u8) -> Option> { + None + } + fn value(&self, _: &[u8; 32], _: &[u8]) -> u8 { + 0 + } + fn valid(&self, _: &[u8; 32], _: &[u8], _: u8) -> bool { + false + } + } + + fn sample_backbone() -> DiscoveryInterfaceConfig { + DiscoveryInterfaceConfig::backbone("relay-a".into(), "10.0.0.1".into(), 4965) + } + + fn static_stamper() -> Arc { + Arc::new(StaticStamper { + stamp: vec![0xBB; STAMP_SIZE], + value: 16, + }) + } + + #[test] + fn empty_tick_emits_nothing() { + let mut a = Announcer::new(static_stamper()); + let (requests, skips) = a.tick(1000.0, None); + assert!(requests.is_empty()); + assert!(skips.is_empty()); + } + + #[test] + fn first_tick_emits_announce() { + let mut a = Announcer::new(static_stamper()); + a.register(1, [0x11; 16], sample_backbone()); + let (requests, skips) = a.tick(1000.0, None); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].interface_id, 1); + assert_eq!(requests[0].stamp_value, 16); + assert!(skips.is_empty()); + + // Verify the blob round-trips. + let (flags, body) = app_data::split_flags(&requests[0].app_data).unwrap(); + assert_eq!(flags & FLAG_SIGNED, FLAG_SIGNED); + assert_eq!(flags & FLAG_ENCRYPTED, 0); + let (info_bytes, stamp) = app_data::split_stamp(body).unwrap(); + assert_eq!(stamp, &[0xBB; STAMP_SIZE]); + let info = app_data::decode_info(info_bytes).unwrap(); + assert_eq!(info.name, "relay-a"); + assert_eq!(info.transport_id, [0x11; 16]); + assert_eq!(info.port, Some(4965)); + } + + #[test] + fn subsequent_tick_within_interval_skips() { + let mut a = Announcer::new(static_stamper()); + a.register(1, [0x11; 16], sample_backbone()); + let _ = a.tick(1000.0, None); + let (requests, skips) = a.tick(1005.0, None); + assert!(requests.is_empty()); + assert_eq!(skips.len(), 1); + assert!(matches!(skips[0].1, SkipReason::RateLimited { .. })); + } + + #[test] + fn tick_after_interval_re_emits() { + let mut a = Announcer::new(static_stamper()); + a.register(1, [0x11; 16], sample_backbone()); + let _ = a.tick(1000.0, None); + let (requests, _) = a.tick(1000.0 + (ANNOUNCE_JOB_INTERVAL_SECS as f64) + 1.0, None); + assert_eq!(requests.len(), 1); + } + + #[test] + fn non_discoverable_is_skipped() { + let mut a = Announcer::new(static_stamper()); + let mut cfg = sample_backbone(); + cfg.discoverable = false; + a.register(1, [0x11; 16], cfg); + let (requests, skips) = a.tick(1000.0, None); + assert!(requests.is_empty()); + assert_eq!(skips.len(), 1); + assert_eq!(skips[0].1, SkipReason::NotDiscoverable); + } + + #[test] + fn unadvertisable_type_is_skipped() { + let mut a = Announcer::new(static_stamper()); + let mut cfg = sample_backbone(); + cfg.interface_type = "LocalInterface".into(); // not in DISCOVERABLE_INTERFACE_TYPES + a.register(1, [0x11; 16], cfg); + let (requests, skips) = a.tick(1000.0, None); + assert!(requests.is_empty()); + assert_eq!(skips[0].1, SkipReason::TypeNotAdvertisable); + } + + #[test] + fn stamper_refusal_is_skipped() { + let mut a = Announcer::new(Arc::new(RefusingStamper)); + a.register(1, [0x11; 16], sample_backbone()); + let (requests, skips) = a.tick(1000.0, None); + assert!(requests.is_empty()); + assert_eq!(skips[0].1, SkipReason::StampGenerationFailed); + } + + #[test] + fn stamp_is_cached_across_ticks() { + // Count generate() calls — second tick with unchanged info must + // reuse the cached stamp. + struct CountingStamper { + count: std::sync::Mutex, + stamp: Vec, + } + impl DiscoveryStamper for CountingStamper { + fn generate(&self, _: &[u8; 32], _: u8) -> Option> { + *self.count.lock().unwrap() += 1; + Some(self.stamp.clone()) + } + fn value(&self, _: &[u8; 32], _: &[u8]) -> u8 { + 16 + } + fn valid(&self, _: &[u8; 32], _: &[u8], _: u8) -> bool { + true + } + } + let stamper = Arc::new(CountingStamper { + count: std::sync::Mutex::new(0), + stamp: vec![0xCC; STAMP_SIZE], + }); + let count_probe = Arc::clone(&stamper); + let mut a = Announcer::new(stamper); + a.register(1, [0x11; 16], sample_backbone()); + + let _ = a.tick(1000.0, None); + let _ = a.tick(2000.0, None); + let _ = a.tick(3000.0, None); + assert_eq!(*count_probe.count.lock().unwrap(), 1); + } + + #[test] + fn config_change_invalidates_stamp_cache() { + // If the caller re-registers with a different info, the stamp + // must be regenerated (infohash changed). + struct CountingStamper { + count: std::sync::Mutex, + stamp: Vec, + } + impl DiscoveryStamper for CountingStamper { + fn generate(&self, _: &[u8; 32], _: u8) -> Option> { + *self.count.lock().unwrap() += 1; + Some(self.stamp.clone()) + } + fn value(&self, _: &[u8; 32], _: &[u8]) -> u8 { + 16 + } + fn valid(&self, _: &[u8; 32], _: &[u8], _: u8) -> bool { + true + } + } + let stamper = Arc::new(CountingStamper { + count: std::sync::Mutex::new(0), + stamp: vec![0xDD; STAMP_SIZE], + }); + let count_probe = Arc::clone(&stamper); + let mut a = Announcer::new(stamper); + a.register(1, [0x11; 16], sample_backbone()); + let _ = a.tick(1000.0, None); + assert_eq!(*count_probe.count.lock().unwrap(), 1); + + // Re-register with a new name — different infohash. + let mut cfg = sample_backbone(); + cfg.name = "relay-a-renamed".into(); + a.register(1, [0x11; 16], cfg); + let _ = a.tick(2000.0 + ANNOUNCE_JOB_INTERVAL_SECS as f64, None); + assert_eq!(*count_probe.count.lock().unwrap(), 2); + } + + #[test] + fn encrypt_true_without_encryptor_skips() { + let mut a = Announcer::new(static_stamper()); + let mut cfg = sample_backbone(); + cfg.encrypt = true; + a.register(1, [0x11; 16], cfg); + let (requests, skips) = a.tick(1000.0, None); + assert!(requests.is_empty()); + assert_eq!(skips[0].1, SkipReason::EncryptorMissing); + } + + #[test] + fn encrypt_true_with_encryptor_succeeds() { + let mut a = Announcer::new(static_stamper()); + let mut cfg = sample_backbone(); + cfg.encrypt = true; + a.register(1, [0x11; 16], cfg); + let xor: &dyn Fn(&[u8]) -> Option> = + &|pt: &[u8]| Some(pt.iter().map(|b| b ^ 0xFF).collect()); + let (requests, _) = a.tick(1000.0, Some(xor)); + assert_eq!(requests.len(), 1); + let (flags, _) = app_data::split_flags(&requests[0].app_data).unwrap(); + assert_eq!(flags & FLAG_ENCRYPTED, FLAG_ENCRYPTED); + } + + #[test] + fn deregister_drops_interface() { + let mut a = Announcer::new(static_stamper()); + a.register(1, [0x11; 16], sample_backbone()); + assert_eq!(a.len(), 1); + a.deregister(1); + assert!(a.is_empty()); + + let (requests, skips) = a.tick(1000.0, None); + assert!(requests.is_empty()); + assert!(skips.is_empty()); + } + + #[test] + fn multiple_interfaces_each_tick_independently() { + let mut a = Announcer::new(static_stamper()); + let mut cfg1 = sample_backbone(); + cfg1.name = "a".into(); + let mut cfg2 = sample_backbone(); + cfg2.name = "b".into(); + cfg2.announce_interval_secs = 30; // shorter interval + a.register(1, [0x11; 16], cfg1); + a.register(2, [0x22; 16], cfg2); + + let (first, _) = a.tick(1000.0, None); + assert_eq!(first.len(), 2); + + // Only the shorter-interval interface is due at +40s. + let (second, skips) = a.tick(1040.0, None); + assert_eq!(second.len(), 1); + assert_eq!(second[0].interface_id, 2); + assert!(matches!(skips[0].1, SkipReason::RateLimited { .. })); + } +} diff --git a/crates/rns-transport/src/discovery/app_data.rs b/crates/rns-transport/src/discovery/app_data.rs new file mode 100644 index 0000000..e673c36 --- /dev/null +++ b/crates/rns-transport/src/discovery/app_data.rs @@ -0,0 +1,534 @@ +//! Discovery announce app_data — msgpack encode/decode. +//! +//! Wire format (matches Python `Discovery.py` `get_interface_announce_data` +//! / `InterfaceAnnounceHandler.received_announce`): +//! +//! ```text +//! app_data = flags_byte(1) || payload +//! +//! payload = msgpack_info || stamp (FLAG_ENCRYPTED clear) +//! = encrypt(msgpack_info || stamp) (FLAG_ENCRYPTED set) +//! +//! msgpack_info = msgpack map with numeric u8 keys — see `constants::key::*` +//! stamp = STAMP_SIZE (32) bytes, produced by the configured DiscoveryStamper +//! ``` +//! +//! The map keys are byte values (not strings). Python encodes them via +//! `umsgpack.packb`, which uses fixint or uint8 depending on range; rmpv +//! produces the same bytes in both cases. + +use std::io::Cursor; + +use rmpv::Value; +use thiserror::Error; + +use super::constants::{FLAG_ENCRYPTED, STAMP_SIZE, key}; + +/// A decoded discovery info payload. Mirrors the Python `info` dict. +/// +/// Optional fields mirror Python's presence-or-absence of keys. Required +/// fields (NAME, TRANSPORT_ID, INTERFACE_TYPE, TRANSPORT, LATITUDE, +/// LONGITUDE, HEIGHT) are always present. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct DiscoveryInfo { + /// Human-readable interface name (key `0xFF`). + pub name: String, + /// Transport identity hash of the announcer (key `0xFE`, 16 bytes). + pub transport_id: [u8; 16], + /// Interface type string, e.g. `"BackboneInterface"` (key `0x00`). + pub interface_type: String, + /// Whether the announcer has transport (routing) enabled (key `0x01`). + pub transport_enabled: bool, + /// Endpoint address (IP/hostname/b32 for I2P) — optional (key `0x02`). + pub reachable_on: Option, + /// Geolocation (keys `0x03` / `0x04` / `0x05`). + pub latitude: f64, + pub longitude: f64, + pub height: f64, + /// TCP/Backbone bind port (key `0x06`). + pub port: Option, + /// IFAC virtual-network overlay (keys `0x07` / `0x08`). + pub ifac_netname: Option, + pub ifac_netkey: Option, + /// Radio-link parameters (keys `0x09` / `0x0A` / `0x0B` / `0x0C`). + pub frequency: Option, + pub bandwidth: Option, + pub spreading_factor: Option, + pub coding_rate: Option, + /// Modulation name for Weave / KISS (key `0x0D`). + pub modulation: Option, + /// Weave channel number (key `0x0E`). + pub channel: Option, +} + +#[derive(Debug, Error)] +pub enum AppDataError { + #[error("empty payload — missing flags byte")] + Empty, + #[error("payload too small for stamp (need at least {need} bytes, got {got})")] + TooSmall { need: usize, got: usize }, + #[error("transport_id must be 16 bytes, got {0}")] + BadTransportId(usize), + #[error("missing required key 0x{0:02X}")] + MissingKey(u8), + #[error("type mismatch at key 0x{key:02X}: expected {expected}")] + TypeMismatch { key: u8, expected: &'static str }, + #[error("msgpack decode: {0}")] + Msgpack(String), + #[error("top-level msgpack value must be a map")] + NotAMap, +} + +/// Encoded payload — separates the stamp from the raw msgpack map so the +/// caller can stamp it separately (stamper wraps the info-hash, not the full +/// app_data). Call [`Encoded::assemble`] once a stamp is in hand. +pub struct Encoded { + /// The msgpack-encoded info map. + pub packed: Vec, + /// SHA-256 of `packed` — used as the stamper's infohash input. + pub infohash: [u8; 32], +} + +impl Encoded { + /// Combine `packed_info || stamp`, optionally encrypt, prefix flags byte. + /// + /// `encrypt` is a closure so discovery doesn't need to carry the network + /// identity type — the caller composes with + /// `Identity::encrypt(&self.network_identity, ...)` when + /// `flag_encrypted` is set. When `encrypt` is `None` and + /// `flag_encrypted` is true, the function returns `None`. + pub fn assemble( + self, + stamp: &[u8], + flag_encrypted: bool, + flag_signed: bool, + encrypt: Option<&DiscoveryEncryptor<'_>>, + ) -> Option> { + if stamp.len() != STAMP_SIZE { + return None; + } + let mut body = self.packed; + body.extend_from_slice(stamp); + + let body = if flag_encrypted { + encrypt?(&body)? + } else { + body + }; + + let mut out = Vec::with_capacity(1 + body.len()); + let mut flags = 0u8; + if flag_signed { + flags |= super::constants::FLAG_SIGNED; + } + if flag_encrypted { + flags |= FLAG_ENCRYPTED; + } + out.push(flags); + out.extend_from_slice(&body); + Some(out) + } +} + +/// Optional network-identity encryptor used when assembling discovery app-data. +pub type DiscoveryEncryptor<'a> = dyn Fn(&[u8]) -> Option> + 'a; + +/// Serialize the info dict to the `(packed, infohash)` pair used by the +/// stamper. Matches Python `msgpack.packb(info)` + `Identity.full_hash(packed)`. +pub fn encode_info(info: &DiscoveryInfo) -> Result { + let map = info_to_map(info); + let value = Value::Map(map); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &value) + .map_err(|e| AppDataError::Msgpack(e.to_string()))?; + let infohash = rns_crypto::sha::full_hash(&buf); + Ok(Encoded { + packed: buf, + infohash, + }) +} + +fn info_to_map(info: &DiscoveryInfo) -> Vec<(Value, Value)> { + // Python-Discovery.py iteration order for required keys. Receivers do + // not depend on ordering; we keep it stable for testability against + // pinned vectors. + let mut entries: Vec<(Value, Value)> = vec![ + ( + u8_key(key::INTERFACE_TYPE), + Value::from(info.interface_type.clone()), + ), + (u8_key(key::TRANSPORT), Value::from(info.transport_enabled)), + ( + u8_key(key::TRANSPORT_ID), + Value::Binary(info.transport_id.to_vec()), + ), + (u8_key(key::NAME), Value::from(info.name.clone())), + (u8_key(key::LATITUDE), Value::F64(info.latitude)), + (u8_key(key::LONGITUDE), Value::F64(info.longitude)), + (u8_key(key::HEIGHT), Value::F64(info.height)), + ]; + + if let Some(addr) = &info.reachable_on { + entries.push((u8_key(key::REACHABLE_ON), Value::from(addr.clone()))); + } + if let Some(port) = info.port { + entries.push((u8_key(key::PORT), Value::from(port))); + } + if let Some(name) = &info.ifac_netname { + entries.push((u8_key(key::IFAC_NETNAME), Value::from(name.clone()))); + } + if let Some(k) = &info.ifac_netkey { + entries.push((u8_key(key::IFAC_NETKEY), Value::from(k.clone()))); + } + if let Some(f) = info.frequency { + entries.push((u8_key(key::FREQUENCY), Value::from(f))); + } + if let Some(b) = info.bandwidth { + entries.push((u8_key(key::BANDWIDTH), Value::from(b))); + } + if let Some(sf) = info.spreading_factor { + entries.push((u8_key(key::SPREADING_FACTOR), Value::from(sf))); + } + if let Some(cr) = info.coding_rate { + entries.push((u8_key(key::CODING_RATE), Value::from(cr))); + } + if let Some(mod_) = &info.modulation { + entries.push((u8_key(key::MODULATION), Value::from(mod_.clone()))); + } + if let Some(ch) = info.channel { + entries.push((u8_key(key::CHANNEL), Value::from(ch))); + } + + entries +} + +fn u8_key(k: u8) -> Value { + Value::from(k) +} + +/// Split an inbound app_data blob into `(flags, payload_body)` where +/// `payload_body` is everything after the flags byte. The body is still +/// `msgpack_info || stamp` (optionally still-encrypted). +pub fn split_flags(app_data: &[u8]) -> Result<(u8, &[u8]), AppDataError> { + let (first, rest) = app_data.split_first().ok_or(AppDataError::Empty)?; + Ok((*first, rest)) +} + +/// Split the decrypted/cleartext body into `(packed_info, stamp)`. The +/// stamp is always the trailing [`STAMP_SIZE`] bytes. +pub fn split_stamp(body: &[u8]) -> Result<(&[u8], &[u8]), AppDataError> { + if body.len() <= STAMP_SIZE { + return Err(AppDataError::TooSmall { + need: STAMP_SIZE + 1, + got: body.len(), + }); + } + let split_at = body.len() - STAMP_SIZE; + Ok((&body[..split_at], &body[split_at..])) +} + +/// Decode a msgpack info map back into [`DiscoveryInfo`]. +pub fn decode_info(packed: &[u8]) -> Result { + let value = rmpv::decode::read_value(&mut Cursor::new(packed)) + .map_err(|e| AppDataError::Msgpack(e.to_string()))?; + let map = match value { + Value::Map(m) => m, + _ => return Err(AppDataError::NotAMap), + }; + + let mut info = DiscoveryInfo::default(); + let mut saw_interface_type = false; + let mut saw_transport_id = false; + + for (k, v) in map { + let Some(kb) = value_as_u8(&k) else { + continue; // unknown/non-numeric keys are ignored for forward compat + }; + match kb { + key::NAME => { + info.name = value_as_string(&v, kb)?; + } + key::TRANSPORT_ID => { + let bytes = value_as_bytes(&v, kb)?; + if bytes.len() != 16 { + return Err(AppDataError::BadTransportId(bytes.len())); + } + info.transport_id.copy_from_slice(&bytes); + saw_transport_id = true; + } + key::INTERFACE_TYPE => { + info.interface_type = value_as_string(&v, kb)?; + saw_interface_type = true; + } + key::TRANSPORT => { + info.transport_enabled = value_as_bool(&v, kb)?; + } + key::REACHABLE_ON => { + info.reachable_on = Some(value_as_string(&v, kb)?); + } + key::LATITUDE => info.latitude = value_as_f64(&v, kb)?, + key::LONGITUDE => info.longitude = value_as_f64(&v, kb)?, + key::HEIGHT => info.height = value_as_f64(&v, kb)?, + key::PORT => { + let n = value_as_u64(&v, kb)?; + info.port = Some(n.min(u16::MAX as u64) as u16); + } + key::IFAC_NETNAME => info.ifac_netname = Some(value_as_string(&v, kb)?), + key::IFAC_NETKEY => info.ifac_netkey = Some(value_as_string(&v, kb)?), + key::FREQUENCY => info.frequency = Some(value_as_u64(&v, kb)?), + key::BANDWIDTH => info.bandwidth = Some(value_as_u64(&v, kb)?), + key::SPREADING_FACTOR => { + info.spreading_factor = Some(value_as_u64(&v, kb)?.min(u8::MAX as u64) as u8); + } + key::CODING_RATE => { + info.coding_rate = Some(value_as_u64(&v, kb)?.min(u8::MAX as u64) as u8); + } + key::MODULATION => info.modulation = Some(value_as_string(&v, kb)?), + key::CHANNEL => { + info.channel = Some(value_as_u64(&v, kb)?.min(u16::MAX as u64) as u16); + } + _ => { /* unknown key: ignore for forward compat */ } + } + } + + if !saw_interface_type { + return Err(AppDataError::MissingKey(key::INTERFACE_TYPE)); + } + if !saw_transport_id { + return Err(AppDataError::MissingKey(key::TRANSPORT_ID)); + } + Ok(info) +} + +fn value_as_u8(v: &Value) -> Option { + v.as_u64().and_then(|n| u8::try_from(n).ok()) +} + +fn value_as_bool(v: &Value, kb: u8) -> Result { + match v { + Value::Boolean(b) => Ok(*b), + _ => Err(AppDataError::TypeMismatch { + key: kb, + expected: "bool", + }), + } +} + +fn value_as_string(v: &Value, kb: u8) -> Result { + match v { + Value::String(s) => Ok(s.as_str().unwrap_or("").to_string()), + Value::Binary(b) => Ok(String::from_utf8_lossy(b).into_owned()), + _ => Err(AppDataError::TypeMismatch { + key: kb, + expected: "string", + }), + } +} + +fn value_as_bytes(v: &Value, kb: u8) -> Result, AppDataError> { + match v { + Value::Binary(b) => Ok(b.clone()), + Value::String(s) => Ok(s.as_bytes().to_vec()), + _ => Err(AppDataError::TypeMismatch { + key: kb, + expected: "bytes", + }), + } +} + +fn value_as_f64(v: &Value, kb: u8) -> Result { + match v { + Value::F64(f) => Ok(*f), + Value::F32(f) => Ok(*f as f64), + Value::Integer(n) => Ok(n.as_f64().unwrap_or(0.0)), + _ => Err(AppDataError::TypeMismatch { + key: kb, + expected: "float", + }), + } +} + +fn value_as_u64(v: &Value, kb: u8) -> Result { + v.as_u64().ok_or(AppDataError::TypeMismatch { + key: kb, + expected: "uint", + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_backbone() -> DiscoveryInfo { + DiscoveryInfo { + name: "London Relay".into(), + transport_id: [0x11; 16], + interface_type: "BackboneInterface".into(), + transport_enabled: true, + reachable_on: Some("relay.example.org".into()), + latitude: 51.5074, + longitude: -0.1278, + height: 35.0, + port: Some(4965), + ifac_netname: Some("mynet".into()), + ifac_netkey: Some("hunter2".into()), + ..Default::default() + } + } + + fn sample_rnode() -> DiscoveryInfo { + DiscoveryInfo { + name: "Berlin LoRa".into(), + transport_id: [0x22; 16], + interface_type: "RNodeInterface".into(), + transport_enabled: false, + latitude: 52.5200, + longitude: 13.4050, + height: 50.0, + frequency: Some(869_525_000), + bandwidth: Some(125_000), + spreading_factor: Some(8), + coding_rate: Some(5), + ..Default::default() + } + } + + #[test] + fn round_trip_backbone_info() { + let info = sample_backbone(); + let encoded = encode_info(&info).expect("encode"); + let decoded = decode_info(&encoded.packed).expect("decode"); + assert_eq!(decoded, info); + } + + #[test] + fn round_trip_rnode_info() { + let info = sample_rnode(); + let encoded = encode_info(&info).expect("encode"); + let decoded = decode_info(&encoded.packed).expect("decode"); + assert_eq!(decoded, info); + } + + #[test] + fn assemble_and_split_unencrypted() { + let info = sample_backbone(); + let encoded = encode_info(&info).expect("encode"); + let packed_clone = encoded.packed.clone(); + let infohash_clone = encoded.infohash; + let stamp = vec![0x5A; STAMP_SIZE]; + let blob = encoded + .assemble(&stamp, false, false, None) + .expect("assemble"); + + let (flags, body) = split_flags(&blob).expect("flags"); + assert_eq!(flags, 0); + let (pinfo, pstamp) = split_stamp(body).expect("stamp split"); + assert_eq!(pinfo, packed_clone.as_slice()); + assert_eq!(pstamp, stamp.as_slice()); + + let decoded = decode_info(pinfo).expect("decode"); + assert_eq!(decoded, info); + + let recomputed_hash = rns_crypto::sha::full_hash(pinfo); + assert_eq!(recomputed_hash, infohash_clone); + } + + #[test] + fn assemble_encrypted_invokes_closure() { + let info = sample_rnode(); + let encoded = encode_info(&info).expect("encode"); + let stamp = vec![0xA5; STAMP_SIZE]; + let blob = encoded + .assemble( + &stamp, + true, + false, + Some(&|plaintext: &[u8]| { + // Pseudo-encrypt by XOR-ing with 0xFF so we can invert. + Some(plaintext.iter().map(|b| b ^ 0xFF).collect()) + }), + ) + .expect("assemble"); + + let (flags, body) = split_flags(&blob).expect("flags"); + assert_eq!(flags & FLAG_ENCRYPTED, FLAG_ENCRYPTED); + + let decrypted: Vec = body.iter().map(|b| b ^ 0xFF).collect(); + let (pinfo, pstamp) = split_stamp(&decrypted).expect("stamp split"); + assert_eq!(pstamp, stamp.as_slice()); + + let decoded = decode_info(pinfo).expect("decode"); + assert_eq!(decoded, info); + } + + #[test] + fn assemble_rejects_wrong_stamp_length() { + let encoded = encode_info(&sample_backbone()).unwrap(); + let short = vec![0; STAMP_SIZE - 1]; + assert!(encoded.assemble(&short, false, false, None).is_none()); + } + + #[test] + fn split_flags_rejects_empty() { + assert!(matches!(split_flags(&[]), Err(AppDataError::Empty))); + } + + #[test] + fn split_stamp_rejects_short_body() { + let body = vec![0; STAMP_SIZE]; + assert!(matches!( + split_stamp(&body), + Err(AppDataError::TooSmall { .. }) + )); + } + + #[test] + fn decode_rejects_missing_transport_id() { + // Build a minimal map missing TRANSPORT_ID. + let map = vec![ + (Value::from(key::INTERFACE_TYPE), Value::from("X")), + (Value::from(key::TRANSPORT), Value::from(false)), + (Value::from(key::NAME), Value::from("n")), + (Value::from(key::LATITUDE), Value::F64(0.0)), + (Value::from(key::LONGITUDE), Value::F64(0.0)), + (Value::from(key::HEIGHT), Value::F64(0.0)), + ]; + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &Value::Map(map)).unwrap(); + assert!(matches!( + decode_info(&buf), + Err(AppDataError::MissingKey(key::TRANSPORT_ID)) + )); + } + + #[test] + fn decode_tolerates_unknown_keys() { + // Forward-compat: an unknown key (0x7F) must not break decoding. + let info = sample_backbone(); + let mut map = info_to_map(&info); + map.push((Value::from(0x7Fu8), Value::from("future-field"))); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &Value::Map(map)).unwrap(); + let decoded = decode_info(&buf).expect("decode"); + assert_eq!(decoded, info); + } + + #[test] + fn bad_transport_id_length_errors() { + let map = vec![ + (Value::from(key::INTERFACE_TYPE), Value::from("X")), + (Value::from(key::TRANSPORT_ID), Value::Binary(vec![0; 8])), + (Value::from(key::TRANSPORT), Value::from(false)), + (Value::from(key::NAME), Value::from("n")), + (Value::from(key::LATITUDE), Value::F64(0.0)), + (Value::from(key::LONGITUDE), Value::F64(0.0)), + (Value::from(key::HEIGHT), Value::F64(0.0)), + ]; + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &Value::Map(map)).unwrap(); + assert!(matches!( + decode_info(&buf), + Err(AppDataError::BadTransportId(8)) + )); + } +} diff --git a/crates/rns-transport/src/discovery/blackhole_manifest.rs b/crates/rns-transport/src/discovery/blackhole_manifest.rs new file mode 100644 index 0000000..ca3bfcb --- /dev/null +++ b/crates/rns-transport/src/discovery/blackhole_manifest.rs @@ -0,0 +1,482 @@ +//! Wire-format codec for the distributed blackhole manifest. +//! +//! Mirrors the msgpack payload served by Python's +//! `rnstransport.info.blackhole` request handler (Transport.py:3243) and +//! consumed by the subscriber side of `BlackholeUpdater` (Discovery.py:658). +//! +//! # Wire shape +//! +//! ```text +//! msgpack::Map { +//! identity_hash_bytes (16B): msgpack::Map { +//! "source": source_identity_hash_bytes (16B), +//! "until": f64 unix-seconds | nil, +//! "reason": str | nil, +//! }, +//! ... +//! } +//! ``` +//! +//! Python uses absolute-deadline `until` on the wire; the Rust table keeps +//! relative `ttl`. Conversions happen at the boundary: +//! - **encode**: `until = created + ttl` when `ttl.is_some()`, else `nil`. +//! - **decode**: `created = now`, `ttl = max(0, until - now)`. This mirrors +//! the semantics in Transport.py:3212 — expired entries are skipped. +//! +//! # Publication filter +//! +//! A node only publishes entries it issued itself. In-memory: entries with +//! `source == None`. Python's equivalent filter (Transport.py:3256) is +//! `source == Transport.identity.hash`; we keep `None` as a marker so the +//! table does not need to know its own identity. + +use std::collections::BTreeMap; + +use rmpv::Value; +use rns_wire::types::IdentityHash; +use thiserror::Error; + +use crate::blackhole::{BlackholeEntry, BlackholeReason, BlackholeTable}; + +/// A single manifest entry on the wire. `created` is not transmitted — +/// Python stores `until` (absolute deadline) instead. +#[derive(Debug, Clone, PartialEq)] +pub struct BlackholeManifestEntry { + /// Absolute unix-second deadline, or `None` for permanent entries. + pub until: Option, + /// Stable string identifier (see [`BlackholeReason::as_str`]). + pub reason: String, + /// Identity hash of the source that issued this entry. + pub source: IdentityHash, +} + +#[derive(Debug, Error, PartialEq)] +pub enum ManifestError { + #[error("manifest root is not a map")] + NotAMap, + #[error("manifest key is not 16-byte identity hash")] + BadKey, + #[error("manifest entry is not a map")] + EntryNotMap, + #[error("manifest entry missing required field: {0}")] + MissingField(&'static str), + #[error("manifest entry has malformed field: {0}")] + BadField(&'static str), + #[error("msgpack decode error: {0}")] + Decode(String), + #[error("msgpack encode error: {0}")] + Encode(String), +} + +/// Build the msgpack manifest payload of **locally-issued** blackhole +/// entries. Used by the `/list` request handler on +/// `rnstransport.info.blackhole`. +/// +/// `our_identity_hash` is injected into every entry's `source` field so +/// subscribers can correctly key entries by publisher. +pub fn build_local_manifest( + table: &BlackholeTable, + our_identity_hash: IdentityHash, +) -> Result, ManifestError> { + let mut map: Vec<(Value, Value)> = Vec::new(); + + for (hash, entry) in table.iter_entries() { + if entry.source.is_some() { + continue; + } + let until = entry.ttl.map(|ttl| entry.created + ttl); + let wire_entry = encode_entry_map(until, entry.reason_str(), our_identity_hash); + map.push((Value::Binary(hash.as_bytes().to_vec()), wire_entry)); + } + + let root = Value::Map(map); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &root).map_err(|e| ManifestError::Encode(e.to_string()))?; + Ok(buf) +} + +fn encode_entry_map(until: Option, reason: &str, source: IdentityHash) -> Value { + let until_v = match until { + Some(t) => Value::F64(t), + None => Value::Nil, + }; + Value::Map(vec![ + ( + Value::String("source".into()), + Value::Binary(source.as_bytes().to_vec()), + ), + (Value::String("until".into()), until_v), + ( + Value::String("reason".into()), + Value::String(reason.to_string().into()), + ), + ]) +} + +/// Parse a msgpack manifest payload into `(identity_hash, entry)` pairs. +/// Sorted for deterministic iteration in tests; order is not load-bearing +/// otherwise. +pub fn decode_manifest( + bytes: &[u8], +) -> Result, ManifestError> { + let mut cursor = std::io::Cursor::new(bytes); + let root = + rmpv::decode::read_value(&mut cursor).map_err(|e| ManifestError::Decode(e.to_string()))?; + + let map = match root { + Value::Map(m) => m, + _ => return Err(ManifestError::NotAMap), + }; + + let mut sorted: BTreeMap<[u8; 16], BlackholeManifestEntry> = BTreeMap::new(); + for (k, v) in map { + let key = match k { + Value::Binary(b) if b.len() == 16 => { + let mut h = [0u8; 16]; + h.copy_from_slice(&b); + h + } + _ => return Err(ManifestError::BadKey), + }; + let entry = decode_entry_map(v)?; + sorted.insert(key, entry); + } + + Ok(sorted.into_iter().collect()) +} + +fn decode_entry_map(v: Value) -> Result { + let map = match v { + Value::Map(m) => m, + _ => return Err(ManifestError::EntryNotMap), + }; + + let mut source: Option = None; + let mut until: Option> = None; + let mut reason: Option = None; + + for (k, val) in map { + let key_str = match k { + Value::String(s) => s.into_str().unwrap_or_default(), + _ => continue, + }; + match key_str.as_str() { + "source" => match val { + Value::Binary(b) if b.len() == 16 => { + let mut h = [0u8; 16]; + h.copy_from_slice(&b); + source = Some(h.into()); + } + _ => return Err(ManifestError::BadField("source")), + }, + "until" => match val { + Value::Nil => until = Some(None), + Value::F64(t) => until = Some(Some(t)), + Value::F32(t) => until = Some(Some(t as f64)), + Value::Integer(i) => { + let as_f = i.as_f64().ok_or(ManifestError::BadField("until"))?; + until = Some(Some(as_f)); + } + _ => return Err(ManifestError::BadField("until")), + }, + "reason" => match val { + Value::Nil => reason = Some(String::new()), + Value::String(s) => { + reason = Some(s.into_str().unwrap_or_default()); + } + _ => return Err(ManifestError::BadField("reason")), + }, + _ => {} + } + } + + Ok(BlackholeManifestEntry { + source: source.ok_or(ManifestError::MissingField("source"))?, + until: until.ok_or(ManifestError::MissingField("until"))?, + reason: reason.ok_or(ManifestError::MissingField("reason"))?, + }) +} + +/// Merge a decoded manifest into `table`. `source_identity_hash` is the +/// publisher that answered the `/list` request; each entry's inner +/// `source` field is preserved so a chain of republishers stays +/// traceable (Python parity: Discovery.py:672-675). +/// +/// Skips: +/// - entries whose local-table source is `None` (locally-issued always wins); +/// - entries whose `until` deadline has already passed (matches +/// Transport.py:3212). +/// +/// Returns the number of entries actually inserted or updated. +pub fn apply_manifest( + table: &mut BlackholeTable, + manifest: &[([u8; 16], BlackholeManifestEntry)], + now: f64, +) -> usize { + let mut applied = 0usize; + for (id_hash, entry) in manifest { + if let Some(until) = entry.until + && until <= now + { + continue; + } + if let Some(existing) = table + .iter_entries() + .find(|(h, _)| h.as_bytes() == id_hash) + .map(|(_, e)| e.clone()) + && existing.source.is_none() + { + continue; + } + + let ttl = entry.until.map(|u| (u - now).max(0.0)); + let reason = BlackholeReason::parse(&entry.reason); + table.insert_entry( + *id_hash, + BlackholeEntry { + created: now, + ttl, + reason, + reason_label: Some(entry.reason.clone()), + source: Some(entry.source), + }, + ); + applied += 1; + } + applied +} + +#[cfg(test)] +mod tests { + use super::*; + + fn our_id() -> IdentityHash { + [0x11; 16].into() + } + + fn peer_id() -> IdentityHash { + [0x22; 16].into() + } + + #[test] + fn empty_table_produces_empty_map() { + let table = BlackholeTable::new(); + let bytes = build_local_manifest(&table, our_id()).unwrap(); + let decoded = decode_manifest(&bytes).unwrap(); + assert!(decoded.is_empty()); + } + + #[test] + fn local_entries_are_published_remote_entries_are_filtered() { + let mut table = BlackholeTable::new(); + table.add([0xAA; 16], None); + table.add_from_source( + [0xBB; 16], + Some(3600.0), + BlackholeReason::RateLimit, + peer_id(), + 1000.0, + ); + + let bytes = build_local_manifest(&table, our_id()).unwrap(); + let manifest = decode_manifest(&bytes).unwrap(); + + assert_eq!(manifest.len(), 1); + assert_eq!(manifest[0].0, [0xAA; 16]); + assert_eq!(manifest[0].1.source, our_id()); + assert_eq!(manifest[0].1.until, None); + assert_eq!(manifest[0].1.reason, "manual"); + } + + #[test] + fn ttl_roundtrips_as_absolute_until() { + let mut table = BlackholeTable::new(); + let now_at_add = now_seconds(); + table.add_with_reason([0xCC; 16], Some(600.0), BlackholeReason::Malformed); + + let bytes = build_local_manifest(&table, our_id()).unwrap(); + let manifest = decode_manifest(&bytes).unwrap(); + + assert_eq!(manifest.len(), 1); + let until = manifest[0].1.until.expect("until present"); + assert!(until >= now_at_add + 599.0 && until <= now_at_add + 601.0 + 10.0); + } + + #[test] + fn apply_manifest_inserts_remote_entries_with_ttl() { + let mut table = BlackholeTable::new(); + let now = 10_000.0; + let manifest = vec![( + [0xDD; 16], + BlackholeManifestEntry { + until: Some(now + 500.0), + reason: "malformed".into(), + source: peer_id(), + }, + )]; + + let applied = apply_manifest(&mut table, &manifest, now); + assert_eq!(applied, 1); + let expected: IdentityHash = [0xDD; 16].into(); + let entry = table + .iter_entries() + .find(|(h, _)| **h == expected) + .unwrap() + .1 + .clone(); + assert_eq!(entry.source, Some(peer_id())); + assert_eq!(entry.reason, BlackholeReason::Malformed); + assert_eq!(entry.created, now); + assert!((entry.ttl.unwrap() - 500.0).abs() < 0.01); + } + + #[test] + fn apply_manifest_skips_expired_entries() { + let mut table = BlackholeTable::new(); + let now = 10_000.0; + let manifest = vec![( + [0xEE; 16], + BlackholeManifestEntry { + until: Some(now - 10.0), + reason: "malformed".into(), + source: peer_id(), + }, + )]; + + let applied = apply_manifest(&mut table, &manifest, now); + assert_eq!(applied, 0); + assert!(table.is_empty()); + } + + #[test] + fn apply_manifest_preserves_permanent_entries() { + let mut table = BlackholeTable::new(); + let now = 10_000.0; + let manifest = vec![( + [0xFF; 16], + BlackholeManifestEntry { + until: None, + reason: "rate_limit".into(), + source: peer_id(), + }, + )]; + + let applied = apply_manifest(&mut table, &manifest, now); + assert_eq!(applied, 1); + let entry = table.iter_entries().next().unwrap().1.clone(); + assert_eq!(entry.ttl, None); + assert_eq!(entry.reason, BlackholeReason::RateLimit); + } + + #[test] + fn apply_manifest_does_not_overwrite_local_entries() { + let mut table = BlackholeTable::new(); + table.add_with_reason([0xAB; 16], None, BlackholeReason::Manual); + + let now = 10_000.0; + let manifest = vec![( + [0xAB; 16], + BlackholeManifestEntry { + until: Some(now + 100.0), + reason: "malformed".into(), + source: peer_id(), + }, + )]; + + let applied = apply_manifest(&mut table, &manifest, now); + assert_eq!(applied, 0); + let entry = table.iter_entries().next().unwrap().1.clone(); + assert_eq!(entry.source, None, "local source preserved"); + assert_eq!(entry.reason, BlackholeReason::Manual); + } + + #[test] + fn apply_manifest_overwrites_existing_remote_entry_from_same_source() { + let mut table = BlackholeTable::new(); + let now = 10_000.0; + table.add_from_source( + [0xCD; 16], + Some(100.0), + BlackholeReason::Malformed, + peer_id(), + now - 50.0, + ); + + let manifest = vec![( + [0xCD; 16], + BlackholeManifestEntry { + until: Some(now + 3600.0), + reason: "rate_limit".into(), + source: peer_id(), + }, + )]; + + let applied = apply_manifest(&mut table, &manifest, now); + assert_eq!(applied, 1); + let entry = table.iter_entries().next().unwrap().1.clone(); + assert_eq!(entry.reason, BlackholeReason::RateLimit); + assert!((entry.ttl.unwrap() - 3600.0).abs() < 0.01); + } + + #[test] + fn decode_rejects_bad_key_length() { + let root = Value::Map(vec![( + Value::Binary(vec![0; 8]), + encode_entry_map(None, "manual", peer_id()), + )]); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &root).unwrap(); + let err = decode_manifest(&buf).unwrap_err(); + assert_eq!(err, ManifestError::BadKey); + } + + #[test] + fn decode_rejects_missing_source() { + let root = Value::Map(vec![( + Value::Binary(vec![0; 16]), + Value::Map(vec![ + (Value::String("until".into()), Value::Nil), + ( + Value::String("reason".into()), + Value::String("manual".into()), + ), + ]), + )]); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &root).unwrap(); + let err = decode_manifest(&buf).unwrap_err(); + assert_eq!(err, ManifestError::MissingField("source")); + } + + #[test] + fn decode_accepts_integer_until_from_python() { + let root = Value::Map(vec![( + Value::Binary(vec![0xAA; 16]), + Value::Map(vec![ + ( + Value::String("source".into()), + Value::Binary(peer_id().as_bytes().to_vec()), + ), + ( + Value::String("until".into()), + Value::Integer(12345678i64.into()), + ), + ( + Value::String("reason".into()), + Value::String("manual".into()), + ), + ]), + )]); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &root).unwrap(); + let decoded = decode_manifest(&buf).unwrap(); + assert_eq!(decoded[0].1.until, Some(12345678.0)); + } + + fn now_seconds() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs_f64() + } +} diff --git a/crates/rns-transport/src/discovery/blackhole_subscriber.rs b/crates/rns-transport/src/discovery/blackhole_subscriber.rs new file mode 100644 index 0000000..9bb48fc --- /dev/null +++ b/crates/rns-transport/src/discovery/blackhole_subscriber.rs @@ -0,0 +1,189 @@ +//! Pure-data subscriber state machine for the distributed blackhole list. +//! +//! Tracks per-source "last pulled at" timestamps and decides which sources +//! are due for a refresh on the current tick. The actual link +//! establishment + `/list` request lives in the runtime layer; this module +//! is intentionally free of tokio so the due-source logic can be unit +//! tested without timers or fakes. +//! +//! Mirrors the scheduling half of Python's `BlackholeUpdater.job()` loop +//! (RNS/Discovery.py:693) with the same constants: +//! `INITIAL_WAIT=20s`, `JOB_INTERVAL=60s`, `UPDATE_INTERVAL=3600s`. + +use std::collections::HashMap; +use std::time::Duration; + +use rns_wire::types::IdentityHash; + +/// Python `BlackholeUpdater.INITIAL_WAIT` — delay before the first job tick. +pub const INITIAL_WAIT: Duration = Duration::from_secs(20); + +/// Python `BlackholeUpdater.JOB_INTERVAL` — time between scheduling sweeps. +pub const JOB_INTERVAL: Duration = Duration::from_secs(60); + +/// Python `BlackholeUpdater.UPDATE_INTERVAL` — minimum gap between +/// successful pulls from the same source (1 hour). +pub const UPDATE_INTERVAL: Duration = Duration::from_secs(60 * 60); + +/// Python `BlackholeUpdater.SOURCE_TIMEOUT` — kept here for parity but +/// currently unused; the runtime wrapper races it against the link +/// establishment / request when it lands. +pub const SOURCE_TIMEOUT: Duration = Duration::from_secs(25); + +/// Per-process subscriber state. Cheap to clone-on-snapshot via the +/// [`SubscriberState::snapshot`] helper; the runtime owner holds the +/// authoritative copy. +#[derive(Debug, Default, Clone)] +pub struct SubscriberState { + /// Unix-seconds timestamp of the most recent successful pull, keyed by + /// source identity hash. Missing key ⇒ "never pulled". + last_updates: HashMap, +} + +impl SubscriberState { + pub fn new() -> Self { + Self::default() + } + + /// Record a successful pull from `source` at `now` (Unix seconds). + pub fn mark_updated(&mut self, source: IdentityHash, now: f64) { + self.last_updates.insert(source, now); + } + + /// Clear the last-update cursor for `source`, forcing the next tick + /// to re-pull even if `UPDATE_INTERVAL` has not elapsed. Useful when + /// an operator edits `blackhole_sources` and wants an immediate + /// refresh. + pub fn forget(&mut self, source: &IdentityHash) { + self.last_updates.remove(source); + } + + /// Returns the list of sources that should be pulled on this tick, + /// given the configured source list and the current time. + /// + /// Order is deterministic (sorted by identity hash) so the runtime + /// does not accidentally thundering-herd one source ahead of another + /// after a restart. + pub fn due_sources(&self, configured: &[IdentityHash], now: f64) -> Vec { + let mut due: Vec = configured + .iter() + .copied() + .filter(|src| { + let last = self.last_updates.get(src).copied().unwrap_or(0.0); + now - last >= UPDATE_INTERVAL.as_secs_f64() + }) + .collect(); + due.sort(); + due.dedup(); + due + } + + /// Drop cursors for sources that no longer appear in `configured`. + /// Keeps the table bounded when an operator rotates their source + /// list. + pub fn prune(&mut self, configured: &[IdentityHash]) { + self.last_updates + .retain(|src, _| configured.iter().any(|c| c == src)); + } + + /// Snapshot the cursor map. Test-only surface. + #[cfg(test)] + pub fn snapshot(&self) -> HashMap { + self.last_updates.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn h(b: u8) -> IdentityHash { + [b; 16].into() + } + + #[test] + fn no_sources_means_nothing_due() { + let s = SubscriberState::new(); + assert!(s.due_sources(&[], 10_000.0).is_empty()); + } + + #[test] + fn fresh_subscribers_are_due_immediately() { + let s = SubscriberState::new(); + let sources = vec![h(0x11), h(0x22)]; + let due = s.due_sources(&sources, 10_000.0); + assert_eq!(due, vec![h(0x11), h(0x22)]); + } + + #[test] + fn due_list_is_deterministic_sorted() { + let s = SubscriberState::new(); + let sources = vec![h(0x33), h(0x11), h(0x22)]; + let due = s.due_sources(&sources, 10_000.0); + assert_eq!(due, vec![h(0x11), h(0x22), h(0x33)]); + } + + #[test] + fn mark_updated_suppresses_source_until_interval_elapses() { + let mut s = SubscriberState::new(); + s.mark_updated(h(0x11), 10_000.0); + + // 30 minutes later — still inside the 1h interval. + let due = s.due_sources(&[h(0x11)], 10_000.0 + 1_800.0); + assert!(due.is_empty()); + + // Right at the interval boundary — due again. + let due = s.due_sources(&[h(0x11)], 10_000.0 + UPDATE_INTERVAL.as_secs_f64()); + assert_eq!(due, vec![h(0x11)]); + } + + #[test] + fn mark_updated_does_not_affect_other_sources() { + let mut s = SubscriberState::new(); + s.mark_updated(h(0x11), 10_000.0); + + let due = s.due_sources(&[h(0x11), h(0x22)], 10_000.0 + 30.0); + assert_eq!(due, vec![h(0x22)]); + } + + #[test] + fn forget_forces_immediate_re_pull() { + let mut s = SubscriberState::new(); + s.mark_updated(h(0x11), 10_000.0); + s.forget(&h(0x11)); + + let due = s.due_sources(&[h(0x11)], 10_000.0 + 10.0); + assert_eq!(due, vec![h(0x11)]); + } + + #[test] + fn duplicate_source_entries_collapse() { + let s = SubscriberState::new(); + let sources = vec![h(0x11), h(0x11), h(0x22), h(0x22), h(0x22)]; + let due = s.due_sources(&sources, 10_000.0); + assert_eq!(due, vec![h(0x11), h(0x22)]); + } + + #[test] + fn prune_drops_cursors_for_removed_sources() { + let mut s = SubscriberState::new(); + s.mark_updated(h(0x11), 10_000.0); + s.mark_updated(h(0x22), 10_000.0); + + s.prune(&[h(0x22)]); + + assert!(s.snapshot().contains_key(&h(0x22))); + assert!(!s.snapshot().contains_key(&h(0x11))); + } + + #[test] + fn prune_keeps_all_cursors_when_list_matches() { + let mut s = SubscriberState::new(); + s.mark_updated(h(0x11), 10_000.0); + s.mark_updated(h(0x22), 10_000.0); + + s.prune(&[h(0x11), h(0x22)]); + + assert_eq!(s.snapshot().len(), 2); + } +} diff --git a/crates/rns-transport/src/discovery/constants.rs b/crates/rns-transport/src/discovery/constants.rs new file mode 100644 index 0000000..6e45c31 --- /dev/null +++ b/crates/rns-transport/src/discovery/constants.rs @@ -0,0 +1,93 @@ +//! Wire-level constants for on-network discovery. Values mirror +//! `RNS/Discovery.py` 1:1; do not renumber. + +/// Application name used in the discovery destination +/// `rnstransport.discovery.interface`. +pub const APP_NAME: &str = "rnstransport"; + +/// Destination aspect path used for discovery announces. +pub const DISCOVERY_ASPECTS: &[&str] = &["discovery", "interface"]; + +/// `rnstransport.discovery.interface` — joined for `aspect_filter` lookups. +pub const DISCOVERY_ASPECT_FILTER: &str = "rnstransport.discovery.interface"; + +/// Destination aspect path for the distributed blackhole list service. +pub const BLACKHOLE_ASPECTS: &[&str] = &["info", "blackhole"]; + +/// `rnstransport.info.blackhole` — joined for `aspect_filter` lookups. +pub const BLACKHOLE_ASPECT_FILTER: &str = "rnstransport.info.blackhole"; + +/// Announce job tick (seconds). Matches Python `InterfaceAnnouncer.JOB_INTERVAL`. +pub const ANNOUNCE_JOB_INTERVAL_SECS: u64 = 60; + +/// Default stamp-value requirement used by both sender (when an interface +/// leaves `discovery_stamp_value` unset) and receiver. Matches Python +/// `InterfaceAnnouncer.DEFAULT_STAMP_VALUE`. +pub const DEFAULT_STAMP_VALUE: u8 = 14; + +/// Rounds used when deriving the stamp workblock. Matches Python +/// `InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS`. +pub const WORKBLOCK_EXPAND_ROUNDS: u32 = 20; + +/// Fixed stamp length (bytes) emitted by the LXMF stamper. Matches Python +/// `LXStamper.STAMP_SIZE`. +pub const STAMP_SIZE: usize = 32; + +/// Discovery app_data is prefixed with one flags byte. +pub const FLAG_SIGNED: u8 = 0b0000_0001; +pub const FLAG_ENCRYPTED: u8 = 0b0000_0010; + +/// Interface types that announce themselves via discovery. Mirrors +/// `InterfaceAnnouncer.DISCOVERABLE_INTERFACE_TYPES`. +pub const DISCOVERABLE_INTERFACE_TYPES: &[&str] = &[ + "BackboneInterface", + "TCPServerInterface", + "TCPClientInterface", + "RNodeInterface", + "WeaveInterface", + "I2PInterface", + "KISSInterface", +]; + +/// Interface types eligible for auto-connect. Mirrors +/// `InterfaceDiscovery.AUTOCONNECT_TYPES`. +pub const AUTOCONNECT_INTERFACE_TYPES: &[&str] = &["BackboneInterface", "TCPServerInterface"]; + +/// Freshness tiers for discovered interfaces (seconds). Match +/// `InterfaceDiscovery.THRESHOLD_*`. +pub const THRESHOLD_UNKNOWN_SECS: u64 = 24 * 60 * 60; +pub const THRESHOLD_STALE_SECS: u64 = 3 * 24 * 60 * 60; +pub const THRESHOLD_REMOVE_SECS: u64 = 7 * 24 * 60 * 60; + +/// Monitor-job cadence and detach threshold (Python +/// `InterfaceDiscovery.MONITOR_INTERVAL` / `DETACH_THRESHOLD`). +pub const MONITOR_INTERVAL_SECS: u64 = 5; +pub const DETACH_THRESHOLD_TICKS: u64 = 12; + +/// Blackhole updater timings (`BlackholeUpdater.*`). +pub const BLACKHOLE_INITIAL_WAIT_SECS: u64 = 20; +pub const BLACKHOLE_JOB_INTERVAL_SECS: u64 = 60; +pub const BLACKHOLE_UPDATE_INTERVAL_SECS: u64 = 60 * 60; +pub const BLACKHOLE_SOURCE_TIMEOUT_SECS: u64 = 25; + +/// msgpack map keys — byte values, must match Python `Discovery.py` exactly. +/// These ride on the wire; renumbering is a breaking protocol change. +pub mod key { + pub const NAME: u8 = 0xFF; + pub const TRANSPORT_ID: u8 = 0xFE; + pub const INTERFACE_TYPE: u8 = 0x00; + pub const TRANSPORT: u8 = 0x01; + pub const REACHABLE_ON: u8 = 0x02; + pub const LATITUDE: u8 = 0x03; + pub const LONGITUDE: u8 = 0x04; + pub const HEIGHT: u8 = 0x05; + pub const PORT: u8 = 0x06; + pub const IFAC_NETNAME: u8 = 0x07; + pub const IFAC_NETKEY: u8 = 0x08; + pub const FREQUENCY: u8 = 0x09; + pub const BANDWIDTH: u8 = 0x0A; + pub const SPREADING_FACTOR: u8 = 0x0B; + pub const CODING_RATE: u8 = 0x0C; + pub const MODULATION: u8 = 0x0D; + pub const CHANNEL: u8 = 0x0E; +} diff --git a/crates/rns-transport/src/discovery/mod.rs b/crates/rns-transport/src/discovery/mod.rs new file mode 100644 index 0000000..9b282bd --- /dev/null +++ b/crates/rns-transport/src/discovery/mod.rs @@ -0,0 +1,37 @@ +//! On-network interface discovery — Rust port of Python `RNS/Discovery.py`. +//! +//! The announcer periodically posts PoW-stamped discovery announces on +//! `rnstransport.discovery.interface`. The receiver validates stamps, stores +//! learned interfaces, and (optionally) auto-connects to eligible transport +//! nodes. A separate blackhole updater fetches blackhole manifests from +//! configured sources via link request. +//! +//! # Stamper indirection +//! +//! Python imports `LXMF.LXStamper` at startup. rsReticulum avoids an upward +//! dependency on rsLXMF, so discovery takes a [`DiscoveryStamper`] trait object; +//! the concrete implementation lives in `lxmf-core::discovery_stamper`. +//! Without a stamper installed, discovery is silent. + +pub mod announcer; +pub mod app_data; +pub mod blackhole_manifest; +pub mod blackhole_subscriber; +pub mod constants; +pub mod receiver; +pub mod stamper; +pub mod storage; + +pub use announcer::{AnnounceRequest, Announcer, DiscoveryInterfaceConfig, SkipReason}; +pub use blackhole_manifest::{ + BlackholeManifestEntry, ManifestError, apply_manifest, build_local_manifest, decode_manifest, +}; +pub use blackhole_subscriber::{ + INITIAL_WAIT as BLACKHOLE_INITIAL_WAIT, JOB_INTERVAL as BLACKHOLE_JOB_INTERVAL, + SOURCE_TIMEOUT as BLACKHOLE_SOURCE_TIMEOUT, SubscriberState as BlackholeSubscriberState, + UPDATE_INTERVAL as BLACKHOLE_UPDATE_INTERVAL, +}; +pub use constants::*; +pub use receiver::{DiscoveryDecryptor, Outcome, Reason, ReceiverConfig}; +pub use stamper::{DiscoveryStamper, NullStamper}; +pub use storage::{DiscoveredInterface, DiscoveryStatus, DiscoveryStore, discovery_hash}; diff --git a/crates/rns-transport/src/discovery/receiver.rs b/crates/rns-transport/src/discovery/receiver.rs new file mode 100644 index 0000000..517a83e --- /dev/null +++ b/crates/rns-transport/src/discovery/receiver.rs @@ -0,0 +1,601 @@ +//! Inbound discovery announce handler. +//! +//! Bridges [`AnnounceHandlerEvent`] (the transport-actor callback type) to +//! the discovery pipeline: +//! +//! 1. split the `app_data` payload into flags / body / stamp, +//! 2. (optionally) decrypt the body using a shared-network decryptor, +//! 3. validate the stamp against a [`DiscoveryStamper`], +//! 4. decode the info map, filter by `discovery_sources` if configured, +//! 5. upsert into [`DiscoveryStore`] and notify any observer. +//! +//! Mirrors Python `Discovery.InterfaceAnnounceHandler.received_announce`. +//! Runs as a dedicated Tokio task so slow stamp validation does not stall +//! the transport actor loop. + +use std::sync::Arc; + +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tracing::{debug, trace, warn}; + +use crate::messages::AnnounceHandlerEvent; + +use super::app_data::{self, DiscoveryInfo}; +use super::constants::FLAG_ENCRYPTED; +use super::stamper::DiscoveryStamper; +use super::storage::{DiscoveredInterface, DiscoveryStore}; + +/// Pluggable decryptor for discovery announces whose flags byte has +/// `FLAG_ENCRYPTED` set. The concrete impl wraps the `network_identity` +/// (Python `RNS.Identity.decrypt`). +/// +/// Returning `None` means the ciphertext could not be decrypted with the +/// held identity — the receiver treats that as "not for us" and drops the +/// announce silently. +pub trait DiscoveryDecryptor: Send + Sync { + fn decrypt(&self, ciphertext: &[u8]) -> Option>; +} + +/// Configuration passed to [`spawn`]. Cheap to clone into the task. +pub struct ReceiverConfig { + pub stamper: Arc, + pub store: Arc, + /// Minimum stamp value required to accept an announce. Mirrors Python + /// `discover_interfaces_required_value`. + pub required_value: u8, + /// When `Some`, only announces whose source transport-id is in the + /// list are accepted (Python `interface_discovery_sources`). `None` + /// accepts any stamped source. + pub discovery_sources: Option>, + /// Optional decryptor for `FLAG_ENCRYPTED` announces. `None` means + /// encrypted announces are silently ignored. + pub decryptor: Option>, + /// Optional observer channel — every successful upsert is published. + /// The sender is never blocked (uses `try_send`), so a slow consumer + /// drops events rather than stalling the receiver. + pub observer: Option>, +} + +/// Result of a single announce classification. Returned by +/// [`process_event`] so tests can assert on decisions without needing a +/// live tokio task. +#[derive(Debug, PartialEq)] +pub enum Outcome { + /// Announce accepted and upserted. + Accepted, + /// Announce rejected before upsert. `Reason` carries the why. + Rejected(Reason), +} + +#[derive(Debug, PartialEq)] +pub enum Reason { + /// No `app_data` on the announce — discovery announces always carry one. + MissingAppData, + /// `app_data` too small to even contain a flags byte + stamp. + Malformed, + /// `FLAG_ENCRYPTED` set without a configured decryptor. + EncryptedWithoutKey, + /// Decryptor returned `None` (ciphertext not addressed to us). + DecryptFailed, + /// Stamp did not meet the required value. + StampInvalid, + /// Info map did not decode. + DecodeFailed, + /// Source (transport_id) not in the configured discovery_sources list. + UnauthorizedSource, + /// Upsert into the on-disk store failed (io error). + StorageFailed, +} + +impl ReceiverConfig { + /// Classify a single announce event, upsert on accept, emit on observer. + /// + /// Synchronous so unit tests can drive it without a task. Returns an + /// [`Outcome`] describing the decision. + pub fn process_event(&self, event: &AnnounceHandlerEvent) -> Outcome { + let Some(raw) = event.app_data.as_ref() else { + return Outcome::Rejected(Reason::MissingAppData); + }; + + let (flags, body) = match app_data::split_flags(raw) { + Ok(p) => p, + Err(_) => return Outcome::Rejected(Reason::Malformed), + }; + + // Decrypt body if FLAG_ENCRYPTED set. We own the bytes once we + // decrypt, but keep a borrow when unencrypted. + let decrypted: Vec; + let working: &[u8] = if flags & FLAG_ENCRYPTED != 0 { + let Some(decryptor) = self.decryptor.as_ref() else { + return Outcome::Rejected(Reason::EncryptedWithoutKey); + }; + match decryptor.decrypt(body) { + Some(pt) => { + decrypted = pt; + &decrypted + } + None => return Outcome::Rejected(Reason::DecryptFailed), + } + } else { + body + }; + + let (packed_info, stamp) = match app_data::split_stamp(working) { + Ok(p) => p, + Err(_) => return Outcome::Rejected(Reason::Malformed), + }; + + let infohash = rns_crypto::sha::full_hash(packed_info); + if !self.stamper.valid(&infohash, stamp, self.required_value) { + return Outcome::Rejected(Reason::StampInvalid); + } + + let info: DiscoveryInfo = match app_data::decode_info(packed_info) { + Ok(i) => i, + Err(err) => { + trace!(?err, "discovery: info decode failed"); + return Outcome::Rejected(Reason::DecodeFailed); + } + }; + + let announced_identity = event.identity_hash.unwrap_or(info.transport_id); + if let Some(sources) = self.discovery_sources.as_ref() + && !sources.iter().any(|s| s == &announced_identity) + { + return Outcome::Rejected(Reason::UnauthorizedSource); + } + + let stamp_value = self.stamper.value(&infohash, stamp); + let now = now_unix(); + let record = DiscoveredInterface { + info, + network_id: announced_identity, + hops: event.hops, + stamp_value, + stamp: stamp.to_vec(), + discovered: now, + last_heard: now, + heard_count: 0, // overridden by upsert merge + status: None, + }; + + if let Err(err) = self.store.upsert(record.clone()) { + warn!(?err, "discovery: storage upsert failed"); + return Outcome::Rejected(Reason::StorageFailed); + } + + if let Some(obs) = self.observer.as_ref() { + // `try_send` keeps the receiver non-blocking; dropped events + // are not a correctness bug — observer is advisory. + let _ = obs.try_send(record); + } + + Outcome::Accepted + } +} + +/// Spawn the receiver task. Returns the sender to register with +/// `TransportMessage::RegisterAnnounceHandler { aspect_filter: +/// Some("rnstransport.discovery.interface"), callback_tx }` and the +/// [`JoinHandle`] for shutdown. +pub fn spawn(config: ReceiverConfig) -> (JoinHandle<()>, mpsc::Sender) { + let (tx, mut rx) = mpsc::channel::(128); + let handle = tokio::spawn(async move { + while let Some(event) = rx.recv().await { + let outcome = config.process_event(&event); + match outcome { + Outcome::Accepted => debug!( + dest = %hex::encode(event.destination_hash), + hops = event.hops, + "discovery announce accepted" + ), + Outcome::Rejected(ref reason) => trace!( + dest = %hex::encode(event.destination_hash), + ?reason, + "discovery announce rejected" + ), + } + } + debug!("discovery receiver task exiting"); + }); + (handle, tx) +} + +fn now_unix() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::discovery::app_data::{Encoded, encode_info}; + use crate::discovery::constants::STAMP_SIZE; + + /// Trivial stamper: `generate` returns a zero-filled stamp; `valid` + /// accepts iff the caller's stamp matches `generate`. Used to drive + /// receiver tests without pulling LXStamper into rns-transport. + struct MockStamper { + ok_stamp: Vec, + value: u8, + } + + impl MockStamper { + fn new(stamp: Vec, value: u8) -> Self { + assert_eq!(stamp.len(), STAMP_SIZE); + Self { + ok_stamp: stamp, + value, + } + } + } + + impl DiscoveryStamper for MockStamper { + fn generate(&self, _ih: &[u8; 32], _tv: u8) -> Option> { + Some(self.ok_stamp.clone()) + } + fn value(&self, _ih: &[u8; 32], _s: &[u8]) -> u8 { + self.value + } + fn valid(&self, _ih: &[u8; 32], stamp: &[u8], required: u8) -> bool { + self.value >= required && stamp == self.ok_stamp.as_slice() + } + } + + struct XorDecryptor; + impl DiscoveryDecryptor for XorDecryptor { + fn decrypt(&self, ct: &[u8]) -> Option> { + Some(ct.iter().map(|b| b ^ 0xFF).collect()) + } + } + + struct FailingDecryptor; + impl DiscoveryDecryptor for FailingDecryptor { + fn decrypt(&self, _ct: &[u8]) -> Option> { + None + } + } + + fn sample_info() -> DiscoveryInfo { + DiscoveryInfo { + name: "unit-test-iface".into(), + transport_id: [0x55; 16], + interface_type: "BackboneInterface".into(), + transport_enabled: true, + latitude: 1.0, + longitude: 2.0, + height: 3.0, + port: Some(4965), + reachable_on: Some("127.0.0.1".into()), + ..Default::default() + } + } + + fn stamped_blob(info: &DiscoveryInfo, stamp: &[u8]) -> (Vec, [u8; 32]) { + let Encoded { packed, infohash } = encode_info(info).unwrap(); + let mut body = packed.clone(); + body.extend_from_slice(stamp); + let mut out = Vec::with_capacity(1 + body.len()); + out.push(0); // flags + out.extend_from_slice(&body); + (out, infohash) + } + + fn encrypted_blob(info: &DiscoveryInfo, stamp: &[u8]) -> (Vec, [u8; 32]) { + let Encoded { packed, infohash } = encode_info(info).unwrap(); + let blob = Encoded { packed, infohash } + .assemble( + stamp, + true, + false, + Some(&|pt: &[u8]| Some(pt.iter().map(|b| b ^ 0xFF).collect())), + ) + .unwrap(); + (blob, infohash) + } + + fn tmpdir(tag: &str) -> std::path::PathBuf { + let p = std::env::temp_dir().join(format!( + "reticulum_rs_discovery_recv_{}_{}_{}", + tag, + std::process::id(), + rand::random::() + )); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).unwrap(); + p + } + + fn make_cfg( + stamper: Arc, + store: Arc, + sources: Option>, + decryptor: Option>, + ) -> ReceiverConfig { + ReceiverConfig { + stamper, + store, + required_value: 14, + discovery_sources: sources, + decryptor, + observer: None, + } + } + + fn event_with(app_data: Vec) -> AnnounceHandlerEvent { + AnnounceHandlerEvent { + destination_hash: [0xAA; 16], + identity_hash: Some([0x11; 16]), + announce_packet_hash: [0x22; 32], + is_path_response: false, + hops: 3, + app_data: Some(app_data), + public_key: None, + ratchet: None, + name_hash: [0u8; 10], + } + } + + #[test] + fn accepts_valid_unencrypted_announce() { + let dir = tmpdir("accept"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let info = sample_info(); + let (blob, _ih) = stamped_blob(&info, &stamp); + + let cfg = make_cfg(stamper, store.clone(), None, None); + let event = event_with(blob); + assert_eq!(cfg.process_event(&event), Outcome::Accepted); + + let listed = store.list(None).unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].info, info); + assert_eq!(listed[0].stamp_value, 20); + assert_eq!(listed[0].hops, 3); + assert_eq!(listed[0].network_id, [0x11; 16]); + } + + #[test] + fn rejects_invalid_stamp() { + let dir = tmpdir("badstamp"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let good = vec![0xAB; STAMP_SIZE]; + let bad = vec![0xCD; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(good, 20)); + let info = sample_info(); + let (blob, _) = stamped_blob(&info, &bad); + + let cfg = make_cfg(stamper, store.clone(), None, None); + assert_eq!( + cfg.process_event(&event_with(blob)), + Outcome::Rejected(Reason::StampInvalid) + ); + assert!(store.list(None).unwrap().is_empty()); + } + + #[test] + fn rejects_below_required_value() { + let dir = tmpdir("lowvalue"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + // value only 5, required 14 + let stamper = Arc::new(MockStamper::new(stamp.clone(), 5)); + let info = sample_info(); + let (blob, _) = stamped_blob(&info, &stamp); + + let cfg = make_cfg(stamper, store.clone(), None, None); + assert_eq!( + cfg.process_event(&event_with(blob)), + Outcome::Rejected(Reason::StampInvalid) + ); + } + + #[test] + fn rejects_missing_app_data() { + let dir = tmpdir("noapp"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamper = Arc::new(MockStamper::new(vec![0; STAMP_SIZE], 20)); + let cfg = make_cfg(stamper, store.clone(), None, None); + + let event = AnnounceHandlerEvent { + destination_hash: [0; 16], + identity_hash: None, + announce_packet_hash: [0; 32], + is_path_response: false, + hops: 0, + app_data: None, + public_key: None, + ratchet: None, + name_hash: [0u8; 10], + }; + assert_eq!( + cfg.process_event(&event), + Outcome::Rejected(Reason::MissingAppData) + ); + } + + #[test] + fn rejects_malformed_payload() { + let dir = tmpdir("malformed"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamper = Arc::new(MockStamper::new(vec![0; STAMP_SIZE], 20)); + let cfg = make_cfg(stamper, store.clone(), None, None); + + // Flag byte present but body too small for a stamp. + let mut tiny = vec![0u8; 8]; + tiny[0] = 0; + assert_eq!( + cfg.process_event(&event_with(tiny)), + Outcome::Rejected(Reason::Malformed) + ); + } + + #[test] + fn rejects_encrypted_without_decryptor() { + let dir = tmpdir("encnokey"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let info = sample_info(); + let (blob, _) = encrypted_blob(&info, &stamp); + + let cfg = make_cfg(stamper, store.clone(), None, None); + assert_eq!( + cfg.process_event(&event_with(blob)), + Outcome::Rejected(Reason::EncryptedWithoutKey) + ); + } + + #[test] + fn rejects_decrypt_failure() { + let dir = tmpdir("decfail"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let info = sample_info(); + let (blob, _) = encrypted_blob(&info, &stamp); + + let cfg = make_cfg( + stamper, + store.clone(), + None, + Some(Arc::new(FailingDecryptor)), + ); + assert_eq!( + cfg.process_event(&event_with(blob)), + Outcome::Rejected(Reason::DecryptFailed) + ); + } + + #[test] + fn accepts_encrypted_with_decryptor() { + let dir = tmpdir("encok"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let info = sample_info(); + let (blob, _) = encrypted_blob(&info, &stamp); + + let cfg = make_cfg(stamper, store.clone(), None, Some(Arc::new(XorDecryptor))); + assert_eq!(cfg.process_event(&event_with(blob)), Outcome::Accepted); + assert_eq!(store.list(None).unwrap().len(), 1); + } + + #[test] + fn rejects_unauthorized_source() { + let dir = tmpdir("unauth"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let mut info = sample_info(); + info.transport_id = [0x55; 16]; + let (blob, _) = stamped_blob(&info, &stamp); + + // Allow list without our source. + let sources = vec![[0x77; 16]]; + let cfg = make_cfg(stamper, store.clone(), Some(sources), None); + assert_eq!( + cfg.process_event(&event_with(blob)), + Outcome::Rejected(Reason::UnauthorizedSource) + ); + } + + #[test] + fn accepts_authorized_source() { + let dir = tmpdir("auth"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let mut info = sample_info(); + info.transport_id = [0x55; 16]; + let (blob, _) = stamped_blob(&info, &stamp); + + let sources = vec![[0x11; 16]]; + let cfg = make_cfg(stamper, store.clone(), Some(sources), None); + assert_eq!(cfg.process_event(&event_with(blob)), Outcome::Accepted); + } + + #[test] + fn rejects_decode_failure() { + let dir = tmpdir("decode"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + // Stamper validates ANY stamp for this test; feed junk bytes as the + // "info" so the decoder errors. + struct PermissiveStamper(Vec); + impl DiscoveryStamper for PermissiveStamper { + fn generate(&self, _: &[u8; 32], _: u8) -> Option> { + Some(self.0.clone()) + } + fn value(&self, _: &[u8; 32], _: &[u8]) -> u8 { + 20 + } + fn valid(&self, _: &[u8; 32], _: &[u8], _: u8) -> bool { + true + } + } + let stamper = Arc::new(PermissiveStamper(stamp.clone())); + + // Flags byte + junk info + stamp. + let mut blob = vec![0u8; 1]; + blob.extend_from_slice(b"not-valid-msgpack"); + blob.extend_from_slice(&stamp); + + let cfg = make_cfg(stamper, store.clone(), None, None); + assert_eq!( + cfg.process_event(&event_with(blob)), + Outcome::Rejected(Reason::DecodeFailed) + ); + } + + #[test] + fn observer_receives_on_accept() { + let dir = tmpdir("obs"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let info = sample_info(); + let (blob, _) = stamped_blob(&info, &stamp); + + let (obs_tx, mut obs_rx) = mpsc::channel::(4); + let cfg = ReceiverConfig { + stamper, + store: store.clone(), + required_value: 14, + discovery_sources: None, + decryptor: None, + observer: Some(obs_tx), + }; + assert_eq!(cfg.process_event(&event_with(blob)), Outcome::Accepted); + + let received = obs_rx.try_recv().expect("observer should receive"); + assert_eq!(received.info.name, "unit-test-iface"); + } + + #[tokio::test] + async fn spawn_round_trip() { + let dir = tmpdir("spawn"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let info = sample_info(); + let (blob, _) = stamped_blob(&info, &stamp); + + let cfg = make_cfg(stamper, store.clone(), None, None); + let (handle, tx) = spawn(cfg); + + tx.send(event_with(blob)).await.unwrap(); + // Drop tx so the task exits cleanly. + drop(tx); + // Wait for the task to complete processing + exit. + handle.await.unwrap(); + + let listed = store.list(None).unwrap(); + assert_eq!(listed.len(), 1); + } +} diff --git a/crates/rns-transport/src/discovery/stamper.rs b/crates/rns-transport/src/discovery/stamper.rs new file mode 100644 index 0000000..6871bcf --- /dev/null +++ b/crates/rns-transport/src/discovery/stamper.rs @@ -0,0 +1,50 @@ +//! Pluggable proof-of-work stamper for discovery announces. +//! +//! Python `RNS.Discovery.InterfaceAnnouncer` imports `LXMF.LXStamper`. +//! rsReticulum avoids an upward dependency on rsLXMF, so discovery accepts a +//! trait object. The concrete implementation lives in +//! `lxmf-core::discovery_stamper::LxmfDiscoveryStamper` and is wired at startup +//! by the embedding application. + +/// Minimal PoW stamp interface consumed by the discovery subsystem. +/// +/// A stamper must be **deterministic for a given `(infohash, target_value)` +/// pair** and independent across calls — the announcer caches its last +/// successful stamp per info-hash and reuses it until the payload changes. +pub trait DiscoveryStamper: Send + Sync { + /// Generate a `STAMP_SIZE`-byte stamp whose SHA-256-derived value meets + /// or exceeds `target_value` (number of leading zero bits, as in the + /// Python `LXStamper.generate_stamp` contract). + /// + /// Returns `None` if generation was cancelled or failed. + fn generate(&self, infohash: &[u8; 32], target_value: u8) -> Option>; + + /// Compute the stamp's current value (Python `LXStamper.stamp_value`). + /// Used by the receiver to log the learned stamp quality. + fn value(&self, infohash: &[u8; 32], stamp: &[u8]) -> u8; + + /// Validate a stamp against `required_value` (Python + /// `LXStamper.stamp_valid`). Returns true iff the stamp meets the bar. + fn valid(&self, infohash: &[u8; 32], stamp: &[u8], required_value: u8) -> bool; +} + +/// A no-op stamper used when on-network discovery is not enabled. +/// +/// Never generates a stamp — so the announcer short-circuits each tick and +/// the receiver rejects every inbound stamp. This keeps discovery silent +/// when no stamper is installed (Python panics in this case; we don't). +pub struct NullStamper; + +impl DiscoveryStamper for NullStamper { + fn generate(&self, _infohash: &[u8; 32], _target_value: u8) -> Option> { + None + } + + fn value(&self, _infohash: &[u8; 32], _stamp: &[u8]) -> u8 { + 0 + } + + fn valid(&self, _infohash: &[u8; 32], _stamp: &[u8], _required_value: u8) -> bool { + false + } +} diff --git a/crates/rns-transport/src/discovery/storage.rs b/crates/rns-transport/src/discovery/storage.rs new file mode 100644 index 0000000..d1948fa --- /dev/null +++ b/crates/rns-transport/src/discovery/storage.rs @@ -0,0 +1,599 @@ +//! Persistence for discovered interfaces — one msgpack file per learned +//! interface named after `discovery_hash` hex (matches Python `InterfaceDiscovery`). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rmpv::Value; +use thiserror::Error; + +use super::app_data::DiscoveryInfo; +use super::constants::{ + STAMP_SIZE, THRESHOLD_REMOVE_SECS, THRESHOLD_STALE_SECS, THRESHOLD_UNKNOWN_SECS, +}; + +/// Freshness status for a learned interface. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DiscoveryStatus { + Stale, + Unknown, + Available, +} + +impl DiscoveryStatus { + /// Numeric rank for sorting (higher = better). + pub fn code(self) -> u32 { + match self { + Self::Stale => 0, + Self::Unknown => 100, + Self::Available => 1000, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Stale => "stale", + Self::Unknown => "unknown", + Self::Available => "available", + } + } +} + +/// A single learned interface. +#[derive(Debug, Clone, PartialEq)] +pub struct DiscoveredInterface { + pub info: DiscoveryInfo, + /// Source transport ID — lets a reader filter by `interface_discovery_sources`. + pub network_id: [u8; 16], + /// Distance hint when the announce was received (0 if unknown). + pub hops: u8, + /// Stamp value observed on the latest announce. + pub stamp_value: u8, + /// The actual stamp bytes last observed (useful for diagnostics). + pub stamp: Vec, + /// Unix seconds — first time this interface was learned. + pub discovered: u64, + /// Unix seconds — most recent announce. + pub last_heard: u64, + /// How many announces contributed to this record (includes the first). + pub heard_count: u64, + /// Cached status at read time (None until classified). + pub status: Option, +} + +impl DiscoveredInterface { + /// Filename stem on disk: hex of `discovery_hash`. + pub fn discovery_hash(&self) -> [u8; 32] { + discovery_hash(&self.info.transport_id, &self.info.name) + } + + /// Hex-form of [`Self::discovery_hash`] — used as the on-disk filename. + pub fn filename(&self) -> String { + hex::encode(self.discovery_hash()) + } +} + +/// `SHA-256(transport_id_hex_ascii || name_utf8)`. +pub fn discovery_hash(transport_id: &[u8; 16], name: &str) -> [u8; 32] { + let mut material = String::with_capacity(32 + name.len()); + material.push_str(&hex::encode(transport_id)); + material.push_str(name); + rns_crypto::sha::full_hash(material.as_bytes()) +} + +#[derive(Debug, Error)] +pub enum StorageError { + #[error("io: {0}")] + Io(#[from] std::io::Error), + #[error("msgpack decode: {0}")] + Decode(String), + #[error("msgpack encode: {0}")] + Encode(String), + #[error("unexpected top-level msgpack shape")] + Shape, +} + +/// Persistent store rooted at `/discovery/interfaces/`. +/// +/// Writes atomically via a `.tmp` sidecar + rename. +pub struct DiscoveryStore { + root: PathBuf, +} + +impl DiscoveryStore { + /// Open (and create if absent) the store under `storage_root`. + pub fn open(storage_root: &Path) -> Result { + let root = storage_root.join("discovery").join("interfaces"); + std::fs::create_dir_all(&root)?; + Ok(Self { root }) + } + + /// Directory containing the per-interface files. + pub fn root(&self) -> &Path { + &self.root + } + + /// Write or update; existing `discovered` + `heard_count` are merged in. + pub fn upsert(&self, mut record: DiscoveredInterface) -> Result<(), StorageError> { + let path = self.root.join(record.filename()); + + if let Ok(existing) = self.load_raw(&path) { + record.discovered = existing.discovered; + record.heard_count = existing.heard_count.saturating_add(1); + } else { + record.heard_count = 1; + } + + let tmp = path.with_extension("tmp"); + let encoded = encode_record(&record)?; + std::fs::write(&tmp, encoded)?; + match std::fs::rename(&tmp, &path) { + Ok(()) => Ok(()), + Err(e) => { + let _ = std::fs::remove_file(&tmp); + Err(e.into()) + } + } + } + + /// Remove a single record; returns `true` if one was present. + pub fn remove(&self, transport_id: &[u8; 16], name: &str) -> Result { + let fname = hex::encode(discovery_hash(transport_id, name)); + let path = self.root.join(fname); + match std::fs::remove_file(&path) { + Ok(()) => Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e.into()), + } + } + + /// List records sorted desc by `(status_code, stamp_value, last_heard)`. + /// Expired entries are culled from disk; `discovery_sources` (when set) + /// filters out records whose `network_id` is not in the set. + pub fn list( + &self, + discovery_sources: Option<&[[u8; 16]]>, + ) -> Result, StorageError> { + let now = unix_now(); + let mut out: Vec = Vec::new(); + + let read = match std::fs::read_dir(&self.root) { + Ok(r) => r, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out), + Err(e) => return Err(e.into()), + }; + + for entry in read { + let entry = entry?; + let path = entry.path(); + // Skip .tmp sidecars and anything non-file. + if !path.is_file() { + continue; + } + if path.extension().is_some() { + continue; + } + let rec = match self.load_raw(&path) { + Ok(r) => r, + Err(_) => { + // Corrupt file: remove so future reads don't keep failing. + let _ = std::fs::remove_file(&path); + continue; + } + }; + + let heard_delta = now.saturating_sub(rec.last_heard); + let mut should_remove = heard_delta > THRESHOLD_REMOVE_SECS; + if let Some(sources) = discovery_sources + && !sources.iter().any(|s| s == &rec.network_id) + { + should_remove = true; + } + if should_remove { + let _ = std::fs::remove_file(&path); + continue; + } + + let status = classify(heard_delta); + let mut enriched = rec; + enriched.status = Some(status); + out.push(enriched); + } + + out.sort_by(|a, b| { + let sa = a.status.map(DiscoveryStatus::code).unwrap_or(0); + let sb = b.status.map(DiscoveryStatus::code).unwrap_or(0); + sb.cmp(&sa) + .then(b.stamp_value.cmp(&a.stamp_value)) + .then(b.last_heard.cmp(&a.last_heard)) + }); + + Ok(out) + } + + fn load_raw(&self, path: &Path) -> Result { + let bytes = std::fs::read(path)?; + decode_record(&bytes) + } +} + +/// Classify a (now - last_heard) delta into a status bucket. Exposed so +/// callers that already have a record in hand can avoid a re-read. +pub fn classify(heard_delta_secs: u64) -> DiscoveryStatus { + if heard_delta_secs > THRESHOLD_STALE_SECS { + DiscoveryStatus::Stale + } else if heard_delta_secs > THRESHOLD_UNKNOWN_SECS { + DiscoveryStatus::Unknown + } else { + DiscoveryStatus::Available + } +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +// On-disk msgpack format mirrors Python's key schema for interop. + +fn encode_record(rec: &DiscoveredInterface) -> Result, StorageError> { + let mut map: Vec<(Value, Value)> = Vec::new(); + + let i = &rec.info; + map.push((s("type"), Value::from(i.interface_type.clone()))); + map.push((s("transport"), Value::from(i.transport_enabled))); + map.push((s("name"), Value::from(i.name.clone()))); + map.push((s("transport_id"), Value::from(hex::encode(i.transport_id)))); + map.push((s("network_id"), Value::from(hex::encode(rec.network_id)))); + map.push((s("hops"), Value::from(rec.hops))); + map.push((s("value"), Value::from(rec.stamp_value))); + map.push((s("stamp"), Value::Binary(rec.stamp.clone()))); + map.push((s("latitude"), Value::F64(i.latitude))); + map.push((s("longitude"), Value::F64(i.longitude))); + map.push((s("height"), Value::F64(i.height))); + if let Some(addr) = &i.reachable_on { + map.push((s("reachable_on"), Value::from(addr.clone()))); + } + if let Some(p) = i.port { + map.push((s("port"), Value::from(p))); + } + if let Some(n) = &i.ifac_netname { + map.push((s("ifac_netname"), Value::from(n.clone()))); + } + if let Some(k) = &i.ifac_netkey { + map.push((s("ifac_netkey"), Value::from(k.clone()))); + } + if let Some(f) = i.frequency { + map.push((s("frequency"), Value::from(f))); + } + if let Some(b) = i.bandwidth { + map.push((s("bandwidth"), Value::from(b))); + } + if let Some(sf) = i.spreading_factor { + map.push((s("sf"), Value::from(sf))); + } + if let Some(cr) = i.coding_rate { + map.push((s("cr"), Value::from(cr))); + } + if let Some(m) = &i.modulation { + map.push((s("modulation"), Value::from(m.clone()))); + } + if let Some(ch) = i.channel { + map.push((s("channel"), Value::from(ch))); + } + map.push((s("discovered"), Value::from(rec.discovered))); + map.push((s("last_heard"), Value::from(rec.last_heard))); + map.push((s("heard_count"), Value::from(rec.heard_count))); + + let value = Value::Map(map); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &value).map_err(|e| StorageError::Encode(e.to_string()))?; + Ok(buf) +} + +fn decode_record(bytes: &[u8]) -> Result { + let mut cur = std::io::Cursor::new(bytes); + let value = + rmpv::decode::read_value(&mut cur).map_err(|e| StorageError::Decode(e.to_string()))?; + let map = match value { + Value::Map(m) => m, + _ => return Err(StorageError::Shape), + }; + + let mut lookup: HashMap = HashMap::new(); + for (k, v) in map { + if let Some(key) = match &k { + Value::String(s) => s.as_str().map(str::to_owned), + _ => None, + } { + lookup.insert(key, v); + } + } + + let info = DiscoveryInfo { + interface_type: str_or_default(&lookup, "type"), + transport_enabled: bool_or_default(&lookup, "transport"), + transport_id: hex16(&lookup, "transport_id").unwrap_or([0; 16]), + name: str_or_default(&lookup, "name"), + reachable_on: str_opt(&lookup, "reachable_on"), + latitude: f64_or_default(&lookup, "latitude"), + longitude: f64_or_default(&lookup, "longitude"), + height: f64_or_default(&lookup, "height"), + port: u64_opt(&lookup, "port").map(|n| n.min(u16::MAX as u64) as u16), + ifac_netname: str_opt(&lookup, "ifac_netname"), + ifac_netkey: str_opt(&lookup, "ifac_netkey"), + frequency: u64_opt(&lookup, "frequency"), + bandwidth: u64_opt(&lookup, "bandwidth"), + spreading_factor: u64_opt(&lookup, "sf").map(|n| n.min(u8::MAX as u64) as u8), + coding_rate: u64_opt(&lookup, "cr").map(|n| n.min(u8::MAX as u64) as u8), + modulation: str_opt(&lookup, "modulation"), + channel: u64_opt(&lookup, "channel").map(|n| n.min(u16::MAX as u64) as u16), + }; + + let stamp = lookup + .get("stamp") + .and_then(|v| match v { + Value::Binary(b) => Some(b.clone()), + _ => None, + }) + .unwrap_or_else(|| vec![0; STAMP_SIZE]); + + Ok(DiscoveredInterface { + info, + network_id: hex16(&lookup, "network_id").unwrap_or([0; 16]), + hops: u64_opt(&lookup, "hops").unwrap_or(0).min(u8::MAX as u64) as u8, + stamp_value: u64_opt(&lookup, "value").unwrap_or(0).min(u8::MAX as u64) as u8, + stamp, + discovered: u64_opt(&lookup, "discovered").unwrap_or(0), + last_heard: u64_opt(&lookup, "last_heard").unwrap_or(0), + heard_count: u64_opt(&lookup, "heard_count").unwrap_or(0), + status: None, + }) +} + +fn s(x: &str) -> Value { + Value::from(x) +} + +fn str_or_default(lookup: &HashMap, k: &str) -> String { + match lookup.get(k) { + Some(Value::String(s)) => s.as_str().unwrap_or("").to_string(), + Some(Value::Binary(b)) => String::from_utf8_lossy(b).into_owned(), + _ => String::new(), + } +} + +fn str_opt(lookup: &HashMap, k: &str) -> Option { + match lookup.get(k) { + Some(Value::String(s)) => Some(s.as_str().unwrap_or("").to_string()), + Some(Value::Binary(b)) => Some(String::from_utf8_lossy(b).into_owned()), + _ => None, + } +} + +fn bool_or_default(lookup: &HashMap, k: &str) -> bool { + match lookup.get(k) { + Some(Value::Boolean(b)) => *b, + _ => false, + } +} + +fn f64_or_default(lookup: &HashMap, k: &str) -> f64 { + match lookup.get(k) { + Some(Value::F64(f)) => *f, + Some(Value::F32(f)) => *f as f64, + Some(Value::Integer(n)) => n.as_f64().unwrap_or(0.0), + _ => 0.0, + } +} + +fn u64_opt(lookup: &HashMap, k: &str) -> Option { + lookup.get(k).and_then(|v| v.as_u64()) +} + +fn hex16(lookup: &HashMap, k: &str) -> Option<[u8; 16]> { + let hex_str = match lookup.get(k)? { + Value::String(s) => s.as_str()?.to_string(), + Value::Binary(b) => { + if b.len() == 16 { + let mut arr = [0u8; 16]; + arr.copy_from_slice(b); + return Some(arr); + } + String::from_utf8_lossy(b).into_owned() + } + _ => return None, + }; + let bytes = hex::decode(hex_str).ok()?; + if bytes.len() != 16 { + return None; + } + let mut arr = [0u8; 16]; + arr.copy_from_slice(&bytes); + Some(arr) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmpdir(tag: &str) -> PathBuf { + let p = std::env::temp_dir().join(format!( + "reticulum_rs_discovery_{}_{}", + tag, + std::process::id() + )); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).unwrap(); + p + } + + fn record(name: &str, transport_id: [u8; 16]) -> DiscoveredInterface { + DiscoveredInterface { + info: DiscoveryInfo { + name: name.into(), + transport_id, + interface_type: "BackboneInterface".into(), + transport_enabled: true, + reachable_on: Some("1.2.3.4".into()), + latitude: 0.0, + longitude: 0.0, + height: 0.0, + port: Some(4965), + ..Default::default() + }, + network_id: transport_id, + hops: 2, + stamp_value: 14, + stamp: vec![0xAA; STAMP_SIZE], + discovered: 1_000_000, + last_heard: 1_000_010, + heard_count: 0, + status: None, + } + } + + #[test] + fn discovery_hash_is_deterministic() { + let a = discovery_hash(&[0x11; 16], "alpha"); + let b = discovery_hash(&[0x11; 16], "alpha"); + let c = discovery_hash(&[0x11; 16], "beta"); + assert_eq!(a, b); + assert_ne!(a, c); + } + + #[test] + fn upsert_then_list() { + let dir = tmpdir("upsert"); + let store = DiscoveryStore::open(&dir).unwrap(); + let now = unix_now(); + let mut r = record("alpha", [0x11; 16]); + r.last_heard = now; + store.upsert(r.clone()).unwrap(); + + let listed = store.list(None).unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].heard_count, 1); + assert_eq!(listed[0].status, Some(DiscoveryStatus::Available)); + } + + #[test] + fn upsert_merges_discovered_and_heard_count() { + let dir = tmpdir("merge"); + let store = DiscoveryStore::open(&dir).unwrap(); + let now = unix_now(); + let mut first = record("alpha", [0x11; 16]); + first.discovered = 42; + first.last_heard = now; + store.upsert(first.clone()).unwrap(); + + let mut second = record("alpha", [0x11; 16]); + second.discovered = 999; // should be ignored on merge + second.last_heard = now + 1; + store.upsert(second).unwrap(); + + let listed = store.list(None).unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].discovered, 42); + assert_eq!(listed[0].heard_count, 2); + } + + #[test] + fn list_filters_unauthorized_sources() { + let dir = tmpdir("sources"); + let store = DiscoveryStore::open(&dir).unwrap(); + let now = unix_now(); + let mut a = record("alpha", [0x11; 16]); + a.last_heard = now; + let mut b = record("beta", [0x22; 16]); + b.last_heard = now; + store.upsert(a).unwrap(); + store.upsert(b).unwrap(); + + let allowed: &[[u8; 16]] = &[[0x11; 16]]; + let listed = store.list(Some(allowed)).unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].info.transport_id, [0x11; 16]); + + // The non-authorized record should have been removed on read. + let listed_again = store.list(None).unwrap(); + assert_eq!(listed_again.len(), 1); + } + + #[test] + fn list_removes_expired() { + let dir = tmpdir("expired"); + let store = DiscoveryStore::open(&dir).unwrap(); + let mut r = record("old", [0x11; 16]); + r.last_heard = 0; // ancient + store.upsert(r).unwrap(); + + let listed = store.list(None).unwrap(); + assert!(listed.is_empty()); + } + + #[test] + fn list_sorts_by_status_then_value_then_recency() { + let dir = tmpdir("sort"); + let store = DiscoveryStore::open(&dir).unwrap(); + let now = unix_now(); + + // Available, low stamp value, old + let mut a = record("a", [0x01; 16]); + a.stamp_value = 10; + a.last_heard = now - 100; + // Available, high stamp value, recent + let mut b = record("b", [0x02; 16]); + b.stamp_value = 20; + b.last_heard = now - 10; + // Unknown (freshness bucket) + let mut c = record("c", [0x03; 16]); + c.last_heard = now - THRESHOLD_UNKNOWN_SECS - 1; + c.stamp_value = 30; + + store.upsert(a).unwrap(); + store.upsert(b).unwrap(); + store.upsert(c).unwrap(); + + let listed = store.list(None).unwrap(); + assert_eq!(listed.len(), 3); + // b (Available, value 20, recent) before a (Available, value 10), both before c (Unknown) + assert_eq!(listed[0].info.name, "b"); + assert_eq!(listed[1].info.name, "a"); + assert_eq!(listed[2].info.name, "c"); + } + + #[test] + fn remove_deletes_record() { + let dir = tmpdir("remove"); + let store = DiscoveryStore::open(&dir).unwrap(); + let r = record("alpha", [0x11; 16]); + store.upsert(r.clone()).unwrap(); + assert!(store.remove(&r.info.transport_id, &r.info.name).unwrap()); + assert!(store.list(None).unwrap().is_empty()); + // Second remove is a no-op. + assert!(!store.remove(&r.info.transport_id, &r.info.name).unwrap()); + } + + #[test] + fn corrupt_file_is_culled_on_read() { + let dir = tmpdir("corrupt"); + let store = DiscoveryStore::open(&dir).unwrap(); + let garbage_name = hex::encode([0xAB; 32]); + std::fs::write(store.root().join(garbage_name), b"not valid msgpack").unwrap(); + assert!(store.list(None).unwrap().is_empty()); + } + + #[test] + fn classify_thresholds() { + assert_eq!(classify(0), DiscoveryStatus::Available); + assert_eq!( + classify(THRESHOLD_UNKNOWN_SECS + 1), + DiscoveryStatus::Unknown + ); + assert_eq!(classify(THRESHOLD_STALE_SECS + 1), DiscoveryStatus::Stale); + } +} diff --git a/crates/rns-transport/src/hashlist.rs b/crates/rns-transport/src/hashlist.rs new file mode 100644 index 0000000..b0d4435 --- /dev/null +++ b/crates/rns-transport/src/hashlist.rs @@ -0,0 +1,137 @@ +use std::collections::HashSet; + +use crate::constants::HASHLIST_MAXSIZE; + +/// Two-generation rotating hash set used for packet deduplication. +/// +/// When the `current` set fills to `max_size / 2`, it is promoted to +/// `previous` and a new empty `current` begins — giving a bounded, amortised +/// O(1) membership structure with a window of up to `max_size` entries. +pub struct PacketHashlist { + current: HashSet<[u8; 32]>, + previous: HashSet<[u8; 32]>, + max_size: usize, +} + +impl PacketHashlist { + pub fn new() -> Self { + Self::new_with_capacity(HASHLIST_MAXSIZE) + } + + /// Build a hashlist with a custom `max_size`, useful when the default + /// capacity would dominate memory (e.g. in benchmarks). + pub fn new_with_capacity(max_size: usize) -> Self { + Self { + current: HashSet::new(), + previous: HashSet::new(), + max_size, + } + } + + /// Check if a packet hash has been seen (checks both generations). + pub fn contains(&self, hash: &[u8; 32]) -> bool { + self.current.contains(hash) || self.previous.contains(hash) + } + + /// Insert a hash. Returns false if already present (duplicate). + pub fn insert(&mut self, hash: [u8; 32]) -> bool { + if self.contains(&hash) { + return false; + } + + if self.current.len() >= self.max_size / 2 { + self.force_rotate(); + } + + self.current.insert(hash); + true + } + + /// Rotate: current becomes previous, new empty set becomes current. + pub fn force_rotate(&mut self) { + self.previous = std::mem::take(&mut self.current); + } + + pub fn len(&self) -> usize { + self.current.len() + self.previous.len() + } + + pub fn is_empty(&self) -> bool { + self.current.is_empty() && self.previous.is_empty() + } + + pub fn clear(&mut self) { + self.current.clear(); + self.previous.clear(); + } + + /// All hashes across both generations; used to snapshot for persistence. + pub fn all_hashes(&self) -> Vec<[u8; 32]> { + self.current + .iter() + .chain(self.previous.iter()) + .copied() + .collect() + } + + /// Rehydrate from a persisted snapshot. Loaded into `previous` so fresh + /// packets land in an empty `current` and rotation behaviour is preserved. + pub fn load_from(&mut self, hashes: Vec<[u8; 32]>) { + self.previous = hashes.into_iter().collect(); + } +} + +impl Default for PacketHashlist { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_insert_and_contains() { + let mut hl = PacketHashlist::new(); + let hash = [0xAA; 32]; + assert!(!hl.contains(&hash)); + assert!(hl.insert(hash)); + assert!(hl.contains(&hash)); + assert!(!hl.insert(hash)); + } + + #[test] + fn test_rotation() { + let mut hl = PacketHashlist { + current: HashSet::new(), + previous: HashSet::new(), + max_size: 10, + }; + + // Rotation triggers at current.len() >= max_size/2, so the 6th insert + // promotes the first five into `previous` and lands alone in `current`. + for i in 0..6 { + let mut hash = [0u8; 32]; + hash[0] = i; + hl.insert(hash); + } + + assert_eq!(hl.previous.len(), 5); + assert_eq!(hl.current.len(), 1); + + let mut old_hash = [0u8; 32]; + old_hash[0] = 0; + assert!(hl.contains(&old_hash)); + } + + #[test] + fn test_clear() { + let mut hl = PacketHashlist::new(); + hl.insert([0x01; 32]); + hl.insert([0x02; 32]); + assert_eq!(hl.len(), 2); + hl.clear(); + assert_eq!(hl.len(), 0); + } +} diff --git a/crates/rns-transport/src/ifac.rs b/crates/rns-transport/src/ifac.rs new file mode 100644 index 0000000..1425352 --- /dev/null +++ b/crates/rns-transport/src/ifac.rs @@ -0,0 +1,362 @@ +//! Interface Access Control (IFAC) signing and verification. +//! +//! IFAC authenticates every packet on a closed-membership interface. A shared +//! interface key drives both an Ed25519 signing key (the tag is the last +//! `ifac_size` bytes of the signature) and an HKDF-XOR mask over the header +//! and payload — the tag itself is left in the clear because receivers need it +//! to regenerate the mask. Packets without a valid tag are dropped before any +//! routing decision, so unauthorised peers can neither send nor decode traffic. +//! +//! Wire layout matches the Python reference (`Transport.transmit` / +//! `Transport.inbound`): `[flags|0x80, hops, tag(ifac_size), payload]` with +//! everything except the tag masked. + +use rns_crypto::ed25519::Ed25519PrivateKey; +use rns_crypto::hkdf::hkdf_sha256; +use subtle::ConstantTimeEq; + +/// Bit 7 of byte 0 signals IFAC presence, regardless of `ifac_size`. +const IFAC_FLAG: u8 = 0x80; + +/// Stamp a packet with its IFAC tag and XOR mask. +/// +/// `ifac_key` is the 64-byte derived interface key: bytes [32..64) seed the +/// Ed25519 signer, and the full key acts as HKDF salt (Python uses +/// `interface.ifac_key` in both roles, so the split must not change). +pub fn ifac_sign(packet: &[u8], ifac_key: &[u8; 64], ifac_size: usize) -> Vec { + assert!(ifac_size > 0 && ifac_size <= 64, "ifac_size must be 1..=64"); + assert!( + packet.len() >= 2, + "packet must have at least 2 bytes (header)" + ); + + let signing_key_bytes: [u8; 32] = ifac_key[32..64] + .try_into() + .expect("ifac_key is [u8; 64]; slice [32..64] is always 32 bytes"); + let ed_key = Ed25519PrivateKey::from_bytes(&signing_key_bytes); + let signature = ed_key.sign(packet); + let tag = &signature[64 - ifac_size..]; + + let mask_len = packet.len() + ifac_size; + let mask = + hkdf_sha256(mask_len, tag, Some(ifac_key), None).expect("HKDF mask generation failed"); + + let mut new_raw = Vec::with_capacity(2 + ifac_size + packet.len() - 2); + new_raw.push(packet[0] | IFAC_FLAG); + new_raw.push(packet[1]); + new_raw.extend_from_slice(tag); + new_raw.extend_from_slice(&packet[2..]); + + // Mask header and payload; leave the tag bytes (indices 2..2+ifac_size) + // in the clear so the receiver can regenerate the same mask. The IFAC + // flag must survive masking, so it is re-OR'd onto byte 0. + let mut masked_raw = Vec::with_capacity(new_raw.len()); + for (i, &byte) in new_raw.iter().enumerate() { + if i == 0 { + masked_raw.push((byte ^ mask[i]) | IFAC_FLAG); + } else if i == 1 || i > ifac_size + 1 { + masked_raw.push(byte ^ mask[i]); + } else { + masked_raw.push(byte); + } + } + + masked_raw +} + +/// Strip and authenticate an IFAC-stamped packet, returning the plain inner +/// form when the tag matches. `None` on any failure — callers should drop the +/// packet silently to avoid leaking membership probes. +pub fn ifac_verify(raw: &[u8], ifac_key: &[u8; 64], ifac_size: usize) -> Option> { + if ifac_size == 0 || ifac_size > 64 { + return None; + } + if raw.len() <= 2 + ifac_size { + return None; + } + + if raw[0] & IFAC_FLAG == 0 { + return None; + } + + let ifac = &raw[2..2 + ifac_size]; + + let mask = hkdf_sha256(raw.len(), ifac, Some(ifac_key), None).ok()?; + + let mut unmasked_raw = Vec::with_capacity(raw.len()); + for (i, &byte) in raw.iter().enumerate() { + if i <= 1 || i > ifac_size + 1 { + unmasked_raw.push(byte ^ mask[i]); + } else { + unmasked_raw.push(byte); + } + } + + let new_header = [unmasked_raw[0] & !IFAC_FLAG, unmasked_raw[1]]; + + let mut new_raw = Vec::with_capacity(2 + raw.len() - 2 - ifac_size); + new_raw.extend_from_slice(&new_header); + new_raw.extend_from_slice(&unmasked_raw[2 + ifac_size..]); + + let signing_key_bytes: [u8; 32] = ifac_key[32..64] + .try_into() + .expect("ifac_key is [u8; 64]; slice [32..64] is always 32 bytes"); + let ed_key = Ed25519PrivateKey::from_bytes(&signing_key_bytes); + let expected_sig = ed_key.sign(&new_raw); + let expected_ifac = &expected_sig[64 - ifac_size..]; + + // Constant-time compare — an early-exit would leak tag prefix bytes. + if ifac.ct_eq(expected_ifac).into() { + Some(new_raw) + } else { + None + } +} + +/// Whether a raw packet carries the IFAC flag. Cheap pre-check to avoid +/// running the full verify path on clear-interface traffic. +pub fn has_ifac_flag(raw: &[u8]) -> bool { + !raw.is_empty() && raw[0] & IFAC_FLAG != 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn make_test_ifac_key() -> [u8; 64] { + rns_identity::ifac::derive_ifac_key(Some("testnet"), Some("password")).unwrap() + } + + #[test] + fn test_ifac_sign_sets_flag() { + let packet = vec![0x01, 0x00, 0xAA, 0xBB]; + let ifac_key = make_test_ifac_key(); + let ifac_size = 2; + + let signed = ifac_sign(&packet, &ifac_key, ifac_size); + + assert_eq!(signed.len(), ifac_size + packet.len()); + assert!(signed[0] & 0x80 != 0); + } + + #[test] + fn test_ifac_roundtrip() { + let packet = { + let mut p = vec![0x01, 0x03]; + p.extend_from_slice(&[0xAA; 20]); + p + }; + let ifac_key = make_test_ifac_key(); + let ifac_size = 4; + + let signed = ifac_sign(&packet, &ifac_key, ifac_size); + let verified = ifac_verify(&signed, &ifac_key, ifac_size); + + assert!(verified.is_some()); + assert_eq!(verified.unwrap(), packet); + } + + /// Asymmetry documentation — `ifac_sign` accepts `packet.len() >= 2` + /// (header-only packets with no payload), but `ifac_verify` requires + /// `raw.len() > 2 + ifac_size`, i.e. at least one payload byte after + /// the tag. Proptest shrank a failing round-trip to this boundary + /// case. In practice, production packets always carry a destination + /// hash (≥16 bytes), so the asymmetry is invisible — but it's real + /// and worth locking in so a later refactor doesn't silently change + /// behavior. + #[test] + fn test_ifac_verify_rejects_header_only_packet() { + let packet = vec![0u8, 0u8]; // 2-byte "header only" input + let key = [0u8; 64]; + let signed = ifac_sign(&packet, &key, 1); + assert_eq!(signed.len(), 2 + 1, "signed = header + tag, no payload"); + // verify's minimum-size gate rejects this before any crypto work. + assert_eq!(ifac_verify(&signed, &key, 1), None); + } + + #[test] + fn test_ifac_verify_wrong_key() { + let packet = { + let mut p = vec![0x01, 0x03]; + p.extend_from_slice(&[0xAA; 20]); + p + }; + let ifac_key = make_test_ifac_key(); + let wrong_key = rns_identity::ifac::derive_ifac_key(Some("wrong"), Some("key")).unwrap(); + let ifac_size = 4; + + let signed = ifac_sign(&packet, &ifac_key, ifac_size); + let verified = ifac_verify(&signed, &wrong_key, ifac_size); + + assert!(verified.is_none()); + } + + #[test] + fn test_ifac_verify_tampered() { + let packet = { + let mut p = vec![0x01, 0x03]; + p.extend_from_slice(&[0xAA; 20]); + p + }; + let ifac_key = make_test_ifac_key(); + let ifac_size = 4; + + let mut signed = ifac_sign(&packet, &ifac_key, ifac_size); + if signed.len() > ifac_size + 3 { + signed[ifac_size + 3] ^= 0xFF; + } + let verified = ifac_verify(&signed, &ifac_key, ifac_size); + + assert!(verified.is_none()); + } + + #[test] + fn test_ifac_verify_no_flag() { + let packet = vec![0x01, 0x03, 0xAA, 0xBB, 0xCC, 0xDD]; + let ifac_key = make_test_ifac_key(); + let ifac_size = 4; + + let verified = ifac_verify(&packet, &ifac_key, ifac_size); + assert!(verified.is_none()); + } + + #[test] + fn test_ifac_verify_too_short() { + let ifac_key = make_test_ifac_key(); + let ifac_size = 4; + + let verified = ifac_verify(&[0x80, 0x01], &ifac_key, ifac_size); + assert!(verified.is_none()); + } + + #[test] + fn test_has_ifac_flag() { + assert!(!has_ifac_flag(&[0x00, 0x01])); + assert!(has_ifac_flag(&[0x80, 0x01])); + assert!(has_ifac_flag(&[0x81, 0x01])); + assert!(!has_ifac_flag(&[])); + } + + #[test] + fn test_ifac_different_sizes() { + let packet = { + let mut p = vec![0x01, 0x03]; + p.extend_from_slice(&[0xAA; 20]); + p + }; + let ifac_key = make_test_ifac_key(); + + for ifac_size in [1, 2, 4, 8, 16] { + let signed = ifac_sign(&packet, &ifac_key, ifac_size); + assert_eq!(signed.len(), ifac_size + packet.len()); + + let verified = ifac_verify(&signed, &ifac_key, ifac_size); + assert!(verified.is_some(), "failed for ifac_size={}", ifac_size); + assert_eq!(verified.unwrap(), packet); + } + } + + #[test] + fn test_ifac_masking_applied() { + let packet = vec![0x01, 0x03, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]; + let ifac_key = make_test_ifac_key(); + let ifac_size = 4; + + let signed = ifac_sign(&packet, &ifac_key, ifac_size); + + let payload_start = 2 + ifac_size; + let original_payload = &packet[2..]; + let signed_payload = &signed[payload_start..]; + assert_ne!( + original_payload, signed_payload, + "masking should change payload bytes" + ); + } + + #[test] + fn test_ifac_flag_byte_preserved_after_roundtrip() { + for flags_byte in [0x00, 0x01, 0x7F, 0x3C, 0x55] { + let packet = vec![flags_byte, 0x03, 0xAA, 0xBB, 0xCC, 0xDD]; + let ifac_key = make_test_ifac_key(); + let ifac_size = 4; + + let signed = ifac_sign(&packet, &ifac_key, ifac_size); + let verified = ifac_verify(&signed, &ifac_key, ifac_size).unwrap(); + assert_eq!( + verified[0], flags_byte, + "flags byte should be preserved for 0x{:02x}", + flags_byte + ); + } + } + + // Proptest round-trips over arbitrary (packet, key, ifac_size) tuples. + // Existing tests cover a handful of fixed values; this widens to the + // interesting axes at once, catching masking / tag-truncation bugs + // that depend on the interaction between payload bytes and key. + use proptest::prelude::*; + + // Bit 7 of byte 0 is the IFAC flag on the wire; real packets always + // have it clear (reserved bit per `flags.rs`). Enforcing this in the + // proptest generator matches the actual input space — an all-1s first + // byte would have its flag bit overwritten by `ifac_sign`, violating + // the round-trip invariant the rest of the protocol guarantees. + fn any_packet_first_byte() -> impl Strategy { + 0u8..=0x7F + } + + proptest! { + #[test] + fn proptest_ifac_roundtrip( + first_byte in any_packet_first_byte(), + // At least 2 "rest" bytes so raw.len() = 2 + ifac_size + rest.len() + // > 2 + ifac_size — the verify minimum. See + // test_ifac_verify_rejects_header_only_packet for the boundary. + rest in proptest::collection::vec(any::(), 2..=254), + ifac_key: [u8; 64], + ifac_size in 1usize..=32, + ) { + let mut packet = Vec::with_capacity(1 + rest.len()); + packet.push(first_byte); + packet.extend_from_slice(&rest); + + let signed = ifac_sign(&packet, &ifac_key, ifac_size); + + // IFAC flag must be present on the signed output. + prop_assert!(has_ifac_flag(&signed), "ifac flag must be set after sign"); + + // Verify with the same key must recover the exact original bytes. + let verified = ifac_verify(&signed, &ifac_key, ifac_size) + .expect("verify with correct key must succeed"); + prop_assert_eq!(verified, packet); + } + + #[test] + fn proptest_ifac_wrong_key_rejects( + first_byte in any_packet_first_byte(), + rest in proptest::collection::vec(any::(), 2..=127), + key_a: [u8; 64], + key_b: [u8; 64], + // ifac_size >= 8 gives a 1/2^64 false-accept rate with a + // random wrong key. Below that (esp. ifac_size=1 = 0.4%), + // the proptest's 256 cases hit collisions by luck — that's + // the inherent weakness of a 1-byte MAC, not a verify bug. + ifac_size in 8usize..=16, + ) { + // Reject when any byte of the key differs — if the two generated + // keys happen to be identical (astronomically rare), the test is + // meaningless so we skip it. + prop_assume!(key_a != key_b); + + let mut packet = Vec::with_capacity(1 + rest.len()); + packet.push(first_byte); + packet.extend_from_slice(&rest); + + let signed = ifac_sign(&packet, &key_a, ifac_size); + prop_assert!( + ifac_verify(&signed, &key_b, ifac_size).is_none(), + "verify with a different key must return None" + ); + } + } +} diff --git a/crates/rns-transport/src/ingress.rs b/crates/rns-transport/src/ingress.rs new file mode 100644 index 0000000..cfb57e8 --- /dev/null +++ b/crates/rns-transport/src/ingress.rs @@ -0,0 +1,384 @@ +//! Per-interface ingress control: announce flood protection. +//! +//! Each interface owns one `IngressController`. The inbound path consults it +//! on every announce — when the incoming rate crosses the burst threshold the +//! controller activates a hold state, shunts subsequent announces into a +//! per-destination hold buffer, and the maintenance tick releases them later +//! in hop-priority order. The split thresholds for freshly-seen vs. mature +//! interfaces (`IC_BURST_FREQ_NEW` vs. `IC_BURST_FREQ`) give newly-online +//! links time to catch up from the network backlog without triggering the +//! limiter on the first burst of announces. + +use std::collections::{HashMap, VecDeque}; +use std::time::{Duration, Instant}; + +use bytes::Bytes; + +use crate::constants::{ + IA_FREQ_SAMPLES, IC_BURST_FREQ, IC_BURST_FREQ_NEW, IC_BURST_HOLD, IC_BURST_PENALTY, + IC_DEQUE_MIN_SAMPLE, IC_HELD_RELEASE_INTERVAL, IC_NEW_TIME, MAX_HELD_ANNOUNCES, + OA_FREQ_SAMPLES, +}; + +/// Per-interface ingress overrides parsed from `[interface.] ic_*` keys. +/// Any field left `None` falls back to the corresponding crate-level constant. +#[derive(Debug, Clone, Default)] +pub struct IngressOverrides { + pub enabled: Option, + pub burst_freq_new: Option, + pub burst_freq: Option, + pub new_time: Option, + pub burst_hold: Option, + pub burst_penalty: Option, + pub max_held: Option, + pub held_release_interval: Option, +} + +impl IngressOverrides { + pub fn is_empty(&self) -> bool { + self.enabled.is_none() + && self.burst_freq_new.is_none() + && self.burst_freq.is_none() + && self.new_time.is_none() + && self.burst_hold.is_none() + && self.burst_penalty.is_none() + && self.max_held.is_none() + && self.held_release_interval.is_none() + } +} + +/// An announce parked in the hold buffer, awaiting release. +#[derive(Debug, Clone)] +pub struct HeldAnnounce { + pub raw: Bytes, + pub destination_hash: [u8; 16], + /// Hops at reception — lower values win release priority. + pub hops: u8, + pub receiving_interface_id: u64, +} + +#[derive(Debug)] +pub struct IngressController { + created: Instant, + enabled: bool, + /// Incoming announce timestamps; capped at `IA_FREQ_SAMPLES`. + ia_freq_deque: VecDeque, + /// Outgoing announce timestamps; capped at `OA_FREQ_SAMPLES`. + oa_freq_deque: VecDeque, + burst_active: bool, + burst_activated: Instant, + /// Earliest instant at which the next held announce may be released. + held_release: Instant, + held_announces: HashMap<[u8; 16], HeldAnnounce>, + + burst_freq_new: f64, + burst_freq: f64, + new_time: f64, + burst_hold: f64, + burst_penalty: f64, + max_held: usize, + held_release_interval: f64, +} + +impl IngressController { + pub fn new() -> Self { + let now = Instant::now(); + Self { + created: now, + enabled: true, + ia_freq_deque: VecDeque::with_capacity(IA_FREQ_SAMPLES), + oa_freq_deque: VecDeque::with_capacity(OA_FREQ_SAMPLES), + burst_active: false, + burst_activated: now, + held_release: now, + held_announces: HashMap::new(), + burst_freq_new: IC_BURST_FREQ_NEW, + burst_freq: IC_BURST_FREQ, + new_time: IC_NEW_TIME, + burst_hold: IC_BURST_HOLD, + burst_penalty: IC_BURST_PENALTY, + max_held: MAX_HELD_ANNOUNCES, + held_release_interval: IC_HELD_RELEASE_INTERVAL, + } + } + + /// Always-permissive controller — use when ingress control is switched off + /// at the transport or interface level. The state machine still compiles + /// samples so operators can read frequency stats, but `should_ingress_limit` + /// is hard-wired to `false`. + pub fn disabled() -> Self { + let mut ctrl = Self::new(); + ctrl.enabled = false; + ctrl + } + + /// Controller with per-interface overrides applied; unset fields keep + /// their compile-time defaults. + pub fn with_overrides(overrides: &IngressOverrides) -> Self { + let mut ctrl = Self::new(); + if let Some(v) = overrides.enabled { + ctrl.enabled = v; + } + if let Some(v) = overrides.burst_freq_new { + ctrl.burst_freq_new = v; + } + if let Some(v) = overrides.burst_freq { + ctrl.burst_freq = v; + } + if let Some(v) = overrides.new_time { + ctrl.new_time = v; + } + if let Some(v) = overrides.burst_hold { + ctrl.burst_hold = v; + } + if let Some(v) = overrides.burst_penalty { + ctrl.burst_penalty = v; + } + if let Some(v) = overrides.max_held { + ctrl.max_held = v; + } + if let Some(v) = overrides.held_release_interval { + ctrl.held_release_interval = v; + } + ctrl + } + + pub fn burst_freq(&self) -> f64 { + self.burst_freq + } + + pub fn burst_freq_new(&self) -> f64 { + self.burst_freq_new + } + + pub fn held_release_interval(&self) -> f64 { + self.held_release_interval + } + + /// Earliest instant at which the next held announce may be released. The + /// cooldown starts when burst mode activates (not deactivates) so a + /// prolonged burst cannot starve existing holds. + pub fn held_release_at(&self) -> Instant { + self.held_release + } + + pub fn is_enabled(&self) -> bool { + self.enabled + } + + pub fn age(&self) -> f64 { + self.created.elapsed().as_secs_f64() + } + + pub fn received_announce(&mut self) { + let now = Instant::now(); + if self.ia_freq_deque.len() >= IA_FREQ_SAMPLES { + self.ia_freq_deque.pop_front(); + } + self.ia_freq_deque.push_back(now); + } + + pub fn sent_announce(&mut self) { + let now = Instant::now(); + if self.oa_freq_deque.len() >= OA_FREQ_SAMPLES { + self.oa_freq_deque.pop_front(); + } + self.oa_freq_deque.push_back(now); + } + + pub fn incoming_announce_frequency(&self) -> f64 { + frequency_from_deque(&self.ia_freq_deque) + } + + pub fn outgoing_announce_frequency(&self) -> f64 { + frequency_from_deque(&self.oa_freq_deque) + } + + /// Whether inbound announces should currently be held. Also updates the + /// internal burst state — an exit from burst only happens once the + /// frequency has dropped *and* `burst_hold` seconds have passed since + /// activation, preventing flapping on a noisy interface. + pub fn should_ingress_limit(&mut self) -> bool { + if !self.enabled { + return false; + } + + let freq_threshold = if self.age() < self.new_time { + self.burst_freq_new + } else { + self.burst_freq + }; + + let ia_freq = self.incoming_announce_frequency(); + let now = Instant::now(); + + if self.burst_active { + if ia_freq < freq_threshold + && now.duration_since(self.burst_activated) + > Duration::from_secs_f64(self.burst_hold) + { + self.burst_active = false; + } + true + } else if ia_freq > freq_threshold { + self.burst_active = true; + self.burst_activated = now; + self.held_release = now + Duration::from_secs_f64(self.burst_penalty); + true + } else { + false + } + } + + pub fn hold_announce(&mut self, announce: HeldAnnounce) { + if self.held_announces.contains_key(&announce.destination_hash) + || self.held_announces.len() < self.max_held + { + self.held_announces + .insert(announce.destination_hash, announce); + } + } + + /// Release at most one held announce per call — the one with the lowest + /// hop count, so short-path announces win priority. `None` means either + /// the burst is still active, the release cooldown has not elapsed, or + /// the buffer is empty. + pub fn try_release_held(&mut self) -> Option { + if self.should_ingress_limit() || self.held_announces.is_empty() { + return None; + } + + let now = Instant::now(); + if now < self.held_release { + return None; + } + + let freq_threshold = if self.age() < self.new_time { + self.burst_freq_new + } else { + self.burst_freq + }; + + if self.incoming_announce_frequency() >= freq_threshold { + return None; + } + + let best_hash = self + .held_announces + .iter() + .min_by_key(|(_, a)| a.hops) + .map(|(hash, _)| *hash)?; + + let announce = self.held_announces.remove(&best_hash)?; + self.held_release = now + Duration::from_secs_f64(self.held_release_interval); + Some(announce) + } + + pub fn held_count(&self) -> usize { + self.held_announces.len() + } + + pub fn is_burst_active(&self) -> bool { + self.burst_active + } +} + +impl Default for IngressController { + fn default() -> Self { + Self::new() + } +} + +/// Announces-per-second estimate over a timestamp deque. Returns 0 until +/// enough samples have accumulated (`IC_DEQUE_MIN_SAMPLE`) so the first few +/// entries on a new interface cannot trip the limiter by themselves. +fn frequency_from_deque(deque: &VecDeque) -> f64 { + let n = deque.len(); + if n <= IC_DEQUE_MIN_SAMPLE { + return 0.0; + } + let span = match deque.front() { + Some(oldest) => oldest.elapsed().as_secs_f64(), + None => return 0.0, + }; + if span <= 0.0 { 0.0 } else { n as f64 / span } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ingress_controller_default_state() { + let ctrl = IngressController::new(); + assert!(ctrl.is_enabled()); + assert!(!ctrl.is_burst_active()); + assert_eq!(ctrl.held_count(), 0); + assert_eq!(ctrl.incoming_announce_frequency(), 0.0); + } + + #[test] + fn ingress_disabled_never_limits() { + let mut ctrl = IngressController::disabled(); + for _ in 0..100 { + ctrl.received_announce(); + } + assert!(!ctrl.should_ingress_limit()); + } + + #[test] + fn hold_announce_dedups_by_destination() { + let mut ctrl = IngressController::new(); + let a = HeldAnnounce { + raw: Bytes::from_static(&[1, 2, 3]), + destination_hash: [0u8; 16], + hops: 1, + receiving_interface_id: 1, + }; + ctrl.hold_announce(a); + assert_eq!(ctrl.held_count(), 1); + + let a2 = HeldAnnounce { + raw: Bytes::from_static(&[4, 5, 6]), + destination_hash: [0u8; 16], + hops: 2, + receiving_interface_id: 1, + }; + ctrl.hold_announce(a2); + assert_eq!(ctrl.held_count(), 1); + + let a3 = HeldAnnounce { + raw: Bytes::from_static(&[7, 8, 9]), + destination_hash: [1u8; 16], + hops: 0, + receiving_interface_id: 1, + }; + ctrl.hold_announce(a3); + assert_eq!(ctrl.held_count(), 2); + } + + #[test] + fn hold_announce_capped_at_max() { + let mut ctrl = IngressController::new(); + for i in 0..MAX_HELD_ANNOUNCES { + let mut h = [0u8; 16]; + h[0] = (i & 0xFF) as u8; + h[1] = ((i >> 8) & 0xFF) as u8; + ctrl.hold_announce(HeldAnnounce { + raw: Bytes::new(), + destination_hash: h, + hops: 0, + receiving_interface_id: 1, + }); + } + assert_eq!(ctrl.held_count(), MAX_HELD_ANNOUNCES); + + ctrl.hold_announce(HeldAnnounce { + raw: Bytes::new(), + destination_hash: [0xFF; 16], + hops: 0, + receiving_interface_id: 1, + }); + assert_eq!(ctrl.held_count(), MAX_HELD_ANNOUNCES); + } +} diff --git a/crates/rns-transport/src/lib.rs b/crates/rns-transport/src/lib.rs new file mode 100644 index 0000000..cf09c75 --- /dev/null +++ b/crates/rns-transport/src/lib.rs @@ -0,0 +1,24 @@ +//! Reticulum transport: routing actor, path tables, announces, blackhole, +//! rate limiting. The Rust replacement for Python's static `Transport` class +//! ([Transport.py](https://github.com/markqvist/Reticulum/blob/master/RNS/Transport.py)). +//! [`actor::TransportActor`] owns all mutable state; other crates send typed +//! [`messages::TransportMessage`]s over a Tokio mpsc channel. + +pub mod actor; +pub mod announce; +pub mod await_path; +pub mod blackhole; +pub mod constants; +pub mod discovery; +pub mod hashlist; +pub mod ifac; +pub mod ingress; +pub mod link_messages; +pub mod link_table; +pub mod messages; +pub mod path_table; +pub mod persistence; +pub mod rate_limit; +pub mod reverse_table; +pub mod traffic; +pub mod tunnel; diff --git a/crates/rns-transport/src/link_messages.rs b/crates/rns-transport/src/link_messages.rs new file mode 100644 index 0000000..05a490f --- /dev/null +++ b/crates/rns-transport/src/link_messages.rs @@ -0,0 +1,146 @@ +//! Link-layer message types routed between the transport actor and the +//! destinations that own registered identities. Kept in their own module so +//! the main `messages.rs` actor enum stays focused on transport primitives. + +use bytes::Bytes; +use tokio::sync::oneshot; + +use crate::messages::InterfaceId; + +#[derive(Debug, Clone)] +pub struct AnnounceRequest { + pub app_name: String, + pub path_response: bool, + pub tag: Option>, + pub attached_interface: Option, +} + +impl AnnounceRequest { + pub fn normal(app_name: String) -> Self { + Self { + app_name, + path_response: false, + tag: None, + attached_interface: None, + } + } +} + +/// Events the transport actor pushes out to a registered destination. +#[derive(Debug)] +pub enum DestinationEvent { + InboundPacket { + raw: Bytes, + interface_id: InterfaceId, + }, + LinkRequest { + raw: Bytes, + interface_id: InterfaceId, + }, + LinkEstablished { + link_id: [u8; 16], + }, + LinkClosed { + link_id: [u8; 16], + }, + DeliveryProof { + msg_id: String, + rtt: Option, + }, + /// Transport asks the destination to announce itself — used when a shared + /// instance connects and needs the peer's current identity map. + AnnounceRequested(AnnounceRequest), +} + +/// Request a new link to `dest_hash`. `result_tx` delivers either the link +/// id or a diagnostic message explaining why establishment failed. +#[derive(Debug)] +pub struct EstablishLinkRequest { + pub dest_hash: [u8; 16], + pub result_tx: oneshot::Sender>, +} + +#[derive(Debug)] +pub struct LinkDataRequest { + pub link_id: [u8; 16], + pub data: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_destination_event_variants() { + let evt1 = DestinationEvent::InboundPacket { + raw: Bytes::from_static(&[1, 2, 3]), + interface_id: 42, + }; + assert!(matches!(evt1, DestinationEvent::InboundPacket { .. })); + + let evt2 = DestinationEvent::LinkRequest { + raw: Bytes::from_static(&[4, 5, 6]), + interface_id: 99, + }; + assert!(matches!(evt2, DestinationEvent::LinkRequest { .. })); + + let evt3 = DestinationEvent::LinkEstablished { + link_id: [0xAA; 16], + }; + assert!(matches!(evt3, DestinationEvent::LinkEstablished { .. })); + + let evt4 = DestinationEvent::LinkClosed { + link_id: [0xBB; 16], + }; + assert!(matches!(evt4, DestinationEvent::LinkClosed { .. })); + } + + #[test] + fn test_establish_link_request() { + let (tx, rx) = oneshot::channel(); + let req = EstablishLinkRequest { + dest_hash: [0xCC; 16], + result_tx: tx, + }; + assert_eq!(req.dest_hash, [0xCC; 16]); + + drop(req.result_tx); + assert!(rx.blocking_recv().is_err()); + } + + #[test] + fn test_establish_link_request_success() { + let (tx, rx) = oneshot::channel(); + let req = EstablishLinkRequest { + dest_hash: [0xDD; 16], + result_tx: tx, + }; + let link_id = [0xEE; 16]; + req.result_tx.send(Ok(link_id)).unwrap(); + let result = rx.blocking_recv().unwrap(); + assert_eq!(result.unwrap(), link_id); + } + + #[test] + fn test_establish_link_request_failure() { + let (tx, rx) = oneshot::channel(); + let req = EstablishLinkRequest { + dest_hash: [0xFF; 16], + result_tx: tx, + }; + req.result_tx.send(Err("no path".to_string())).unwrap(); + let result = rx.blocking_recv().unwrap(); + assert!(result.is_err()); + assert_eq!(result.unwrap_err(), "no path"); + } + + #[test] + fn test_link_data_request() { + let req = LinkDataRequest { + link_id: [0xAA; 16], + data: vec![10, 20, 30, 40, 50], + }; + assert_eq!(req.link_id, [0xAA; 16]); + assert_eq!(req.data.len(), 5); + } +} diff --git a/crates/rns-transport/src/link_table.rs b/crates/rns-transport/src/link_table.rs new file mode 100644 index 0000000..b29eadc --- /dev/null +++ b/crates/rns-transport/src/link_table.rs @@ -0,0 +1,334 @@ +use std::collections::HashMap; + +use crate::messages::InterfaceId; +use rns_wire::types::LinkId; + +/// Transport-level state for one forwarded or terminated link. +#[derive(Debug, Clone)] +pub struct LinkEntry { + /// Registration time (Unix seconds). + pub timestamp: f64, + /// Next-hop transport id for a routed link; `None` when this node is the endpoint. + pub next_hop: Option<[u8; 16]>, + pub interface_id: InterfaceId, + pub remaining_hops: u8, + pub destination_hash: [u8; 16], + /// Handshake complete. + pub established: bool, + /// Proof received. Forwarding does not require this — unvalidated links + /// still forward while `now < proof_timeout` so in-flight traffic is not + /// stranded during the establishment window. + pub validated: bool, + pub proof_timeout: f64, + /// Interface the initial link request arrived on. + pub receiving_interface: InterfaceId, + pub taken_hops: u8, +} + +pub struct LinkTable { + entries: HashMap, +} + +impl LinkTable { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + } + } + + pub fn insert(&mut self, link_id: impl Into, entry: LinkEntry) { + self.entries.insert(link_id.into(), entry); + } + + pub fn get(&self, link_id: &[u8; 16]) -> Option<&LinkEntry> { + self.entries.get(link_id) + } + + pub fn get_mut(&mut self, link_id: &[u8; 16]) -> Option<&mut LinkEntry> { + self.entries.get_mut(link_id) + } + + pub fn remove(&mut self, link_id: &[u8; 16]) -> Option { + self.entries.remove(link_id) + } + + pub fn contains(&self, link_id: &[u8; 16]) -> bool { + self.entries.contains_key(link_id) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.entries.iter() + } + + /// Cull stale links with two different clocks: + /// - Validated links drop after `timeout` seconds of inactivity. + /// - Unvalidated links drop once their own `proof_timeout` elapses, since + /// proof never arrived during the establishment window. + /// + /// Returns `(total_culled, destinations_that_expired_unvalidated)` — the + /// caller can re-issue path discovery for those destinations. + pub fn cull_stale(&mut self, timeout: f64) -> (usize, Vec<[u8; 16]>) { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + let cutoff = now - timeout; + + let mut unvalidated_expired = Vec::new(); + + let before = self.entries.len(); + self.entries.retain(|_, entry| { + if entry.validated { + entry.timestamp > cutoff + } else if now > entry.proof_timeout { + unvalidated_expired.push(entry.destination_hash); + false + } else { + true + } + }); + (before - self.entries.len(), unvalidated_expired) + } + + /// Drop entries whose interfaces have gone away. Run with the current + /// active-interface set during periodic maintenance. + pub fn cull_dead_interfaces( + &mut self, + active_interfaces: &std::collections::HashSet, + ) -> usize { + let before = self.entries.len(); + self.entries.retain(|_, entry| { + active_interfaces.contains(&entry.interface_id) + && active_interfaces.contains(&entry.receiving_interface) + }); + before - self.entries.len() + } +} + +impl Default for LinkTable { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_link_table_basic() { + let mut table = LinkTable::new(); + let link_id = [0xAA; 16]; + table.insert( + link_id, + LinkEntry { + timestamp: 1000.0, + next_hop: None, + interface_id: 1, + remaining_hops: 0, + destination_hash: [0xBB; 16], + established: true, + validated: true, + proof_timeout: 0.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + assert!(table.contains(&link_id)); + assert_eq!(table.len(), 1); + } + + #[test] + fn test_link_table_unvalidated_entry() { + let mut table = LinkTable::new(); + let link_id = [0xCC; 16]; + let _dest_hash = [0xDD; 16]; + table.insert( + link_id, + LinkEntry { + timestamp: 1000.0, + next_hop: Some([0xDD; 16]), + interface_id: 1, + remaining_hops: 3, + destination_hash: [0xEE; 16], + established: false, + validated: false, + proof_timeout: 1060.0, + receiving_interface: 2, + taken_hops: 1, + }, + ); + let entry = table.get(&link_id).unwrap(); + assert!(!entry.validated); + assert_eq!(entry.proof_timeout, 1060.0); + } + + #[test] + fn test_link_table_unvalidated_cull() { + let mut table = LinkTable::new(); + let link_id = [0xDD; 16]; + let dest_hash = [0xEE; 16]; + table.insert( + link_id, + LinkEntry { + timestamp: 1000.0, + next_hop: None, + interface_id: 1, + remaining_hops: 1, + destination_hash: dest_hash, + established: false, + validated: false, + proof_timeout: 500.0, + receiving_interface: 2, + taken_hops: 0, + }, + ); + assert_eq!(table.len(), 1); + + let (culled, expired_dests) = table.cull_stale(900.0); + assert_eq!(culled, 1); + assert_eq!(expired_dests.len(), 1); + assert_eq!(expired_dests[0], dest_hash); + assert_eq!(table.len(), 0); + } + + #[test] + fn test_link_table_cull_validated_vs_unvalidated() { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let mut table = LinkTable::new(); + + table.insert( + [0x01; 16], + LinkEntry { + timestamp: now, + next_hop: None, + interface_id: 1, + remaining_hops: 1, + destination_hash: [0xA1; 16], + established: true, + validated: true, + proof_timeout: now + 100.0, + receiving_interface: 2, + taken_hops: 0, + }, + ); + + table.insert( + [0x02; 16], + LinkEntry { + timestamp: 100.0, + next_hop: None, + interface_id: 1, + remaining_hops: 1, + destination_hash: [0xA2; 16], + established: true, + validated: true, + proof_timeout: 200.0, + receiving_interface: 2, + taken_hops: 0, + }, + ); + + table.insert( + [0x03; 16], + LinkEntry { + timestamp: now, + next_hop: None, + interface_id: 1, + remaining_hops: 1, + destination_hash: [0xA3; 16], + established: false, + validated: false, + proof_timeout: now + 100.0, + receiving_interface: 2, + taken_hops: 0, + }, + ); + + table.insert( + [0x04; 16], + LinkEntry { + timestamp: now, + next_hop: None, + interface_id: 1, + remaining_hops: 1, + destination_hash: [0xA4; 16], + established: false, + validated: false, + proof_timeout: 500.0, + receiving_interface: 2, + taken_hops: 0, + }, + ); + + assert_eq!(table.len(), 4); + let (culled, expired_dests) = table.cull_stale(900.0); + assert_eq!(culled, 2); + assert_eq!(table.len(), 2); + assert_eq!(expired_dests.len(), 1); + assert_eq!(expired_dests[0], [0xA4; 16]); + } + + #[test] + fn test_link_table_cull_dead_interfaces() { + let mut table = LinkTable::new(); + let mut active = std::collections::HashSet::new(); + active.insert(1u64); + active.insert(2u64); + + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + table.insert( + [0x01; 16], + LinkEntry { + timestamp: now, + next_hop: None, + interface_id: 1, + remaining_hops: 1, + destination_hash: [0xA1; 16], + established: true, + validated: true, + proof_timeout: now + 100.0, + receiving_interface: 2, + taken_hops: 0, + }, + ); + + table.insert( + [0x02; 16], + LinkEntry { + timestamp: now, + next_hop: None, + interface_id: 99, + remaining_hops: 1, + destination_hash: [0xA2; 16], + established: true, + validated: true, + proof_timeout: now + 100.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + + assert_eq!(table.len(), 2); + let culled = table.cull_dead_interfaces(&active); + assert_eq!(culled, 1); + assert_eq!(table.len(), 1); + assert!(table.contains(&[0x01; 16])); + } +} diff --git a/crates/rns-transport/src/messages.rs b/crates/rns-transport/src/messages.rs new file mode 100644 index 0000000..8d15149 --- /dev/null +++ b/crates/rns-transport/src/messages.rs @@ -0,0 +1,675 @@ +//! Actor-model interface for the transport. +//! +//! Every routing state mutation flows through `TransportMessage` into the +//! single task that owns the routing tables. This eliminates shared mutable +//! state and its locking on the hot path; other components interact with the +//! transport exclusively via `mpsc` senders and `oneshot` reply channels. + +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use bytes::Bytes; +use tokio::sync::mpsc; + +use crate::constants::{InterfaceDirection, InterfaceMode}; +pub use crate::ingress::HeldAnnounce; +use crate::ingress::IngressController; + +pub type InterfaceId = u64; + +/// Transport-level role of an interface. Python Reticulum distinguishes +/// ordinary network interfaces, the local shared-instance listener, accepted +/// local clients behind that listener, and the one interface a leaf process uses +/// to reach an existing shared instance. Several routing rules depend on that +/// distinction. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum InterfaceRole { + #[default] + Normal, + SharedServer, + LocalClient, + SharedInstancePeer, +} + +impl InterfaceRole { + pub fn as_str(self) -> &'static str { + match self { + Self::Normal => "normal", + Self::SharedServer => "shared_server", + Self::LocalClient => "local_client", + Self::SharedInstancePeer => "shared_instance_peer", + } + } +} + +#[derive(Debug)] +pub struct InboundPacket { + pub raw: Bytes, + pub interface_id: InterfaceId, + pub rssi: Option, + pub snr: Option, + pub q: Option, +} + +#[derive(Debug)] +pub struct OutboundRequest { + pub raw: Bytes, + pub destination_hash: [u8; 16], +} + +/// Periodic maintenance tick. Drives cache culling, retransmit scheduling, +/// and rate-limit decay so the actor needs no internal timer. +#[derive(Debug)] +pub struct TimerTick { + pub timestamp: f64, +} + +/// Metadata and TX handle for one registered interface. The actor owns the +/// sender; driver code holds only the matching receiver. +pub struct InterfaceEntry { + pub name: String, + pub mode: InterfaceMode, + pub role: InterfaceRole, + pub direction: InterfaceDirection, + pub bitrate: u64, + pub mtu: u32, + pub tx: mpsc::Sender, + pub ifac_key: Option<[u8; 64]>, + pub ifac_size: usize, + pub announce_cap: f64, + /// Earliest Unix time at which the next announce may be sent — enforces + /// `ANNOUNCE_CAP` spacing in the outbound path. + pub announce_allowed_at: f64, + pub announce_rate_target: Option, + pub announce_rate_grace: Option, + pub announce_rate_penalty: Option, + /// Shared with the driver so the actor sees online-state flips without + /// polling. `None` when the driver doesn't expose one (e.g. in-memory test + /// interfaces). + pub online: Option>, + pub rxb: Option>, + pub txb: Option>, + /// Incremented when an outbound `try_send` cannot enqueue — surfaced in + /// interface stats to flag a driver whose receiver is falling behind. + pub tx_drops: Arc, + pub ingress: IngressController, + /// Announces awaiting bandwidth-capped retransmission. Drained in + /// hop-priority order (lowest hops first, oldest among ties). + pub announce_queue: Vec, +} + +impl InterfaceEntry { + /// Minimal entry with defaults for everything optional. Use the + /// chainable `with_*` methods to fill in IFAC, rate limits, and + /// driver-shared counters. + pub fn new( + name: String, + mode: InterfaceMode, + direction: InterfaceDirection, + bitrate: u64, + mtu: u32, + tx: mpsc::Sender, + ) -> Self { + Self { + name, + mode, + role: InterfaceRole::Normal, + direction, + bitrate, + mtu, + tx, + ifac_key: None, + ifac_size: 0, + announce_cap: crate::constants::ANNOUNCE_CAP, + announce_allowed_at: 0.0, + announce_rate_target: None, + announce_rate_grace: None, + announce_rate_penalty: None, + online: None, + rxb: None, + txb: None, + tx_drops: Arc::new(std::sync::atomic::AtomicU64::new(0)), + ingress: IngressController::new(), + announce_queue: Vec::new(), + } + } + + pub fn with_ifac(mut self, key: [u8; 64], size: usize) -> Self { + self.ifac_key = Some(key); + self.ifac_size = size; + self + } + + pub fn with_announce_rate(mut self, target: f64, grace: u32, penalty: f64) -> Self { + self.announce_rate_target = Some(target); + self.announce_rate_grace = Some(grace); + self.announce_rate_penalty = Some(penalty); + self + } + + pub fn with_role(mut self, role: InterfaceRole) -> Self { + self.role = role; + self + } + + pub fn with_counters( + mut self, + online: Arc, + rxb: Arc, + txb: Arc, + ) -> Self { + self.online = Some(online); + self.rxb = Some(rxb); + self.txb = Some(txb); + self + } +} + +/// Announce queued for bandwidth-capped retransmission on an interface. +#[derive(Debug, Clone)] +pub struct QueuedAnnounce { + pub destination_hash: [u8; 16], + /// Queue-insertion time (Unix seconds); used as tie-breaker in priority ordering. + pub time: f64, + pub hops: u8, + pub raw: Bytes, +} + +impl std::fmt::Debug for InterfaceEntry { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("InterfaceEntry") + .field("name", &self.name) + .field("mode", &self.mode) + .field("role", &self.role) + .field("direction", &self.direction) + .field("bitrate", &self.bitrate) + .field("mtu", &self.mtu) + .field("ifac_size", &self.ifac_size) + .field("announce_cap", &self.announce_cap) + .field("announce_allowed_at", &self.announce_allowed_at) + .field("held_announces", &self.ingress.held_count()) + .field("announce_queue", &self.announce_queue.len()) + .finish() + } +} + +/// Event pushed to a registered announce handler. +#[derive(Debug, Clone)] +pub struct AnnounceHandlerEvent { + pub destination_hash: [u8; 16], + /// Identity hash recovered from the validated announce payload. + pub identity_hash: Option<[u8; 16]>, + pub announce_packet_hash: [u8; 32], + pub is_path_response: bool, + pub hops: u8, + pub app_data: Option>, + /// X25519 || Ed25519 public key from the announce payload. + pub public_key: Option<[u8; 64]>, + pub ratchet: Option<[u8; 32]>, + /// `SHA-256(app_name)[:10]` of the aspect this destination announced + /// under. Zero array if the announce arrived without a payload (degenerate + /// case — handlers with `aspect_filter == None` still receive it). + pub name_hash: [u8; 10], +} + +/// Every mutation of transport state enters through this enum — the actor +/// dispatches on the variant, so adding a new operation is a matter of adding +/// a variant and a match arm rather than exposing a new lock or shared type. +// This is the transport actor's public message surface. Boxing individual +// variants would churn all senders/receivers for little runtime benefit. +#[allow(clippy::large_enum_variant)] +pub enum TransportMessage { + Inbound(InboundPacket), + Outbound(OutboundRequest), + OutboundAttached { + request: OutboundRequest, + interface_id: InterfaceId, + }, + Tick(TimerTick), + /// Read-only query paired with a oneshot reply channel — used for all + /// RPC and introspection so callers don't need direct state access. + Rpc { + query: TransportQuery, + response_tx: tokio::sync::oneshot::Sender, + }, + RegisterDestination { + hash: [u8; 16], + app_name: String, + delivery_tx: Option>, + }, + DeregisterDestination { + hash: [u8; 16], + }, + RegisterAnnounceHandler { + aspect_filter: Option, + receive_path_responses: bool, + callback_tx: mpsc::Sender, + }, + /// Remove handler(s) whose `aspect_filter` matches; `None` removes all. + /// Handlers with closed senders are also reaped on dispatch. + DeregisterAnnounceHandler { + aspect_filter: Option, + }, + /// Ask the actor to satisfy a packet request: replay from its recent- + /// announce cache when possible, otherwise emit a CacheRequest packet. + CacheRequest { + packet_hash: [u8; 32], + destination_hash: [u8; 16], + }, + RequestPath { + destination_hash: [u8; 16], + }, + RegisterInterface { + id: InterfaceId, + entry: InterfaceEntry, + }, + DeregisterInterface { + id: InterfaceId, + }, + SetStoragePaths { + storage_dir: std::path::PathBuf, + }, + SetTransportEnabled { + enabled: bool, + }, + SetTransportIdentity { + identity_hash: [u8; 16], + }, + SetBlackholeSources { + sources: Vec<[u8; 16]>, + }, + /// Shared-instance connection dropped; pause packet processing until the + /// matching `SharedConnectionRestored` arrives. + SharedConnectionLost, + SharedConnectionRestored { + interface_id: InterfaceId, + }, + /// Driver-built tunnel synthesis packet ready for transmission on the + /// given interface. The actor does not build these because it does not + /// hold the signing identity. + SynthesizeTunnel { + interface_id: InterfaceId, + raw_packet: Bytes, + }, + /// Register an outbound-packet receipt so the inbound path can match + /// arriving proofs back to `msg_id`. + RegisterReceipt { + truncated_hash: [u8; 16], + full_hash: [u8; 32], + msg_id: String, + /// Override default 180s timeout when `Some`. + timeout: Option, + }, + /// Record a new link in the table. `initiator=true` means we started the + /// handshake, so the entry is pending until `ActivateLink` arrives. + RegisterLink { + link_id: [u8; 16], + destination_hash: [u8; 16], + interface_id: InterfaceId, + next_hop: Option<[u8; 16]>, + remaining_hops: u8, + initiator: bool, + }, + /// Promote a pending (initiator) link to validated. + ActivateLink { + link_id: [u8; 16], + }, + /// Block the caller until a path to `dest` is learned or the caller's + /// timeout fires. Used by request APIs that must not return before + /// forwarding is possible. + AwaitPath { + dest: [u8; 16], + reply: tokio::sync::oneshot::Sender, + }, + Shutdown, +} + +/// Static string name for a `TransportMessage` variant, used as a `msg` +/// field on the `actor.handle_message` span. Using a fixed &'static str +/// keeps the span field cheap (no allocation in the hot path). +pub fn msg_variant_name(msg: &TransportMessage) -> &'static str { + match msg { + TransportMessage::Inbound(_) => "Inbound", + TransportMessage::Outbound(_) => "Outbound", + TransportMessage::OutboundAttached { .. } => "OutboundAttached", + TransportMessage::Tick(_) => "Tick", + TransportMessage::Rpc { .. } => "Rpc", + TransportMessage::RegisterDestination { .. } => "RegisterDestination", + TransportMessage::DeregisterDestination { .. } => "DeregisterDestination", + TransportMessage::RegisterAnnounceHandler { .. } => "RegisterAnnounceHandler", + TransportMessage::DeregisterAnnounceHandler { .. } => "DeregisterAnnounceHandler", + TransportMessage::CacheRequest { .. } => "CacheRequest", + TransportMessage::RequestPath { .. } => "RequestPath", + TransportMessage::RegisterInterface { .. } => "RegisterInterface", + TransportMessage::DeregisterInterface { .. } => "DeregisterInterface", + TransportMessage::SetStoragePaths { .. } => "SetStoragePaths", + TransportMessage::SetTransportEnabled { .. } => "SetTransportEnabled", + TransportMessage::SetTransportIdentity { .. } => "SetTransportIdentity", + TransportMessage::SetBlackholeSources { .. } => "SetBlackholeSources", + TransportMessage::SharedConnectionLost => "SharedConnectionLost", + TransportMessage::SharedConnectionRestored { .. } => "SharedConnectionRestored", + TransportMessage::SynthesizeTunnel { .. } => "SynthesizeTunnel", + TransportMessage::RegisterReceipt { .. } => "RegisterReceipt", + TransportMessage::RegisterLink { .. } => "RegisterLink", + TransportMessage::ActivateLink { .. } => "ActivateLink", + TransportMessage::AwaitPath { .. } => "AwaitPath", + TransportMessage::Shutdown => "Shutdown", + } +} + +/// Read-mostly queries carried by `TransportMessage::Rpc`. +#[derive(Debug, Clone)] +pub enum TransportQuery { + GetPathTable, + GetInterfaceStats, + GetRateTable, + GetLinkCount, + GetRecentAnnounces, + GetNextHop { + dest: [u8; 16], + }, + GetNextHopIfName { + dest: [u8; 16], + }, + GetNextHopBitrate { + dest: [u8; 16], + }, + GetNextHopInterfaceId { + dest: [u8; 16], + }, + GetPacketRssi { + packet_hash: [u8; 32], + }, + GetPacketSnr { + packet_hash: [u8; 32], + }, + GetPacketQ { + packet_hash: [u8; 32], + }, + /// First-hop timeout: `MTU * per_byte_latency + DEFAULT_PER_HOP_TIMEOUT`. + FirstHopTimeout { + dest: [u8; 16], + }, + /// Extra link-proof timeout for a slow interface: `MTU * per_byte_latency`. + ExtraLinkProofTimeout { + interface_id: InterfaceId, + }, + DropPath { + dest: [u8; 16], + }, + DropAnnounceQueues, + GetBlackholedIdentities, + BlackholeIdentity { + hash: [u8; 16], + ttl: Option, + reason: crate::blackhole::BlackholeReason, + reason_label: Option, + }, + UnblackholeIdentity { + hash: [u8; 16], + }, + /// Single-hash blackhole lookup returning `BoolResult`. + IsBlackholed { + hash: [u8; 16], + }, + /// Drop every non-Manual entry; response is `IntResult(count_cleared)`. + /// Separate from unblackhole-by-hash so operators can flush auto-populated + /// entries without losing their explicit blocks. + ClearSystemBlackholes, + /// Build this node's distributed blackhole `/list` manifest. Response is + /// `Data(msgpack)`. + BuildBlackholeManifest { + publisher: [u8; 16], + }, + /// Merge a distributed blackhole `/list` manifest. Response is + /// `IntResult(count_applied)`. + ApplyBlackholeManifest { + payload: Vec, + }, + HaltInterface { + id: InterfaceId, + }, + ResumeInterface { + id: InterfaceId, + }, + DropAllVia { + next_hop: [u8; 16], + }, + /// Remote-status RPC — interface stats + optional link count, wire-format + /// compatible with `Transport.remote_status_handler`. + RemoteStatus { + include_link_count: bool, + }, + /// Remote-path RPC — path table filtered by destination and hop limit, + /// wire-format compatible with `Transport.remote_path_handler`. + RemotePath { + command: String, + destination: Option<[u8; 16]>, + max_hops: Option, + }, + SetPathState { + dest: [u8; 16], + state: crate::constants::PathState, + }, + GetPathState { + dest: [u8; 16], + }, + PathIsUnresponsive { + dest: [u8; 16], + }, + /// Pin / unpin a destination from the cache. While retained, the + /// maintenance sweep will not reap the entry regardless of age. + /// Returns `BoolResult(true)` when the destination is known to the + /// cache, `false` when not. + RetainDestination { + dest: [u8; 16], + }, + UseDestination { + dest: [u8; 16], + }, + UnretainDestination { + dest: [u8; 16], + }, + /// Immediate cleanup trigger. Returns `IntResult(entries_remaining)`. + /// The actor tick runs cleanup every 5 minutes regardless. + CleanKnownDestinations, +} + +#[derive(Debug)] +pub enum TransportQueryResponse { + PathTable(Vec), + InterfaceStats(Vec), + RateTable(Vec), + Announces(Vec), + IntResult(i64), + FloatResult(Option), + StringResult(Option), + HashResult(Option<[u8; 16]>), + BoolResult(bool), + PathStateResult(crate::constants::PathState), + BlackholeList(Vec), + /// Pre-serialized binary payload (msgpack for remote-* RPCs). + Data(Vec), + Ok, + Error(String), +} + +#[derive(Debug, Clone)] +pub struct PathTableRpcEntry { + pub hash: [u8; 16], + pub timestamp: f64, + pub via: Option<[u8; 16]>, + pub hops: u8, + pub expires: f64, + pub interface: String, +} + +#[derive(Debug, Clone)] +pub struct InterfaceStatRpcEntry { + pub id: InterfaceId, + pub name: String, + pub rx_bytes: u64, + pub tx_bytes: u64, + pub rx_rate: u64, + pub tx_rate: u64, + pub online: bool, + pub bitrate: u64, + pub mtu: u32, + pub mode: String, + pub role: String, + pub announce_queue: Option, + pub held_announces: u64, + pub incoming_announce_frequency: f64, + pub outgoing_announce_frequency: f64, + pub clients: Option, + pub announce_rate_target: Option, + pub announce_rate_grace: Option, + pub announce_rate_penalty: Option, + pub announce_cap: f64, + pub ifac_size: usize, + pub tx_drops: u64, +} + +#[derive(Debug, Clone)] +pub struct RateTableRpcEntry { + pub hash: [u8; 16], + pub rate: f64, + pub last: f64, + pub rate_violations: u32, + pub blocked_until: f64, + pub timestamps: Vec, +} + +#[derive(Debug, Clone)] +pub struct AnnounceRpcEntry { + pub dest_hash: [u8; 16], + pub hops: u8, + pub app_data: Option>, + pub timestamp: f64, + pub public_key: Option<[u8; 64]>, + pub ratchet: Option<[u8; 32]>, + /// Pinned via `RetainDestination`; the maintenance sweep skips the + /// entry regardless of age while this is `true`. + pub retained: bool, +} + +#[derive(Debug, Clone)] +pub struct BlackholeRpcEntry { + pub identity_hash: [u8; 16], + pub source: Option<[u8; 16]>, + pub created: f64, + /// `None` means permanent. + pub ttl: Option, + pub reason: crate::blackhole::BlackholeReason, + pub reason_label: Option, +} + +impl std::fmt::Debug for TransportMessage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Inbound(p) => f.debug_tuple("Inbound").field(p).finish(), + Self::Outbound(r) => f.debug_tuple("Outbound").field(r).finish(), + Self::OutboundAttached { + request, + interface_id, + } => f + .debug_struct("OutboundAttached") + .field("request", request) + .field("interface_id", interface_id) + .finish(), + Self::Tick(t) => f.debug_tuple("Tick").field(t).finish(), + Self::Rpc { query, .. } => f.debug_struct("Rpc").field("query", query).finish(), + Self::RegisterDestination { hash, app_name, .. } => f + .debug_struct("RegisterDestination") + .field("hash", hash) + .field("app_name", app_name) + .finish(), + Self::DeregisterDestination { hash } => f + .debug_struct("DeregisterDestination") + .field("hash", hash) + .finish(), + Self::RegisterAnnounceHandler { aspect_filter, .. } => f + .debug_struct("RegisterAnnounceHandler") + .field("aspect_filter", aspect_filter) + .finish(), + Self::DeregisterAnnounceHandler { aspect_filter } => f + .debug_struct("DeregisterAnnounceHandler") + .field("aspect_filter", aspect_filter) + .finish(), + Self::CacheRequest { + packet_hash, + destination_hash, + } => f + .debug_struct("CacheRequest") + .field("packet_hash", packet_hash) + .field("destination_hash", destination_hash) + .finish(), + Self::RequestPath { destination_hash } => f + .debug_struct("RequestPath") + .field("destination_hash", destination_hash) + .finish(), + Self::RegisterInterface { id, entry } => f + .debug_struct("RegisterInterface") + .field("id", id) + .field("entry", entry) + .finish(), + Self::DeregisterInterface { id } => f + .debug_struct("DeregisterInterface") + .field("id", id) + .finish(), + Self::SetStoragePaths { storage_dir } => f + .debug_struct("SetStoragePaths") + .field("storage_dir", storage_dir) + .finish(), + Self::SetTransportEnabled { enabled } => f + .debug_struct("SetTransportEnabled") + .field("enabled", enabled) + .finish(), + Self::SetTransportIdentity { identity_hash } => f + .debug_struct("SetTransportIdentity") + .field("identity_hash", identity_hash) + .finish(), + Self::SetBlackholeSources { sources } => f + .debug_struct("SetBlackholeSources") + .field("sources", sources) + .finish(), + Self::SharedConnectionLost => f.debug_struct("SharedConnectionLost").finish(), + Self::SharedConnectionRestored { interface_id } => f + .debug_struct("SharedConnectionRestored") + .field("interface_id", interface_id) + .finish(), + Self::SynthesizeTunnel { interface_id, .. } => f + .debug_struct("SynthesizeTunnel") + .field("interface_id", interface_id) + .finish(), + Self::RegisterReceipt { + truncated_hash, + msg_id, + .. + } => f + .debug_struct("RegisterReceipt") + .field("truncated_hash", truncated_hash) + .field("msg_id", msg_id) + .finish(), + Self::RegisterLink { + link_id, + destination_hash, + initiator, + .. + } => f + .debug_struct("RegisterLink") + .field("link_id", link_id) + .field("destination_hash", destination_hash) + .field("initiator", initiator) + .finish(), + Self::ActivateLink { link_id } => f + .debug_struct("ActivateLink") + .field("link_id", link_id) + .finish(), + Self::AwaitPath { dest, .. } => { + f.debug_struct("AwaitPath").field("dest", dest).finish() + } + Self::Shutdown => write!(f, "Shutdown"), + } + } +} diff --git a/crates/rns-transport/src/path_table.rs b/crates/rns-transport/src/path_table.rs new file mode 100644 index 0000000..50edf17 --- /dev/null +++ b/crates/rns-transport/src/path_table.rs @@ -0,0 +1,371 @@ +use std::collections::{HashMap, VecDeque}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::constants::{ + AP_PATH_TIME, DESTINATION_TIMEOUT, InterfaceMode, MAX_RANDOM_BLOBS, PERSIST_RANDOM_BLOBS, + PathState, ROAMING_PATH_TIME, +}; +use crate::messages::InterfaceId; +use rns_wire::types::DestHash; + +/// One known path to a destination. +#[derive(Debug, Clone)] +pub struct PathEntry { + /// Learn time (Unix seconds). + pub timestamp: f64, + /// Next-hop transport id; `None` for a directly-connected neighbour. + pub next_hop: Option<[u8; 16]>, + pub hops: u8, + /// Expiry (Unix seconds), derived from interface mode at insert time. + pub expires: f64, + /// Recent announce-random blobs, capped at `MAX_RANDOM_BLOBS` to bound + /// anti-replay memory on long-lived paths. + pub random_blobs: VecDeque<[u8; 10]>, + pub interface_id: InterfaceId, + /// Hash of the cached announce packet — used to satisfy CacheRequest + /// without holding the full packet bytes. + pub packet_hash: Option<[u8; 32]>, +} + +impl PathEntry { + pub fn new( + next_hop: Option<[u8; 16]>, + hops: u8, + interface_id: InterfaceId, + interface_mode: InterfaceMode, + ) -> Self { + let now = now_f64(); + let expires = now + path_expiry(interface_mode) as f64; + + Self { + timestamp: now, + next_hop, + hops, + expires, + random_blobs: VecDeque::new(), + interface_id, + packet_hash: None, + } + } + + pub fn add_random_blob(&mut self, blob: [u8; 10]) { + if self.random_blobs.len() >= MAX_RANDOM_BLOBS { + self.random_blobs.pop_front(); + } + self.random_blobs.push_back(blob); + } + + pub fn has_random_blob(&self, blob: &[u8; 10]) -> bool { + self.random_blobs.contains(blob) + } + + pub fn is_expired(&self) -> bool { + now_f64() > self.expires + } + + /// Most recent blobs to persist — older entries can be regenerated from + /// the wire on replay, so we cap the snapshot at `PERSIST_RANDOM_BLOBS` + /// to keep the on-disk table small. + pub fn blobs_for_persist(&self) -> Vec<[u8; 10]> { + let start = self.random_blobs.len().saturating_sub(PERSIST_RANDOM_BLOBS); + self.random_blobs.iter().skip(start).copied().collect() + } +} + +/// Destination-hash → path mapping plus a parallel liveness state map so we +/// can probe unresponsive paths without rewriting the entries. +pub struct PathTable { + entries: HashMap, + states: HashMap, +} + +impl PathTable { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + states: HashMap::new(), + } + } + + /// Insert or replace a path entry. The parallel liveness state is + /// cleared so a fresh/replacement entry never inherits a stale + /// `Responsive`/`Unresponsive` reading from its predecessor. `get_state` + /// reads a missing entry as `Unknown`, so clearing is equivalent to + /// writing `Unknown` but avoids holding an entry we'd only overwrite. + /// + /// Python Reticulum 1.1.8 (`8c082b2`) fixes the same bug by clearing state + /// at the inbound insert sites. The Rust transport has additional insert + /// sites (announce install, PathResponse install, tunnel path restore, disk + /// load), so the invariant is enforced here: state is never older than the + /// entry it describes. + pub fn insert(&mut self, dest_hash: impl Into, entry: PathEntry) { + let hash: DestHash = dest_hash.into(); + self.states.remove(&hash); + self.entries.insert(hash, entry); + } + + pub fn get(&self, dest_hash: &[u8; 16]) -> Option<&PathEntry> { + self.entries.get(dest_hash) + } + + pub fn get_mut(&mut self, dest_hash: &[u8; 16]) -> Option<&mut PathEntry> { + self.entries.get_mut(dest_hash) + } + + /// A path exists and has not yet expired. Callers should prefer this + /// over `get().is_some()` so stale entries are not treated as routable. + pub fn has_path(&self, dest_hash: &[u8; 16]) -> bool { + self.entries.get(dest_hash).is_some_and(|e| !e.is_expired()) + } + + pub fn hops_to(&self, dest_hash: &[u8; 16]) -> Option { + self.entries.get(dest_hash).map(|e| e.hops) + } + + pub fn remove(&mut self, dest_hash: &[u8; 16]) -> Option { + self.states.remove(dest_hash); + self.entries.remove(dest_hash) + } + + /// Drop every path whose interface id matches — used when an interface + /// goes down so we don't keep routing through a dead transport. + pub fn drop_all_via(&mut self, interface_id: InterfaceId) -> usize { + let before = self.entries.len(); + self.entries.retain(|_, e| e.interface_id != interface_id); + before - self.entries.len() + } + + pub fn drop_all_via_next_hop(&mut self, next_hop: &[u8; 16]) -> usize { + let before = self.entries.len(); + self.entries.retain(|_, e| e.next_hop != Some(*next_hop)); + before - self.entries.len() + } + + /// Force-expire a path and cull immediately. Useful when the caller + /// already knows the path is bad (e.g. a link proof failed) and + /// shouldn't wait for the periodic cull cycle. + pub fn expire(&mut self, dest_hash: &[u8; 16]) -> bool { + if let Some(entry) = self.entries.get_mut(dest_hash) { + entry.expires = 0.0; + self.cull_expired(); + true + } else { + false + } + } + + pub fn set_state(&mut self, dest_hash: impl Into, state: PathState) { + self.states.insert(dest_hash.into(), state); + } + + pub fn get_state(&self, dest_hash: &[u8; 16]) -> PathState { + self.states + .get(dest_hash) + .copied() + .unwrap_or(PathState::Unknown) + } + + /// Full cull pass. Prefer `cull_expired_batch` on the hot path to bound + /// per-tick work. + pub fn cull_expired(&mut self) -> usize { + let before = self.entries.len(); + self.entries.retain(|_, entry| !entry.is_expired()); + self.states + .retain(|hash, _| self.entries.contains_key(hash)); + before - self.entries.len() + } + + /// Batched cull — removes at most `limit` expired entries so the actor + /// cannot stall on a very large path table. + pub fn cull_expired_batch(&mut self, limit: usize) -> usize { + let to_remove: Vec = self + .entries + .iter() + .filter(|(_, entry)| entry.is_expired()) + .take(limit) + .map(|(hash, _)| *hash) + .collect(); + let count = to_remove.len(); + for hash in &to_remove { + self.entries.remove(hash.as_bytes()); + self.states.remove(hash.as_bytes()); + } + count + } + + /// Drop paths whose interface id is no longer active. + pub fn cull_dead_interfaces( + &mut self, + active_interfaces: &std::collections::HashSet, + ) -> usize { + let before = self.entries.len(); + self.entries + .retain(|_, entry| active_interfaces.contains(&entry.interface_id)); + self.states + .retain(|hash, _| self.entries.contains_key(hash)); + before - self.entries.len() + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.entries.iter() + } +} + +impl Default for PathTable { + fn default() -> Self { + Self::new() + } +} + +/// Path lifetime by interface mode — access points and roaming interfaces +/// hold paths for shorter windows because they're expected to churn faster +/// than gateway/boundary links. +fn path_expiry(mode: InterfaceMode) -> u64 { + match mode { + InterfaceMode::AccessPoint => AP_PATH_TIME, + InterfaceMode::Roaming => ROAMING_PATH_TIME, + _ => DESTINATION_TIMEOUT, + } +} + +fn now_f64() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_path_table_basic() { + let mut table = PathTable::new(); + let hash = [0xAA; 16]; + let entry = PathEntry::new(Some([0xBB; 16]), 3, 1, InterfaceMode::Gateway); + table.insert(hash, entry); + + assert!(table.has_path(&hash)); + assert_eq!(table.hops_to(&hash), Some(3)); + assert_eq!(table.len(), 1); + } + + #[test] + fn test_path_table_remove() { + let mut table = PathTable::new(); + let hash = [0xAA; 16]; + table.insert(hash, PathEntry::new(None, 0, 1, InterfaceMode::Gateway)); + assert!(table.has_path(&hash)); + table.remove(&hash); + assert!(!table.has_path(&hash)); + } + + #[test] + fn test_random_blob_dedup() { + let mut entry = PathEntry::new(None, 0, 1, InterfaceMode::Gateway); + let blob = [0x42; 10]; + assert!(!entry.has_random_blob(&blob)); + entry.add_random_blob(blob); + assert!(entry.has_random_blob(&blob)); + } + + #[test] + fn test_random_blob_max() { + let mut entry = PathEntry::new(None, 0, 1, InterfaceMode::Gateway); + for i in 0..MAX_RANDOM_BLOBS + 10 { + let mut blob = [0u8; 10]; + blob[0] = i as u8; + entry.add_random_blob(blob); + } + assert_eq!(entry.random_blobs.len(), MAX_RANDOM_BLOBS); + } + + #[test] + fn test_path_state() { + let mut table = PathTable::new(); + let hash = [0xAA; 16]; + assert_eq!(table.get_state(&hash), PathState::Unknown); + table.set_state(hash, PathState::Responsive); + assert_eq!(table.get_state(&hash), PathState::Responsive); + } + + /// Regression test for the Python 1.1.8 path-state race (`8c082b2`). + /// A fresh or replacement `PathEntry` must never inherit a stale + /// `Responsive`/`Unresponsive` reading from its predecessor, or + /// probing won't resume after a reroute. + #[test] + fn test_insert_clears_path_state() { + let mut table = PathTable::new(); + let hash = [0xAA; 16]; + table.insert(hash, PathEntry::new(None, 0, 1, InterfaceMode::Gateway)); + table.set_state(hash, PathState::Responsive); + assert_eq!(table.get_state(&hash), PathState::Responsive); + + // Insert a replacement entry (e.g. a fresh announce through a new + // next hop). Liveness state must reset to Unknown so the actor + // probes before trusting the new path. + table.insert( + hash, + PathEntry::new(Some([0xBB; 16]), 2, 2, InterfaceMode::Gateway), + ); + assert_eq!(table.get_state(&hash), PathState::Unknown); + } + + #[test] + fn test_expire_force_cull() { + let mut table = PathTable::new(); + let hash = [0xBB; 16]; + table.insert(hash, PathEntry::new(None, 0, 1, InterfaceMode::Gateway)); + assert!(table.has_path(&hash)); + + let result = table.expire(&hash); + assert!(result); + assert!(!table.has_path(&hash)); + assert_eq!(table.len(), 0); + } + + #[test] + fn test_expire_nonexistent() { + let mut table = PathTable::new(); + let result = table.expire(&[0xFF; 16]); + assert!(!result); + } + + #[test] + fn test_cull_dead_interfaces() { + let mut table = PathTable::new(); + let mut active = std::collections::HashSet::new(); + active.insert(1u64); + active.insert(2u64); + + table.insert( + [0xAA; 16], + PathEntry::new(None, 0, 1, InterfaceMode::Gateway), + ); + table.insert( + [0xBB; 16], + PathEntry::new(None, 1, 2, InterfaceMode::Gateway), + ); + table.insert( + [0xCC; 16], + PathEntry::new(None, 2, 99, InterfaceMode::Gateway), + ); + + assert_eq!(table.len(), 3); + let culled = table.cull_dead_interfaces(&active); + assert_eq!(culled, 1); + assert_eq!(table.len(), 2); + assert!(table.has_path(&[0xAA; 16])); + assert!(table.has_path(&[0xBB; 16])); + assert!(!table.has_path(&[0xCC; 16])); + } +} diff --git a/crates/rns-transport/src/persistence.rs b/crates/rns-transport/src/persistence.rs new file mode 100644 index 0000000..cf02f5a --- /dev/null +++ b/crates/rns-transport/src/persistence.rs @@ -0,0 +1,1227 @@ +//! Atomic msgpack persistence for transport tables. `atomic_write` is +//! write-to-tmp + rename so a crash leaves either the old or new file. + +use std::collections::HashMap; +use std::path::Path; + +use rmpv::Value; +use serde::{Deserialize, Serialize}; + +use crate::hashlist::PacketHashlist; +use crate::path_table::PathTable; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedPathEntry { + pub destination_hash: Vec, + pub timestamp: f64, + pub next_hop: Option>, + pub hops: u8, + pub expires: f64, + pub random_blobs: Vec>, + pub interface_id: u64, + /// Stable identifier for the interface that learned this path. The load + /// path uses it to remap the volatile `interface_id` (re-allocated from + /// zero on every actor boot) once the matching interface registers. + #[serde(default)] + pub interface_name: Option, + /// Python's `destination_table` stores the full hash of `str(interface)`. + /// Keep it in the Rust sidecar too so sidecar/canonical loads can share + /// the same rebinding path. + #[serde(default)] + pub interface_hash: Option>, + /// Full hash of the cached announce packet backing this path. + #[serde(default)] + pub packet_hash: Option>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedPathTable { + pub entries: Vec, + pub version: u32, +} + +impl PersistedPathTable { + pub const CURRENT_VERSION: u32 = 4; + pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2, 3, 4]; +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedHashlist { + pub hashes: Vec>, + pub version: u32, +} + +pub fn save_path_table( + table: &PathTable, + interface_names: &HashMap, + path: &Path, +) -> Result<(), PersistenceError> { + let mut entries = Vec::new(); + for (hash, entry) in table.iter() { + let interface_name = interface_names.get(&entry.interface_id).cloned(); + // Skip entries whose interface has already been deregistered — we + // can't restore them safely (no name → no remap target on load). + if interface_name.is_none() { + continue; + } + let interface_hash = interface_name + .as_deref() + .map(interface_hash_from_name) + .map(|h| h.to_vec()); + entries.push(PersistedPathEntry { + destination_hash: hash.to_vec(), + timestamp: entry.timestamp, + next_hop: entry.next_hop.map(|h| h.to_vec()), + hops: entry.hops, + expires: entry.expires, + random_blobs: entry + .blobs_for_persist() + .iter() + .map(|b| b.to_vec()) + .collect(), + interface_id: entry.interface_id, + interface_name, + interface_hash, + packet_hash: entry.packet_hash.map(|h| h.to_vec()), + }); + } + + let persisted = PersistedPathTable { + entries, + version: PersistedPathTable::CURRENT_VERSION, + }; + + atomic_write(path, &persisted) +} + +/// Loads a path-table snapshot. Entries without `interface_name` (v1/v2) +/// are dropped at the actor boundary since `interface_id` is volatile. +pub fn load_path_table(path: &Path) -> Result, PersistenceError> { + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let persisted: PersistedPathTable = + rmp_serde::from_slice(&data).map_err(|e| PersistenceError::Deserialize(e.to_string()))?; + + if !PersistedPathTable::SUPPORTED_VERSIONS.contains(&persisted.version) { + return Err(PersistenceError::VersionMismatch { + expected: PersistedPathTable::CURRENT_VERSION, + found: persisted.version, + }); + } + + Ok(persisted.entries) +} + +#[derive(Debug, Clone)] +pub struct PythonDestinationEntry { + pub destination_hash: [u8; 16], + pub timestamp: f64, + pub received_from: [u8; 16], + pub hops: u8, + pub expires: f64, + pub random_blobs: Vec<[u8; 10]>, + pub interface_hash: [u8; 32], + pub packet_hash: [u8; 32], +} + +#[derive(Debug, Clone)] +pub struct PythonCachedAnnounce { + pub raw_packet: Vec, + pub interface_reference: Option, +} + +pub fn interface_hash_from_name(name: &str) -> [u8; 32] { + rns_crypto::sha::full_hash(name.as_bytes()) +} + +pub fn save_python_destination_table( + table: &PathTable, + interface_names: &HashMap, + path: &Path, +) -> Result<(), PersistenceError> { + let mut entries = Vec::new(); + for (hash, entry) in table.iter() { + let Some(interface_name) = interface_names.get(&entry.interface_id) else { + continue; + }; + let Some(packet_hash) = entry.packet_hash else { + continue; + }; + let received_from = entry.next_hop.unwrap_or(*hash.as_bytes()); + let random_blobs = entry + .blobs_for_persist() + .iter() + .map(|b| Value::Binary(b.to_vec())) + .collect(); + entries.push(Value::Array(vec![ + Value::Binary(hash.to_vec()), + Value::F64(entry.timestamp), + Value::Binary(received_from.to_vec()), + Value::Integer((entry.hops as u64).into()), + Value::F64(entry.expires), + Value::Array(random_blobs), + Value::Binary(interface_hash_from_name(interface_name).to_vec()), + Value::Binary(packet_hash.to_vec()), + ])); + } + + let mut serialized = Vec::new(); + rmpv::encode::write_value(&mut serialized, &Value::Array(entries)) + .map_err(|e| PersistenceError::Serialize(e.to_string()))?; + atomic_write_bytes(path, &serialized) +} + +pub fn load_python_destination_table( + path: &Path, +) -> Result, PersistenceError> { + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let value = rmpv::decode::read_value(&mut std::io::Cursor::new(data)) + .map_err(|e| PersistenceError::Deserialize(e.to_string()))?; + let entries = match value { + Value::Array(entries) => entries, + other => { + return Err(PersistenceError::Deserialize(format!( + "expected destination_table array, got {other:?}" + ))); + } + }; + + let mut out = Vec::new(); + for entry in entries { + let fields = match entry { + Value::Array(fields) => fields, + _ => continue, + }; + if fields.len() < 8 { + return Err(PersistenceError::Deserialize( + "short destination_table entry".to_string(), + )); + } + let Some(destination_hash) = value_bin_array::<16>(&fields[0]) else { + continue; + }; + let timestamp = value_f64(&fields[1]).unwrap_or(0.0); + let Some(received_from) = value_bin_array::<16>(&fields[2]) else { + continue; + }; + let Some(hops) = value_u8(&fields[3]) else { + continue; + }; + let expires = value_f64(&fields[4]).unwrap_or(0.0); + let random_blobs = match &fields[5] { + Value::Array(values) => values + .iter() + .filter_map(value_bin_array::<10>) + .collect::>(), + _ => Vec::new(), + }; + let Some(interface_hash) = value_bin_array::<32>(&fields[6]) else { + continue; + }; + let Some(packet_hash) = value_bin_array::<32>(&fields[7]) else { + continue; + }; + out.push(PythonDestinationEntry { + destination_hash, + timestamp, + received_from, + hops, + expires, + random_blobs, + interface_hash, + packet_hash, + }); + } + Ok(out) +} + +pub fn save_python_announce_cache_for_paths<'a, I>( + path_entries: &PathTable, + announces: I, + interface_names: &HashMap, + announce_cache_dir: &Path, +) -> Result<(), PersistenceError> +where + I: IntoIterator, +{ + std::fs::create_dir_all(announce_cache_dir).map_err(PersistenceError::Io)?; + let announces_by_dest: HashMap<[u8; 16], &crate::actor::RecentAnnounce> = + announces.into_iter().map(|a| (a.dest_hash, a)).collect(); + + for (dest_hash, path_entry) in path_entries.iter() { + let Some(packet_hash) = path_entry.packet_hash else { + continue; + }; + let Some(announce) = announces_by_dest.get(dest_hash.as_bytes()) else { + continue; + }; + if announce.raw_packet.is_empty() { + continue; + } + let interface_reference = interface_names + .get(&path_entry.interface_id) + .map(|name| Value::String(name.as_str().into())) + .unwrap_or(Value::Nil); + let value = Value::Array(vec![ + Value::Binary(announce.raw_packet.clone()), + interface_reference, + ]); + let mut serialized = Vec::new(); + rmpv::encode::write_value(&mut serialized, &value) + .map_err(|e| PersistenceError::Serialize(e.to_string()))?; + let path = announce_cache_dir.join(hex::encode(packet_hash)); + atomic_write_bytes(&path, &serialized)?; + } + Ok(()) +} + +pub fn load_python_cached_announce( + announce_cache_dir: &Path, + packet_hash: &[u8; 32], +) -> Result, PersistenceError> { + let path = announce_cache_dir.join(hex::encode(packet_hash)); + if !path.exists() { + return Ok(None); + } + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let value = rmpv::decode::read_value(&mut std::io::Cursor::new(data)) + .map_err(|e| PersistenceError::Deserialize(e.to_string()))?; + let fields = match value { + Value::Array(fields) if fields.len() >= 2 => fields, + other => { + return Err(PersistenceError::Deserialize(format!( + "expected cached announce array, got {other:?}" + ))); + } + }; + let raw_packet = match &fields[0] { + Value::Binary(bytes) => bytes.clone(), + _ => { + return Err(PersistenceError::Deserialize( + "cached announce raw packet was not binary".to_string(), + )); + } + }; + let interface_reference = match &fields[1] { + Value::Nil => None, + Value::String(value) => value.as_str().map(str::to_string), + _ => None, + }; + Ok(Some(PythonCachedAnnounce { + raw_packet, + interface_reference, + })) +} + +fn value_bin_array(value: &Value) -> Option<[u8; N]> { + let Value::Binary(bytes) = value else { + return None; + }; + let mut out = [0u8; N]; + if bytes.len() != N { + return None; + } + out.copy_from_slice(bytes); + Some(out) +} + +fn value_f64(value: &Value) -> Option { + match value { + Value::F64(value) => Some(*value), + Value::F32(value) => Some(*value as f64), + Value::Integer(value) => value.as_i64().map(|v| v as f64), + _ => None, + } +} + +fn value_u8(value: &Value) -> Option { + match value { + Value::Integer(value) => value.as_u64()?.try_into().ok(), + _ => None, + } +} + +pub fn save_hashlist(hashlist: &PacketHashlist, path: &Path) -> Result<(), PersistenceError> { + let hashes = hashlist + .all_hashes() + .iter() + .map(|h| Value::Binary(h.to_vec())) + .collect(); + let mut serialized = Vec::new(); + rmpv::encode::write_value(&mut serialized, &Value::Array(hashes)) + .map_err(|e| PersistenceError::Serialize(e.to_string()))?; + atomic_write_bytes(path, &serialized) +} + +pub fn load_hashlist(path: &Path) -> Result, PersistenceError> { + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let raw_hashes = match rmp_serde::from_slice::>>(&data) { + Ok(hashes) => hashes, + Err(list_err) => { + let persisted: PersistedHashlist = rmp_serde::from_slice(&data) + .map_err(|e| PersistenceError::Deserialize(format!("{list_err}; {e}")))?; + persisted.hashes + } + }; + + let mut hashes = Vec::new(); + for h in raw_hashes { + if h.len() == 32 { + let mut arr = [0u8; 32]; + arr.copy_from_slice(&h); + hashes.push(arr); + } + } + Ok(hashes) +} + +/// Write to a sibling `.tmp` file and rename on top of the target so a crash +/// mid-write cannot leave a half-written snapshot on disk. +fn atomic_write(path: &Path, data: &T) -> Result<(), PersistenceError> { + let serialized = + rmp_serde::to_vec(data).map_err(|e| PersistenceError::Serialize(e.to_string()))?; + atomic_write_bytes(path, &serialized) +} + +fn atomic_write_bytes(path: &Path, serialized: &[u8]) -> Result<(), PersistenceError> { + let tmp_path = path.with_extension("tmp"); + std::fs::write(&tmp_path, serialized).map_err(PersistenceError::Io)?; + std::fs::rename(&tmp_path, path).map_err(PersistenceError::Io)?; + + Ok(()) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedBlackholeEntry { + pub identity_hash: Vec, + pub created: f64, + pub ttl: Option, + #[serde(default)] + pub reason: crate::blackhole::BlackholeReason, + #[serde(default)] + pub reason_label: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedBlackholeTable { + pub entries: Vec, + pub version: u32, +} + +impl PersistedBlackholeTable { + pub const CURRENT_VERSION: u32 = 2; + pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2]; +} + +pub fn save_blackhole_table( + table: &crate::blackhole::BlackholeTable, + path: &Path, +) -> Result<(), PersistenceError> { + let mut entries = Vec::new(); + for (hash, entry) in table.iter_entries() { + entries.push(PersistedBlackholeEntry { + identity_hash: hash.to_vec(), + created: entry.created, + ttl: entry.ttl, + reason: entry.reason, + reason_label: entry.reason_label.clone(), + }); + } + + let persisted = PersistedBlackholeTable { + entries, + version: PersistedBlackholeTable::CURRENT_VERSION, + }; + + atomic_write(path, &persisted) +} + +pub fn load_blackhole_table(path: &Path) -> Result, PersistenceError> { + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let persisted: PersistedBlackholeTable = + rmp_serde::from_slice(&data).map_err(|e| PersistenceError::Deserialize(e.to_string()))?; + + if !PersistedBlackholeTable::SUPPORTED_VERSIONS.contains(&persisted.version) { + return Err(PersistenceError::VersionMismatch { + expected: PersistedBlackholeTable::CURRENT_VERSION, + found: persisted.version, + }); + } + + Ok(persisted.entries) +} + +#[derive(Debug, Clone)] +pub struct PythonBlackholeEntry { + pub identity_hash: [u8; 16], + pub source: [u8; 16], + pub created: f64, + pub ttl: Option, + pub reason: crate::blackhole::BlackholeReason, + pub reason_label: Option, +} + +pub fn save_python_blackhole_files( + table: &crate::blackhole::BlackholeTable, + local_identity_hash: [u8; 16], + blackhole_dir: &Path, +) -> Result<(), PersistenceError> { + std::fs::create_dir_all(blackhole_dir).map_err(PersistenceError::Io)?; + + let mut local_entries = Vec::new(); + let mut remote_entries: HashMap<[u8; 16], Vec<(Value, Value)>> = HashMap::new(); + for (identity_hash, entry) in table.iter_entries() { + let source = entry + .source + .map(|source| source.into_bytes()) + .unwrap_or(local_identity_hash); + let until = entry.ttl.map(|ttl| entry.created + ttl); + let value = blackhole_entry_value(source, until, entry.reason_str()); + let key = Value::Binary(identity_hash.to_vec()); + if source == local_identity_hash { + local_entries.push((key, value)); + } else { + remote_entries.entry(source).or_default().push((key, value)); + } + } + + write_value_file(&blackhole_dir.join("local"), &Value::Map(local_entries))?; + for (source, entries) in remote_entries { + write_value_file( + &blackhole_dir.join(hex::encode(source)), + &Value::Map(entries), + )?; + } + Ok(()) +} + +pub fn load_python_blackhole_dir( + blackhole_dir: &Path, + local_identity_hash: [u8; 16], + enabled_sources: &[[u8; 16]], + now: f64, +) -> Result, PersistenceError> { + let mut remote_entries = Vec::new(); + let mut local_entries = Vec::new(); + let read_dir = match std::fs::read_dir(blackhole_dir) { + Ok(read_dir) => read_dir, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(PersistenceError::Io(e)), + }; + + for item in read_dir { + let Ok(item) = item else { + continue; + }; + let path = item.path(); + if !path.is_file() { + continue; + } + let Some(filename) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + let source = if filename == "local" { + local_identity_hash + } else { + let Ok(bytes) = hex::decode(filename) else { + continue; + }; + if bytes.len() != 16 { + continue; + } + let mut source = [0u8; 16]; + source.copy_from_slice(&bytes); + if !enabled_sources.contains(&source) { + continue; + } + source + }; + let is_local = source == local_identity_hash; + + let Ok(data) = std::fs::read(&path) else { + continue; + }; + let Ok(Value::Map(map)) = rmpv::decode::read_value(&mut std::io::Cursor::new(data)) else { + continue; + }; + + for (identity_value, entry_value) in map { + let Some(identity_hash) = value_bin_array::<16>(&identity_value) else { + continue; + }; + let Value::Map(entry_map) = entry_value else { + continue; + }; + let until = map_get(&entry_map, "until").and_then(value_f64); + if until.is_some_and(|until| now >= until) { + continue; + } + let reason = map_get(&entry_map, "reason") + .and_then(Value::as_str) + .map(crate::blackhole::BlackholeReason::parse) + .unwrap_or(crate::blackhole::BlackholeReason::Manual); + let reason_label = map_get(&entry_map, "reason") + .and_then(Value::as_str) + .map(ToOwned::to_owned); + let entry = PythonBlackholeEntry { + identity_hash, + source, + created: now, + ttl: until.map(|until| (until - now).max(0.0)), + reason, + reason_label, + }; + if is_local { + local_entries.push(entry); + } else { + remote_entries.push(entry); + } + } + } + + // Python protects local blackholes from remote-source overrides. The actor + // inserts entries in order, so load remote files first and local last. + let mut entries = remote_entries; + entries.extend(local_entries); + Ok(entries) +} + +fn blackhole_entry_value(source: [u8; 16], until: Option, reason: &str) -> Value { + Value::Map(vec![ + ( + Value::String("source".into()), + Value::Binary(source.to_vec()), + ), + ( + Value::String("until".into()), + until.map(Value::F64).unwrap_or(Value::Nil), + ), + (Value::String("reason".into()), Value::String(reason.into())), + ]) +} + +fn write_value_file(path: &Path, value: &Value) -> Result<(), PersistenceError> { + let mut serialized = Vec::new(); + rmpv::encode::write_value(&mut serialized, value) + .map_err(|e| PersistenceError::Serialize(e.to_string()))?; + atomic_write_bytes(path, &serialized) +} + +fn map_get<'a>(map: &'a [(Value, Value)], key: &str) -> Option<&'a Value> { + map.iter() + .find(|(candidate, _)| candidate.as_str() == Some(key)) + .map(|(_, value)| value) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedAnnounceEntry { + pub destination_hash: Vec, + pub hops: u8, + pub app_data: Option>, + pub timestamp: f64, + pub public_key: Option>, + pub ratchet: Option>, + /// Raw announce bytes so CacheRequest replays hit a byte-identical packet + /// instead of re-serialising (which would disturb signatures). + pub raw_packet: Vec, + /// Pinned via `RetainDestination`; the maintenance sweep skips the + /// entry regardless of age while this is `true`. + pub retained: bool, + /// `SHA-256(app_name)[:10]` of the announced aspect. Lets cache consumers + /// retro-filter without re-parsing `raw_packet`. + pub name_hash: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedAnnounceCache { + pub entries: Vec, + pub version: u32, +} + +impl PersistedAnnounceCache { + pub const CURRENT_VERSION: u32 = 5; +} + +pub fn save_announce_cache<'a, I>(announces: I, path: &Path) -> Result<(), PersistenceError> +where + I: IntoIterator, +{ + let entries: Vec = announces + .into_iter() + .map(|a| PersistedAnnounceEntry { + destination_hash: a.dest_hash.to_vec(), + hops: a.hops, + app_data: a.app_data.clone(), + timestamp: a.timestamp, + public_key: a.public_key.map(|k| k.to_vec()), + ratchet: a.ratchet.map(|r| r.to_vec()), + raw_packet: a.raw_packet.clone(), + retained: a.retained, + name_hash: a.name_hash.to_vec(), + }) + .collect(); + + let persisted = PersistedAnnounceCache { + entries, + version: PersistedAnnounceCache::CURRENT_VERSION, + }; + + atomic_write(path, &persisted) +} + +pub fn load_announce_cache(path: &Path) -> Result, PersistenceError> { + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let persisted: PersistedAnnounceCache = + rmp_serde::from_slice(&data).map_err(|e| PersistenceError::Deserialize(e.to_string()))?; + + if persisted.version != PersistedAnnounceCache::CURRENT_VERSION { + return Err(PersistenceError::VersionMismatch { + expected: PersistedAnnounceCache::CURRENT_VERSION, + found: persisted.version, + }); + } + + Ok(persisted.entries) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedTunnelEntry { + pub tunnel_id: Vec, + pub interface_id: u64, + pub expires: f64, + pub paths: Vec, + /// Same role as `PersistedPathEntry::interface_name` — used to remap a + /// stale `interface_id` once the matching interface registers. + #[serde(default)] + pub interface_name: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedTunnelPath { + pub destination_hash: Vec, + pub hops: u8, + pub expires: f64, + pub timestamp: f64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PersistedTunnelTable { + pub entries: Vec, + pub version: u32, +} + +impl PersistedTunnelTable { + pub const CURRENT_VERSION: u32 = 2; + pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2]; +} + +pub fn save_tunnel_table( + table: &crate::tunnel::TunnelTable, + interface_names: &HashMap, + path: &Path, +) -> Result<(), PersistenceError> { + let entries: Vec = table + .iter() + .filter_map(|(_, entry)| { + // Skip entries whose interface has already been deregistered. + let interface_name = interface_names.get(&entry.interface_id).cloned()?; + let paths: Vec = entry + .tunnel_paths + .iter() + .map(|(dest, tp)| PersistedTunnelPath { + destination_hash: dest.to_vec(), + hops: tp.hops, + expires: tp.expires, + timestamp: tp.timestamp, + }) + .collect(); + Some(PersistedTunnelEntry { + tunnel_id: entry.tunnel_id.to_vec(), + interface_id: entry.interface_id, + expires: entry.expires, + paths, + interface_name: Some(interface_name), + }) + }) + .collect(); + + let persisted = PersistedTunnelTable { + entries, + version: PersistedTunnelTable::CURRENT_VERSION, + }; + + atomic_write(path, &persisted) +} + +pub fn load_tunnel_table(path: &Path) -> Result, PersistenceError> { + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let persisted: PersistedTunnelTable = + rmp_serde::from_slice(&data).map_err(|e| PersistenceError::Deserialize(e.to_string()))?; + + if !PersistedTunnelTable::SUPPORTED_VERSIONS.contains(&persisted.version) { + return Err(PersistenceError::VersionMismatch { + expected: PersistedTunnelTable::CURRENT_VERSION, + found: persisted.version, + }); + } + + Ok(persisted.entries) +} + +#[derive(Debug, thiserror::Error)] +pub enum PersistenceError { + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), + #[error("serialization error: {0}")] + Serialize(String), + #[error("deserialization error: {0}")] + Deserialize(String), + #[error("version mismatch: expected {expected}, found {found}")] + VersionMismatch { expected: u32, found: u32 }, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constants::InterfaceMode; + use crate::path_table::PathEntry; + + #[test] + fn test_save_load_path_table() { + let mut table = PathTable::new(); + let hash = [0xAA; 16]; + let entry = PathEntry::new(Some([0xBB; 16]), 3, 1, InterfaceMode::Gateway); + table.insert(hash, entry); + + let dir = std::env::temp_dir().join("reticulum_rs_test_persist"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("path_table.msgpack"); + + let mut names = HashMap::new(); + names.insert(1u64, "test_iface".to_string()); + save_path_table(&table, &names, &path).unwrap(); + let loaded = load_path_table(&path).unwrap(); + + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].destination_hash, hash.to_vec()); + assert_eq!(loaded[0].hops, 3); + assert_eq!(loaded[0].interface_id, 1); + assert_eq!(loaded[0].interface_name.as_deref(), Some("test_iface")); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn save_skips_entries_with_no_interface_name() { + let mut table = PathTable::new(); + let hash = [0xAA; 16]; + let entry = PathEntry::new(Some([0xBB; 16]), 3, 99, InterfaceMode::Gateway); + table.insert(hash, entry); + + let dir = std::env::temp_dir().join("reticulum_rs_test_persist_skip"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("path_table.msgpack"); + + // No name registered for interface_id=99 → entry should be skipped. + let names: HashMap = HashMap::new(); + save_path_table(&table, &names, &path).unwrap(); + let loaded = load_path_table(&path).unwrap(); + assert!(loaded.is_empty()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn legacy_v2_path_table_loads_entries_with_name_none() { + // Simulate a pre-v3 snapshot by writing v2 shape (no interface_name) + // and verify it deserializes via serde(default). + #[derive(Serialize)] + struct V2Entry { + destination_hash: Vec, + timestamp: f64, + next_hop: Option>, + hops: u8, + expires: f64, + random_blobs: Vec>, + interface_id: u64, + } + #[derive(Serialize)] + struct V2Table { + entries: Vec, + version: u32, + } + let v2 = V2Table { + entries: vec![V2Entry { + destination_hash: vec![0xAA; 16], + timestamp: 1.0, + next_hop: None, + hops: 1, + expires: 9999999999.0, + random_blobs: vec![], + interface_id: 1, + }], + version: 2, + }; + let bytes = rmp_serde::to_vec(&v2).unwrap(); + + let dir = std::env::temp_dir().join("reticulum_rs_test_v2_path"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("path_table.msgpack"); + std::fs::write(&path, &bytes).unwrap(); + + let loaded = load_path_table(&path).unwrap(); + assert_eq!(loaded.len(), 1); + assert!(loaded[0].interface_name.is_none()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn save_load_python_destination_table_and_announce_cache() { + let destination_hash = [0xAA; 16]; + let next_hop = [0xBB; 16]; + let packet_hash = [0xCC; 32]; + let mut entry = PathEntry::new(Some(next_hop), 2, 7, InterfaceMode::Gateway); + entry.timestamp = 1234.5; + entry.expires = 9876.5; + entry.packet_hash = Some(packet_hash); + entry.add_random_blob([0x44; 10]); + + let mut table = PathTable::new(); + table.insert(destination_hash, entry); + let mut names = HashMap::new(); + names.insert(7, "Interface[Test]".to_string()); + + let dir = std::env::temp_dir().join("reticulum_rs_test_python_destination_table"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let destination_table_path = dir.join("destination_table"); + + save_python_destination_table(&table, &names, &destination_table_path).unwrap(); + let loaded = load_python_destination_table(&destination_table_path).unwrap(); + + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].destination_hash, destination_hash); + assert_eq!(loaded[0].timestamp, 1234.5); + assert_eq!(loaded[0].received_from, next_hop); + assert_eq!(loaded[0].hops, 2); + assert_eq!(loaded[0].expires, 9876.5); + assert_eq!(loaded[0].random_blobs, vec![[0x44; 10]]); + assert_eq!( + loaded[0].interface_hash, + interface_hash_from_name("Interface[Test]") + ); + assert_eq!(loaded[0].packet_hash, packet_hash); + + let announces = [crate::actor::RecentAnnounce { + dest_hash: destination_hash, + hops: 2, + app_data: None, + timestamp: 1234.5, + public_key: None, + ratchet: None, + raw_packet: vec![0xFE; 42], + retained: false, + name_hash: [0xAB; 10], + }]; + let cache_dir = dir.join("cache").join("announces"); + save_python_announce_cache_for_paths(&table, announces.iter(), &names, &cache_dir).unwrap(); + let cached = load_python_cached_announce(&cache_dir, &packet_hash) + .unwrap() + .unwrap(); + assert_eq!(cached.raw_packet, vec![0xFE; 42]); + assert_eq!( + cached.interface_reference.as_deref(), + Some("Interface[Test]") + ); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_save_load_hashlist() { + let mut hashlist = PacketHashlist::new(); + let aa = [0xAA; 32]; + let bb = [0xBB; 32]; + hashlist.insert(aa); + hashlist.insert(bb); + + let dir = std::env::temp_dir().join("reticulum_rs_test_hashlist"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("packet_hashlist"); + + save_hashlist(&hashlist, &path).unwrap(); + let raw = std::fs::read(&path).unwrap(); + let mut python_shape: Vec> = rmp_serde::from_slice(&raw).unwrap(); + python_shape.sort(); + assert_eq!(python_shape, vec![aa.to_vec(), bb.to_vec()]); + + let loaded = load_hashlist(&path).unwrap(); + assert_eq!(loaded.len(), 2); + assert!(loaded.contains(&aa)); + assert!(loaded.contains(&bb)); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn load_hashlist_accepts_legacy_rust_sidecar_shape() { + let persisted = PersistedHashlist { + hashes: vec![vec![0xAA; 32], vec![0x42; 31], vec![0xBB; 32]], + version: 1, + }; + let bytes = rmp_serde::to_vec(&persisted).unwrap(); + + let dir = std::env::temp_dir().join("reticulum_rs_test_hashlist_legacy"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("hashlist.msgpack"); + std::fs::write(&path, bytes).unwrap(); + + let loaded = load_hashlist(&path).unwrap(); + assert_eq!(loaded.len(), 2); + assert!(loaded.contains(&[0xAA; 32])); + assert!(loaded.contains(&[0xBB; 32])); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_atomic_write() { + let dir = std::env::temp_dir().join("reticulum_rs_test_atomic"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("test.msgpack"); + + let data = PersistedHashlist { + hashes: Vec::new(), + version: 1, + }; + atomic_write(&path, &data).unwrap(); + + assert!(path.exists()); + assert!(!path.with_extension("tmp").exists()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_version_mismatch() { + let dir = std::env::temp_dir().join("reticulum_rs_test_version"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("path_table.msgpack"); + + let bad = PersistedPathTable { + entries: Vec::new(), + version: 999, + }; + atomic_write(&path, &bad).unwrap(); + + let result = load_path_table(&path); + assert!(result.is_err()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_persisted_path_entry_roundtrip() { + let entry = PersistedPathEntry { + destination_hash: vec![0xAA; 16], + timestamp: 1234567890.0, + next_hop: Some(vec![0xBB; 16]), + hops: 5, + expires: 1234567890.0 + 604800.0, + random_blobs: vec![vec![0x42; 10]], + interface_id: 42, + interface_name: Some("test_iface".to_string()), + interface_hash: Some(interface_hash_from_name("test_iface").to_vec()), + packet_hash: Some(vec![0x11; 32]), + }; + + let serialized = rmp_serde::to_vec(&entry).unwrap(); + let deserialized: PersistedPathEntry = rmp_serde::from_slice(&serialized).unwrap(); + + assert_eq!(deserialized.destination_hash, entry.destination_hash); + assert_eq!(deserialized.hops, entry.hops); + assert_eq!(deserialized.interface_id, entry.interface_id); + } + + #[test] + fn test_save_load_blackhole_table() { + let mut table = crate::blackhole::BlackholeTable::new(); + table.add([0xAA; 16], None); + table.add_with_reason( + [0xBB; 16], + Some(3600.0), + crate::blackhole::BlackholeReason::RateLimit, + ); + + let dir = std::env::temp_dir().join("reticulum_rs_test_blackhole"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("blackhole_table.msgpack"); + + save_blackhole_table(&table, &path).unwrap(); + let loaded = load_blackhole_table(&path).unwrap(); + + assert_eq!(loaded.len(), 2); + + let aa = loaded + .iter() + .find(|e| e.identity_hash == vec![0xAA; 16]) + .unwrap(); + let bb = loaded + .iter() + .find(|e| e.identity_hash == vec![0xBB; 16]) + .unwrap(); + assert_eq!(aa.reason, crate::blackhole::BlackholeReason::Manual); + assert_eq!(aa.ttl, None); + assert_eq!(bb.reason, crate::blackhole::BlackholeReason::RateLimit); + assert_eq!(bb.ttl, Some(3600.0)); + assert!(bb.created > 0.0); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn save_load_python_blackhole_files_preserves_source_rules() { + let local_source = [0x11; 16]; + let remote_source = [0x22; 16]; + let shared_identity = [0xAA; 16]; + let remote_only_identity = [0xBB; 16]; + + let mut table = crate::blackhole::BlackholeTable::new(); + table.insert_entry( + shared_identity, + crate::blackhole::BlackholeEntry { + created: 1000.0, + ttl: None, + reason: crate::blackhole::BlackholeReason::Manual, + reason_label: None, + source: None, + }, + ); + table.insert_entry( + remote_only_identity, + crate::blackhole::BlackholeEntry { + created: 1000.0, + ttl: Some(60.0), + reason: crate::blackhole::BlackholeReason::RateLimit, + reason_label: None, + source: Some(remote_source.into()), + }, + ); + + let dir = std::env::temp_dir().join("reticulum_rs_test_python_blackhole"); + let _ = std::fs::remove_dir_all(&dir); + save_python_blackhole_files(&table, local_source, &dir).unwrap(); + + assert!(dir.join("local").exists()); + assert!(dir.join(hex::encode(remote_source)).exists()); + + let loaded = + load_python_blackhole_dir(&dir, local_source, &[remote_source], 1010.0).unwrap(); + assert_eq!(loaded.len(), 2); + assert!(loaded.iter().any(|entry| { + entry.identity_hash == shared_identity + && entry.source == local_source + && entry.reason == crate::blackhole::BlackholeReason::Manual + })); + let remote = loaded + .iter() + .find(|entry| entry.identity_hash == remote_only_identity) + .unwrap(); + assert_eq!(remote.source, remote_source); + assert_eq!(remote.reason, crate::blackhole::BlackholeReason::RateLimit); + assert_eq!(remote.ttl, Some(50.0)); + + let conflicting_remote = Value::Map(vec![( + Value::Binary(shared_identity.to_vec()), + blackhole_entry_value( + remote_source, + None, + crate::blackhole::BlackholeReason::ProtocolViolation.as_str(), + ), + )]); + write_value_file(&dir.join(hex::encode(remote_source)), &conflicting_remote).unwrap(); + let loaded = + load_python_blackhole_dir(&dir, local_source, &[remote_source], 1010.0).unwrap(); + let final_shared = loaded + .iter() + .rev() + .find(|entry| entry.identity_hash == shared_identity) + .unwrap(); + assert_eq!(final_shared.source, local_source); + assert_eq!( + final_shared.reason, + crate::blackhole::BlackholeReason::Manual + ); + + let disabled = load_python_blackhole_dir(&dir, local_source, &[], 1010.0).unwrap(); + assert!(disabled.iter().all(|entry| entry.source == local_source)); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_load_v1_blackhole_table_falls_back_to_manual() { + // v1 snapshots have no `reason` field; serde(default) fills in + // Manual, which is correct — v1 predates auto-population. + #[derive(Serialize)] + struct V1Entry { + identity_hash: Vec, + created: f64, + ttl: Option, + } + #[derive(Serialize)] + struct V1Table { + entries: Vec, + version: u32, + } + let v1 = V1Table { + entries: vec![V1Entry { + identity_hash: vec![0x77; 16], + created: 1234.0, + ttl: None, + }], + version: 1, + }; + let bytes = rmp_serde::to_vec(&v1).unwrap(); + + let dir = std::env::temp_dir().join("reticulum_rs_test_blackhole_v1"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("blackhole_table.msgpack"); + std::fs::write(&path, &bytes).unwrap(); + + let loaded = load_blackhole_table(&path).unwrap(); + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].reason, crate::blackhole::BlackholeReason::Manual); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_save_load_announce_cache() { + let announces = vec![crate::actor::RecentAnnounce { + dest_hash: [0xCC; 16], + hops: 3, + app_data: Some(vec![10, 20, 30]), + timestamp: 1000.0, + public_key: None, + ratchet: Some([0xDD; 32]), + raw_packet: vec![0xEE; 64], + retained: false, + name_hash: [0xAB; 10], + }]; + + let dir = std::env::temp_dir().join("reticulum_rs_test_announce_persist"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("announce_cache.msgpack"); + + save_announce_cache(&announces, &path).unwrap(); + let loaded = load_announce_cache(&path).unwrap(); + + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].destination_hash, [0xCC; 16].to_vec()); + assert_eq!(loaded[0].hops, 3); + assert_eq!(loaded[0].ratchet, Some(vec![0xDD; 32])); + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/rns-transport/src/rate_limit.rs b/crates/rns-transport/src/rate_limit.rs new file mode 100644 index 0000000..ec7d0ae --- /dev/null +++ b/crates/rns-transport/src/rate_limit.rs @@ -0,0 +1,273 @@ +use std::collections::HashMap; +use std::time::{SystemTime, UNIX_EPOCH}; +use tracing::debug; + +use crate::constants::MAX_RATE_TIMESTAMPS; +use rns_wire::types::DestHash; + +/// Announces-per-second above which a destination is counted as violating. +pub const RATE_VIOLATION_THRESHOLD: f64 = 1.0; +/// Violations tolerated before a penalty kicks in. +pub const RATE_VIOLATIONS_BEFORE_PENALTY: u32 = 3; +/// Base penalty in seconds; doubles with each additional violation. +pub const RATE_PENALTY_BASE: f64 = 60.0; +/// Penalty cap (1 hour) so a persistent offender never stays blocked forever. +pub const RATE_PENALTY_MAX: f64 = 3600.0; + +#[derive(Debug, Clone)] +pub struct RateEntry { + pub timestamps: Vec, + /// Announces per second across the window. + pub rate: f64, + /// Most recent announce (Unix seconds). + pub last: f64, + pub violations: u32, + /// `0.0` means no active penalty; otherwise the Unix-seconds deadline. + pub blocked_until: f64, +} + +pub struct RateTable { + entries: HashMap, +} + +impl RateTable { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + } + } + + /// Record an announce and return the current rate. A destination under + /// active penalty gets `f64::MAX` so callers can treat "over the limit" + /// and "blocked" as a single numeric comparison. + pub fn record(&mut self, dest_hash: impl Into) -> f64 { + let dest_hash = dest_hash.into(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let entry = self.entries.entry(dest_hash).or_insert_with(|| RateEntry { + timestamps: Vec::new(), + rate: 0.0, + last: 0.0, + violations: 0, + blocked_until: 0.0, + }); + + if entry.blocked_until > now { + return f64::MAX; + } + + entry.timestamps.push(now); + entry.last = now; + + if entry.timestamps.len() > MAX_RATE_TIMESTAMPS { + let drain_count = entry.timestamps.len() - MAX_RATE_TIMESTAMPS; + entry.timestamps.drain(..drain_count); + } + + if entry.timestamps.len() >= 2 { + let span = entry.timestamps.last().unwrap() - entry.timestamps.first().unwrap(); + if span > 0.0 { + entry.rate = (entry.timestamps.len() - 1) as f64 / span; + } + } + + if entry.rate > RATE_VIOLATION_THRESHOLD { + entry.violations += 1; + debug!( + dest = hex::encode(dest_hash), + rate = format!("{:.2}", entry.rate), + violations = entry.violations, + "rate limit violation detected" + ); + if entry.violations >= RATE_VIOLATIONS_BEFORE_PENALTY { + // Exponential back-off, clamped so a persistent offender + // doesn't snowball into an effectively-permanent block. + let penalty = (RATE_PENALTY_BASE + * 2.0_f64.powi((entry.violations - RATE_VIOLATIONS_BEFORE_PENALTY) as i32)) + .min(RATE_PENALTY_MAX); + entry.blocked_until = now + penalty; + debug!( + dest = hex::encode(dest_hash), + penalty_secs = format!("{:.1}", penalty), + "rate limit penalty applied" + ); + } + } + + entry.rate + } + + pub fn is_blocked(&self, dest_hash: &[u8; 16]) -> bool { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + self.entries + .get(dest_hash) + .is_some_and(|e| e.blocked_until > now) + } + + pub fn get_rate(&self, dest_hash: &[u8; 16]) -> f64 { + self.entries.get(dest_hash).map_or(0.0, |e| e.rate) + } + + pub fn last_announce(&self, dest_hash: &[u8; 16]) -> Option { + self.entries.get(dest_hash).map(|e| e.last) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn cull(&mut self, cutoff: f64) { + self.entries.retain(|_, e| e.last > cutoff); + } + + pub fn iter(&self) -> impl Iterator { + self.entries.iter() + } + + /// Per-interface announce rate limit. + /// + /// Uses the interface-level triplet `(rate_target, rate_grace, rate_penalty)`: + /// any interval shorter than `rate_target` is a violation, violations + /// decay when the interval is long enough, and exceeding the grace count + /// parks the destination for `rate_target + rate_penalty` seconds. + /// + /// Returns `true` when rebroadcast should be suppressed. Path-table + /// storage is unaffected — only the outbound announce is held back. + pub fn check_interface_rate( + &mut self, + dest_hash: impl Into, + rate_target: f64, + rate_grace: u32, + rate_penalty: f64, + ) -> bool { + let dest_hash = dest_hash.into(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let entry = match self.entries.entry(dest_hash) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert(RateEntry { + timestamps: vec![now], + rate: 0.0, + last: now, + violations: 0, + blocked_until: 0.0, + }); + return false; + } + }; + + if now <= entry.blocked_until { + return true; + } + + entry.timestamps.push(now); + while entry.timestamps.len() > MAX_RATE_TIMESTAMPS { + entry.timestamps.remove(0); + } + + let current_rate = now - entry.last; + + if current_rate < rate_target { + entry.violations += 1; + } else { + entry.violations = entry.violations.saturating_sub(1); + } + + if entry.violations > rate_grace { + entry.blocked_until = entry.last + rate_target + rate_penalty; + // Leave `last` untouched so the penalty window is anchored to the + // announce that originally tipped us over the grace threshold. + return true; + } + + entry.last = now; + false + } +} + +impl Default for RateTable { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_rate_recording() { + let mut rt = RateTable::new(); + let hash = [0xAA; 16]; + let rate = rt.record(hash); + assert_eq!(rate, 0.0); + } + + #[test] + fn test_rate_limit_bounds() { + let mut rt = RateTable::new(); + let hash = [0xAA; 16]; + for _ in 0..MAX_RATE_TIMESTAMPS + 5 { + rt.record(hash); + } + let entry = rt.entries.get(&hash).unwrap(); + assert!(entry.timestamps.len() <= MAX_RATE_TIMESTAMPS); + } + + #[test] + fn test_violation_tracking() { + let mut rt = RateTable::new(); + let hash = [0xBB; 16]; + + for _ in 0..20 { + rt.record(hash); + } + + let entry = rt.entries.get(&hash).unwrap(); + assert!(entry.violations > 0 || entry.rate > 0.0); + } + + #[test] + fn test_blocked_check() { + let mut rt = RateTable::new(); + let hash = [0xCC; 16]; + + assert!(!rt.is_blocked(&hash)); + + rt.record(hash); + } + + #[test] + fn test_interface_rate_first_announce_not_blocked() { + let mut rt = RateTable::new(); + let hash = [0xDD; 16]; + let blocked = rt.check_interface_rate(hash, 300.0, 3, 600.0); + assert!(!blocked); + } + + #[test] + fn test_interface_rate_rapid_fire_triggers_block() { + let mut rt = RateTable::new(); + let hash = [0xEE; 16]; + // Three back-to-back calls: first records, second violates, third + // violates again — with grace=1 the running count hits 2 and trips. + rt.check_interface_rate(hash, 300.0, 1, 600.0); + rt.check_interface_rate(hash, 300.0, 1, 600.0); + let blocked = rt.check_interface_rate(hash, 300.0, 1, 600.0); + assert!(blocked); + } +} diff --git a/crates/rns-transport/src/reverse_table.rs b/crates/rns-transport/src/reverse_table.rs new file mode 100644 index 0000000..fa41704 --- /dev/null +++ b/crates/rns-transport/src/reverse_table.rs @@ -0,0 +1,197 @@ +use std::collections::HashMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::constants::REVERSE_TIMEOUT; +use crate::messages::InterfaceId; +use rns_wire::types::TruncatedHash; + +/// Record of an in-flight packet so the matching proof can be routed back +/// along the same path. Entries expire after `REVERSE_TIMEOUT` — long enough +/// to tolerate slow links, short enough that stale routes don't accumulate. +#[derive(Debug, Clone)] +pub struct ReverseEntry { + pub timestamp: f64, + pub receiving_interface: InterfaceId, + pub remaining_hops: u8, + /// Interface we forwarded the packet on, when known. Proofs that come + /// back on a different interface are rejected — the mismatch means + /// either a routing change or a spoof attempt. + pub outbound_interface: Option, +} + +pub struct ReverseTable { + entries: HashMap, +} + +impl ReverseTable { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + } + } + + pub fn insert( + &mut self, + packet_hash: impl Into, + interface_id: InterfaceId, + remaining_hops: u8, + ) { + self.insert_with_outbound(packet_hash, interface_id, remaining_hops, None); + } + + /// Insert with explicit outbound-interface tracking. See `ReverseEntry` + /// for why the outbound interface is pinned. + pub fn insert_with_outbound( + &mut self, + packet_hash: impl Into, + interface_id: InterfaceId, + remaining_hops: u8, + outbound_interface: Option, + ) { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + self.entries.insert( + packet_hash.into(), + ReverseEntry { + timestamp: now, + receiving_interface: interface_id, + remaining_hops, + outbound_interface, + }, + ); + } + + pub fn get(&self, packet_hash: &[u8; 16]) -> Option<&ReverseEntry> { + self.entries.get(packet_hash) + } + + pub fn remove(&mut self, packet_hash: &[u8; 16]) -> Option { + self.entries.remove(packet_hash) + } + + pub fn cull_expired(&mut self) -> usize { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + let cutoff = now - REVERSE_TIMEOUT as f64; + + let before = self.entries.len(); + self.entries.retain(|_, entry| entry.timestamp > cutoff); + before - self.entries.len() + } + + /// Batched cull — bounds per-tick work on large tables. + pub fn cull_expired_batch(&mut self, limit: usize) -> usize { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + let cutoff = now - REVERSE_TIMEOUT as f64; + + let to_remove: Vec = self + .entries + .iter() + .filter(|(_, entry)| entry.timestamp <= cutoff) + .take(limit) + .map(|(hash, _)| *hash) + .collect(); + let count = to_remove.len(); + for hash in &to_remove { + self.entries.remove(hash.as_bytes()); + } + count + } + + /// Drop entries whose receiving or outbound interface has gone away — + /// those proofs could never be routed back regardless. + pub fn cull_dead_interfaces( + &mut self, + active_interfaces: &std::collections::HashSet, + ) -> usize { + let before = self.entries.len(); + self.entries.retain(|_, entry| { + active_interfaces.contains(&entry.receiving_interface) + && entry + .outbound_interface + .is_none_or(|id| active_interfaces.contains(&id)) + }); + before - self.entries.len() + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +impl Default for ReverseTable { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_insert_and_get() { + let mut rt = ReverseTable::new(); + let hash = [0xAA; 16]; + rt.insert(hash, 42, 5); + let entry = rt.get(&hash).unwrap(); + assert_eq!(entry.receiving_interface, 42); + assert_eq!(entry.remaining_hops, 5); + assert_eq!(entry.outbound_interface, None); + } + + #[test] + fn test_insert_with_outbound() { + let mut rt = ReverseTable::new(); + let hash = [0xBB; 16]; + rt.insert_with_outbound(hash, 1, 3, Some(2)); + let entry = rt.get(&hash).unwrap(); + assert_eq!(entry.receiving_interface, 1); + assert_eq!(entry.remaining_hops, 3); + assert_eq!(entry.outbound_interface, Some(2)); + } + + #[test] + fn test_remove() { + let mut rt = ReverseTable::new(); + let hash = [0xAA; 16]; + rt.insert(hash, 1, 0); + assert_eq!(rt.len(), 1); + rt.remove(&hash); + assert_eq!(rt.len(), 0); + } + + #[test] + fn test_cull_dead_interfaces() { + let mut rt = ReverseTable::new(); + let mut active = std::collections::HashSet::new(); + active.insert(1u64); + active.insert(2u64); + + rt.insert([0x01; 16], 1, 3); + rt.insert_with_outbound([0x02; 16], 1, 3, Some(2)); + rt.insert([0x03; 16], 99, 3); + rt.insert_with_outbound([0x04; 16], 1, 3, Some(99)); + + assert_eq!(rt.len(), 4); + let culled = rt.cull_dead_interfaces(&active); + assert_eq!(culled, 2); + assert_eq!(rt.len(), 2); + assert!(rt.get(&[0x01; 16]).is_some()); + assert!(rt.get(&[0x02; 16]).is_some()); + assert!(rt.get(&[0x03; 16]).is_none()); + assert!(rt.get(&[0x04; 16]).is_none()); + } +} diff --git a/crates/rns-transport/src/traffic.rs b/crates/rns-transport/src/traffic.rs new file mode 100644 index 0000000..e6fe7d1 --- /dev/null +++ b/crates/rns-transport/src/traffic.rs @@ -0,0 +1,63 @@ +use std::collections::HashMap; + +use crate::messages::InterfaceId; + +#[derive(Debug, Clone, Default)] +pub struct InterfaceTraffic { + pub rx_bytes: u64, + pub tx_bytes: u64, + /// Previous sample, retained so `update_speeds` can compute a delta + /// without keeping a ring buffer of samples. + pub rx_bytes_prev: u64, + pub tx_bytes_prev: u64, + /// Bytes per second, over the last `update_speeds` interval. + pub rx_speed: f64, + pub tx_speed: f64, +} + +pub struct TrafficCounter { + interfaces: HashMap, +} + +impl TrafficCounter { + pub fn new() -> Self { + Self { + interfaces: HashMap::new(), + } + } + + pub fn record_rx(&mut self, interface_id: InterfaceId, bytes: u64) { + let entry = self.interfaces.entry(interface_id).or_default(); + entry.rx_bytes += bytes; + } + + pub fn record_tx(&mut self, interface_id: InterfaceId, bytes: u64) { + let entry = self.interfaces.entry(interface_id).or_default(); + entry.tx_bytes += bytes; + } + + /// Compute per-second speeds from the delta since the last call. Intended + /// to run on a 1 Hz tick so the delta equals bytes-per-second directly. + pub fn update_speeds(&mut self) { + for entry in self.interfaces.values_mut() { + entry.rx_speed = (entry.rx_bytes - entry.rx_bytes_prev) as f64; + entry.tx_speed = (entry.tx_bytes - entry.tx_bytes_prev) as f64; + entry.rx_bytes_prev = entry.rx_bytes; + entry.tx_bytes_prev = entry.tx_bytes; + } + } + + pub fn get(&self, interface_id: &InterfaceId) -> Option<&InterfaceTraffic> { + self.interfaces.get(interface_id) + } + + pub fn all(&self) -> &HashMap { + &self.interfaces + } +} + +impl Default for TrafficCounter { + fn default() -> Self { + Self::new() + } +} diff --git a/crates/rns-transport/src/tunnel.rs b/crates/rns-transport/src/tunnel.rs new file mode 100644 index 0000000..1f42d1f --- /dev/null +++ b/crates/rns-transport/src/tunnel.rs @@ -0,0 +1,355 @@ +use std::collections::HashMap; + +use crate::messages::InterfaceId; + +/// One virtual-overlay tunnel plus the per-destination paths riding it. +/// Tunnels let transports stitch together routes that cross a network +/// boundary the underlying interface cannot reach directly. +#[derive(Debug, Clone)] +pub struct TunnelEntry { + pub tunnel_id: [u8; 32], + pub interface_id: InterfaceId, + pub tunnel_paths: HashMap<[u8; 16], TunnelPath>, + pub expires: f64, +} + +#[derive(Debug, Clone)] +pub struct TunnelPath { + pub timestamp: f64, + pub hops: u8, + pub expires: f64, + pub random_blobs: Vec<[u8; 10]>, +} + +pub struct TunnelTable { + entries: HashMap<[u8; 32], TunnelEntry>, +} + +impl TunnelTable { + pub fn new() -> Self { + Self { + entries: HashMap::new(), + } + } + + pub fn insert(&mut self, entry: TunnelEntry) { + self.entries.insert(entry.tunnel_id, entry); + } + + pub fn get(&self, tunnel_id: &[u8; 32]) -> Option<&TunnelEntry> { + self.entries.get(tunnel_id) + } + + pub fn get_mut(&mut self, tunnel_id: &[u8; 32]) -> Option<&mut TunnelEntry> { + self.entries.get_mut(tunnel_id) + } + + pub fn remove(&mut self, tunnel_id: &[u8; 32]) -> Option { + self.entries.remove(tunnel_id) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.entries.iter() + } + + pub fn iter_mut(&mut self) -> impl Iterator { + self.entries.iter_mut() + } + + pub fn cull_expired(&mut self) -> usize { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let before = self.entries.len(); + self.entries.retain(|_, entry| entry.expires > now); + before - self.entries.len() + } + + /// Batched cull — bounds per-tick work on large tables. + pub fn cull_expired_batch(&mut self, limit: usize) -> usize { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + + let to_remove: Vec<[u8; 32]> = self + .entries + .iter() + .filter(|(_, entry)| entry.expires <= now) + .take(limit) + .map(|(hash, _)| *hash) + .collect(); + let count = to_remove.len(); + for hash in &to_remove { + self.entries.remove(hash); + } + count + } +} + +impl Default for TunnelTable { + fn default() -> Self { + Self::new() + } +} + +/// Payload of a tunnel-synthesis announce. Total wire size = 176 bytes. +#[derive(Debug, Clone)] +pub struct TunnelSynthesisData { + /// Transport identity key: `X25519(32) || Ed25519(32)`. + pub public_key: [u8; 64], + /// SHA-256 of the interface identifier string. + pub interface_hash: [u8; 32], + /// Randomness that makes each announce unique for replay protection. + pub random_hash: [u8; 16], + /// Ed25519 signature over `public_key || interface_hash || random_hash`. + pub signature: [u8; 64], +} + +impl TunnelSynthesisData { + /// `public_key(64) || interface_hash(32) || random_hash(16) || signature(64) = 176 bytes`. + pub fn pack(&self) -> Vec { + let mut data = Vec::with_capacity(176); + data.extend_from_slice(&self.public_key); + data.extend_from_slice(&self.interface_hash); + data.extend_from_slice(&self.random_hash); + data.extend_from_slice(&self.signature); + data + } + + pub fn unpack(data: &[u8]) -> Option { + if data.len() < 176 { + return None; + } + let mut public_key = [0u8; 64]; + public_key.copy_from_slice(&data[0..64]); + let mut interface_hash = [0u8; 32]; + interface_hash.copy_from_slice(&data[64..96]); + let mut random_hash = [0u8; 16]; + random_hash.copy_from_slice(&data[96..112]); + let mut signature = [0u8; 64]; + signature.copy_from_slice(&data[112..176]); + + Some(Self { + public_key, + interface_hash, + random_hash, + signature, + }) + } + + /// Tunnel identifier: `SHA-256(public_key || interface_hash)`. + pub fn tunnel_id(&self) -> [u8; 32] { + use rns_crypto::sha::sha256; + let mut tunnel_id_data = Vec::with_capacity(96); + tunnel_id_data.extend_from_slice(&self.public_key); + tunnel_id_data.extend_from_slice(&self.interface_hash); + sha256(&tunnel_id_data) + } +} + +/// Install or refresh a tunnel from a validated tunnel-synthesis announce. +/// A reappearing tunnel keeps its existing path set — only the interface +/// binding and expiry move forward, so in-flight routes aren't lost when the +/// underlying link flaps. +pub fn handle_tunnel( + tunnel_table: &mut TunnelTable, + tunnel_id: [u8; 32], + interface_id: crate::messages::InterfaceId, + destination_timeout: f64, +) { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + let expires = now + destination_timeout; + + if let Some(existing) = tunnel_table.get_mut(&tunnel_id) { + existing.interface_id = interface_id; + existing.expires = expires; + } else { + let entry = TunnelEntry { + tunnel_id, + interface_id, + tunnel_paths: std::collections::HashMap::new(), + expires, + }; + tunnel_table.insert(entry); + } +} + +/// Build a tunnel-synthesis packet addressed to the well-known tunnel +/// synthesize PLAIN destination. The returned bytes are ready to send on the +/// interface that should host the tunnel; the receiver validates the +/// signature and installs the tunnel via `handle_tunnel`. +pub fn build_tunnel_synthesis_packet( + identity: &rns_identity::identity::Identity, + interface_hash: [u8; 32], +) -> Option> { + let public_key = identity.get_public_key(); + + let random_vec = rns_crypto::random::random_bytes(16); + let mut random_hash = [0u8; 16]; + random_hash.copy_from_slice(&random_vec); + + let mut signed_data = Vec::with_capacity(112); + signed_data.extend_from_slice(&public_key); + signed_data.extend_from_slice(&interface_hash); + signed_data.extend_from_slice(&random_hash); + + let signature = identity.sign(&signed_data)?; + + let synth_data = TunnelSynthesisData { + public_key, + interface_hash, + random_hash, + signature, + }; + let payload = synth_data.pack(); + + let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.tunnel.synthesize", + None, + ); + + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Plain, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + Some(raw) +} + +/// Interface identifier used in tunnel synthesis: `SHA-256(name)`. +pub fn interface_hash(name: &str) -> [u8; 32] { + rns_crypto::sha::sha256(name.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tunnel_table_basic() { + let mut table = TunnelTable::new(); + let tunnel_id = [0xAA; 32]; + let entry = TunnelEntry { + tunnel_id, + interface_id: 1, + tunnel_paths: std::collections::HashMap::new(), + expires: 99999999.0, + }; + table.insert(entry); + assert!(table.get(&tunnel_id).is_some()); + assert_eq!(table.len(), 1); + } + + #[test] + fn test_tunnel_synthesis_roundtrip() { + let data = TunnelSynthesisData { + public_key: [0x42; 64], + interface_hash: [0xAB; 32], + random_hash: [0xCD; 16], + signature: [0xEF; 64], + }; + let packed = data.pack(); + assert_eq!(packed.len(), 176); + + let unpacked = TunnelSynthesisData::unpack(&packed).unwrap(); + assert_eq!(unpacked.public_key, data.public_key); + assert_eq!(unpacked.interface_hash, data.interface_hash); + assert_eq!(unpacked.random_hash, data.random_hash); + assert_eq!(unpacked.signature, data.signature); + } + + #[test] + fn test_tunnel_synthesis_id() { + let data = TunnelSynthesisData { + public_key: [0x42; 64], + interface_hash: [0xAB; 32], + random_hash: [0xCD; 16], + signature: [0xEF; 64], + }; + let id = data.tunnel_id(); + assert_eq!(id.len(), 32); + let id2 = data.tunnel_id(); + assert_eq!(id, id2); + } + + #[test] + fn test_handle_tunnel_new() { + let mut table = TunnelTable::new(); + let tunnel_id = [0xFF; 32]; + handle_tunnel(&mut table, tunnel_id, 1, 604800.0); + assert!(table.get(&tunnel_id).is_some()); + assert_eq!(table.get(&tunnel_id).unwrap().interface_id, 1); + } + + #[test] + fn test_handle_tunnel_reappear() { + let mut table = TunnelTable::new(); + let tunnel_id = [0xFF; 32]; + handle_tunnel(&mut table, tunnel_id, 1, 604800.0); + + handle_tunnel(&mut table, tunnel_id, 2, 604800.0); + assert_eq!(table.get(&tunnel_id).unwrap().interface_id, 2); + assert_eq!(table.len(), 1); + } + + #[test] + fn test_tunnel_cull_expired() { + let mut table = TunnelTable::new(); + let entry = TunnelEntry { + tunnel_id: [0xAA; 32], + interface_id: 1, + tunnel_paths: std::collections::HashMap::new(), + expires: 0.0, + }; + table.insert(entry); + assert_eq!(table.len(), 1); + table.cull_expired(); + assert_eq!(table.len(), 0); + } + + #[test] + fn test_tunnel_iter() { + let mut table = TunnelTable::new(); + let entry1 = TunnelEntry { + tunnel_id: [0xAA; 32], + interface_id: 1, + tunnel_paths: std::collections::HashMap::new(), + expires: 99999999.0, + }; + let entry2 = TunnelEntry { + tunnel_id: [0xBB; 32], + interface_id: 2, + tunnel_paths: std::collections::HashMap::new(), + expires: 99999999.0, + }; + table.insert(entry1); + table.insert(entry2); + assert_eq!(table.iter().count(), 2); + } +} diff --git a/crates/rns-wire/Cargo.toml b/crates/rns-wire/Cargo.toml new file mode 100644 index 0000000..c269458 --- /dev/null +++ b/crates/rns-wire/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "rns-wire" +description = "Wire format, packet encoding, and hash computation for Reticulum" +version.workspace = true +edition.workspace = true +license.workspace = true + +[features] +default = ["std"] +std = ["rns-crypto/std"] + +[dependencies] +rns-crypto = { workspace = true } +thiserror = { workspace = true } +sha2 = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/rns-wire/src/constants.rs b/crates/rns-wire/src/constants.rs new file mode 100644 index 0000000..20b41e4 --- /dev/null +++ b/crates/rns-wire/src/constants.rs @@ -0,0 +1,81 @@ +//! Shared protocol constants (MTU, hash sizes, header bounds). + +/// Maximum Transmission Unit — hard protocol limit. +pub const MTU: usize = 500; + +/// Truncated hash length in bits (128 bits = 16 bytes). +pub const TRUNCATED_HASHLENGTH: usize = 128; + +/// Full hash length in bits (256 bits = 32 bytes). +pub const HASHLENGTH: usize = 256; + +/// Key size in bits (512 bits = 64 bytes: X25519_pub(32) + Ed25519_pub(32)). +pub const KEYSIZE: usize = 512; + +/// Signature length in bits (512 bits = 64 bytes). +pub const SIGLENGTH: usize = 512; + +/// Token encryption overhead: IV(16) + HMAC(32) = 48 bytes. +pub const TOKEN_OVERHEAD: usize = 48; + +/// AES-128 block size. +pub const AES128_BLOCKSIZE: usize = 16; + +/// Minimum header size (HEADER_1): flags(1) + hops(1) + dest_hash(16) + context(1) = 19. +pub const HEADER_MINSIZE: usize = 2 + TRUNCATED_HASHLENGTH / 8 + 1; + +/// Maximum header size (HEADER_2): flags(1) + hops(1) + transport_id(16) + dest_hash(16) + context(1) = 35. +pub const HEADER_MAXSIZE: usize = 2 + (TRUNCATED_HASHLENGTH / 8) * 2 + 1; + +/// Maximum Data Unit: MTU - HEADER_MAXSIZE - IFAC_MIN = 500 - 35 - 1 = 464. +pub const MDU: usize = MTU - HEADER_MAXSIZE - 1; + +/// Encrypted link MDU, matching Python `RNS.Link.MDU`: +/// floor((MTU - IFAC_MIN - HEADER_MIN - TOKEN_OVERHEAD) / AES128_BLOCKSIZE) +/// * AES128_BLOCKSIZE - 1 = 431. +pub const ENCRYPTED_MDU: usize = + ((MTU - 1 - HEADER_MINSIZE - TOKEN_OVERHEAD) / AES128_BLOCKSIZE) * AES128_BLOCKSIZE - 1; + +/// MDU available to plaintext (unencrypted) payloads. +pub const PLAIN_MDU: usize = MDU; + +/// Default per-hop timeout in seconds. +pub const DEFAULT_PER_HOP_TIMEOUT: f64 = 6.0; + +/// Name hash length in bytes (80 bits = 10 bytes). +pub const NAME_HASH_LENGTH: usize = 10; + +/// Ratchet size in bytes (256 bits = 32 bytes). +pub const RATCHETSIZE: usize = 32; + +/// Ratchet count — max retained ratchet keys. +pub const RATCHET_COUNT: usize = 512; + +/// Ratchet interval — minimum seconds between rotations. +pub const RATCHET_INTERVAL: u64 = 1800; + +/// Ratchet expiry — seconds before received ratchets expire (30 days). +pub const RATCHET_EXPIRY: u64 = 2_592_000; + +/// Explicit proof length: packet_hash(32) + signature(64) = 96 bytes. +pub const EXPL_LENGTH: usize = 96; + +/// Implicit proof length: signature(64) = 64 bytes. +pub const IMPL_LENGTH: usize = 64; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_derived_constants() { + assert_eq!(HEADER_MINSIZE, 19); + assert_eq!(HEADER_MAXSIZE, 35); + assert_eq!(MDU, 464); + assert_eq!(ENCRYPTED_MDU, 431); + assert_eq!(TRUNCATED_HASHLENGTH / 8, 16); + assert_eq!(HASHLENGTH / 8, 32); + assert_eq!(KEYSIZE / 8, 64); + assert_eq!(SIGLENGTH / 8, 64); + } +} diff --git a/crates/rns-wire/src/context.rs b/crates/rns-wire/src/context.rs new file mode 100644 index 0000000..3472bf6 --- /dev/null +++ b/crates/rns-wire/src/context.rs @@ -0,0 +1,148 @@ +//! Packet context byte — a one-byte discriminator carried in every header. + +/// Context byte carried in the packet header. Unknown bytes are preserved +/// via [`PacketContext::Unknown`] so forward-compatible contexts round-trip. +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PacketContext { + None, + Resource, + ResourceAdv, + ResourceReq, + ResourceHmu, + ResourcePrf, + ResourceIcl, + ResourceRcl, + CacheRequest, + Request, + Response, + PathResponse, + Command, + CommandStatus, + Channel, + Keepalive, + LinkIdentify, + LinkClose, + LinkProof, + Lrrtt, + Lrproof, + /// Unrecognised context byte; preserved verbatim for forward compatibility. + Unknown(u8), +} + +impl PacketContext { + /// Decode a context byte. + pub fn from_byte(byte: u8) -> Self { + match byte { + 0x00 => Self::None, + 0x01 => Self::Resource, + 0x02 => Self::ResourceAdv, + 0x03 => Self::ResourceReq, + 0x04 => Self::ResourceHmu, + 0x05 => Self::ResourcePrf, + 0x06 => Self::ResourceIcl, + 0x07 => Self::ResourceRcl, + 0x08 => Self::CacheRequest, + 0x09 => Self::Request, + 0x0A => Self::Response, + 0x0B => Self::PathResponse, + 0x0C => Self::Command, + 0x0D => Self::CommandStatus, + 0x0E => Self::Channel, + 0xFA => Self::Keepalive, + 0xFB => Self::LinkIdentify, + 0xFC => Self::LinkClose, + 0xFD => Self::LinkProof, + 0xFE => Self::Lrrtt, + 0xFF => Self::Lrproof, + other => Self::Unknown(other), + } + } + + /// Encode as the single wire byte. + pub fn to_byte(self) -> u8 { + match self { + Self::None => 0x00, + Self::Resource => 0x01, + Self::ResourceAdv => 0x02, + Self::ResourceReq => 0x03, + Self::ResourceHmu => 0x04, + Self::ResourcePrf => 0x05, + Self::ResourceIcl => 0x06, + Self::ResourceRcl => 0x07, + Self::CacheRequest => 0x08, + Self::Request => 0x09, + Self::Response => 0x0A, + Self::PathResponse => 0x0B, + Self::Command => 0x0C, + Self::CommandStatus => 0x0D, + Self::Channel => 0x0E, + Self::Keepalive => 0xFA, + Self::LinkIdentify => 0xFB, + Self::LinkClose => 0xFC, + Self::LinkProof => 0xFD, + Self::Lrrtt => 0xFE, + Self::Lrproof => 0xFF, + Self::Unknown(b) => b, + } + } + + /// Whether packets with this context are transmitted in plaintext. + /// + /// Resource, ResourcePrf, Keepalive, and CacheRequest bypass `Packet.pack()` + /// encryption so they can be relayed by nodes without the link key. + pub fn is_plaintext_context(self) -> bool { + matches!( + self, + Self::Resource | Self::ResourcePrf | Self::Keepalive | Self::CacheRequest + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_roundtrip_all_known() { + let known = [ + PacketContext::None, + PacketContext::Resource, + PacketContext::ResourceAdv, + PacketContext::ResourceReq, + PacketContext::ResourceHmu, + PacketContext::ResourcePrf, + PacketContext::ResourceIcl, + PacketContext::ResourceRcl, + PacketContext::CacheRequest, + PacketContext::Request, + PacketContext::Response, + PacketContext::PathResponse, + PacketContext::Command, + PacketContext::CommandStatus, + PacketContext::Channel, + PacketContext::Keepalive, + PacketContext::LinkIdentify, + PacketContext::LinkClose, + PacketContext::LinkProof, + PacketContext::Lrrtt, + PacketContext::Lrproof, + ]; + for ctx in known { + let byte = ctx.to_byte(); + let parsed = PacketContext::from_byte(byte); + assert_eq!(parsed, ctx); + } + } + + #[test] + fn test_unknown_byte_preserved() { + let ctx = PacketContext::from_byte(0x0F); + assert_eq!(ctx, PacketContext::Unknown(0x0F)); + assert_eq!(ctx.to_byte(), 0x0F); + + let ctx2 = PacketContext::from_byte(0x99); + assert_eq!(ctx2, PacketContext::Unknown(0x99)); + assert_eq!(ctx2.to_byte(), 0x99); + } +} diff --git a/crates/rns-wire/src/flags.rs b/crates/rns-wire/src/flags.rs new file mode 100644 index 0000000..3bb92a3 --- /dev/null +++ b/crates/rns-wire/src/flags.rs @@ -0,0 +1,194 @@ +//! Decoded view of the packet flags byte. + +/// Packet type carried in the lower 2 bits of the flags byte. +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum PacketType { + Data = 0x00, + Announce = 0x01, + LinkRequest = 0x02, + Proof = 0x03, +} + +/// Destination kind carried in bits 3-2 of the flags byte. +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum DestinationType { + Single = 0x00, + Group = 0x01, + Plain = 0x02, + Link = 0x03, +} + +/// Header layout (bit 6 of flags): single-hash vs. transport-id + dest-hash. +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum HeaderType { + Header1 = 0x00, + Header2 = 0x01, +} + +/// Propagation mode (bit 4 of flags): link-local broadcast vs. routed transport. +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum TransportType { + Broadcast = 0x00, + Transport = 0x01, +} + +/// Decoded view of the single flags byte at offset 0 of every packet. +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PacketFlags { + pub header_type: HeaderType, + pub context_flag: bool, + pub transport_type: TransportType, + pub destination_type: DestinationType, + pub packet_type: PacketType, +} + +impl PacketFlags { + /// Pack flags into a single byte. + /// + /// Bit layout (from Python Packet.py:168-174): + /// Bit 7: unused/reserved (always 0) + /// Bit 6: header_type + /// Bit 5: context_flag + /// Bit 4: transport_type + /// Bits 3-2: destination_type + /// Bits 1-0: packet_type + pub fn pack(&self) -> u8 { + let ht = (self.header_type as u8) << 6; + let cf = (self.context_flag as u8) << 5; + let tt = (self.transport_type as u8) << 4; + let dt = (self.destination_type as u8) << 2; + let pt = self.packet_type as u8; + ht | cf | tt | dt | pt + } + + /// Unpack flags from a single byte. + /// + /// Follows Python's unpack masks (Packet.py:246-250): + /// header_type = (flags & 0b01000000) >> 6 + /// context_flag = (flags & 0b00100000) >> 5 + /// transport_type = (flags & 0b00010000) >> 4 + /// destination_type = (flags & 0b00001100) >> 2 + /// packet_type = (flags & 0b00000011) + pub fn unpack(byte: u8) -> Option { + let header_type = match (byte & 0b0100_0000) >> 6 { + 0 => HeaderType::Header1, + 1 => HeaderType::Header2, + _ => unreachable!(), + }; + let context_flag = (byte & 0b0010_0000) >> 5 != 0; + let transport_type = match (byte & 0b0001_0000) >> 4 { + 0 => TransportType::Broadcast, + 1 => TransportType::Transport, + _ => unreachable!(), + }; + let destination_type = match (byte & 0b0000_1100) >> 2 { + 0 => DestinationType::Single, + 1 => DestinationType::Group, + 2 => DestinationType::Plain, + 3 => DestinationType::Link, + _ => unreachable!(), + }; + let packet_type = match byte & 0b0000_0011 { + 0 => PacketType::Data, + 1 => PacketType::Announce, + 2 => PacketType::LinkRequest, + 3 => PacketType::Proof, + _ => unreachable!(), + }; + + Some(Self { + header_type, + context_flag, + transport_type, + destination_type, + packet_type, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pack_unpack_roundtrip() { + let flags = PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Data, + }; + let byte = flags.pack(); + assert_eq!(byte, 0x00); + assert_eq!(PacketFlags::unpack(byte), Some(flags)); + } + + #[test] + fn test_all_ones() { + let flags = PacketFlags { + header_type: HeaderType::Header2, + context_flag: true, + transport_type: TransportType::Transport, + destination_type: DestinationType::Link, + packet_type: PacketType::Proof, + }; + let byte = flags.pack(); + // Every defined bit set: 0b01111111. + assert_eq!(byte, 0x7F); + assert_eq!(PacketFlags::unpack(byte), Some(flags)); + } + + #[test] + fn test_announce_flags() { + let flags = PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Announce, + }; + let byte = flags.pack(); + assert_eq!(byte, 0x01); + } + + #[test] + fn test_transport_header2() { + let flags = PacketFlags { + header_type: HeaderType::Header2, + context_flag: false, + transport_type: TransportType::Transport, + destination_type: DestinationType::Single, + packet_type: PacketType::Data, + }; + let byte = flags.pack(); + // header_type(bit 6) | transport_type(bit 4) = 0x50. + assert_eq!(byte, 0x50); + } + + #[test] + fn test_bit7_ignored_on_unpack() { + // Bit 7 is reserved; parsing must ignore it. + let byte = 0x80 | 0x01; + let flags = PacketFlags::unpack(byte).unwrap(); + assert_eq!(flags.header_type, HeaderType::Header1); + assert_eq!(flags.packet_type, PacketType::Announce); + } + + #[test] + fn test_exhaustive_roundtrip() { + for byte in 0..=0x7Fu8 { + let flags = PacketFlags::unpack(byte).unwrap(); + assert_eq!(flags.pack(), byte); + } + } +} diff --git a/crates/rns-wire/src/hash.rs b/crates/rns-wire/src/hash.rs new file mode 100644 index 0000000..2e8d6be --- /dev/null +++ b/crates/rns-wire/src/hash.rs @@ -0,0 +1,148 @@ +//! Packet hashing — the bytes that contribute to a packet's identity hash +//! (excludes hop counter and routing-only fields so it's stable across hops). + +use alloc::vec::Vec; +use rns_crypto::sha::truncated_hash; + +use crate::constants::TRUNCATED_HASHLENGTH; +use crate::flags::HeaderType; + +/// Extract the portion of a raw packet that contributes to its hash. +/// +/// Per Packet.py:345-361 the hop counter, routing-only flag bits, and +/// (for Header2) the transport id are excluded so a packet's hash is stable +/// across forwarding. +pub fn get_hashable_part(raw: &[u8], header_type: HeaderType) -> Vec { + let mut hashable = Vec::new(); + + // Only the lower nibble of flags is hash-stable (upper bits carry routing state). + hashable.push(raw[0] & 0x0F); + + match header_type { + HeaderType::Header2 => { + // Skip flags + hops + transport_id. + let skip = (TRUNCATED_HASHLENGTH / 8) + 2; + if raw.len() > skip { + hashable.extend_from_slice(&raw[skip..]); + } + } + HeaderType::Header1 => { + // Skip flags + hops. + if raw.len() > 2 { + hashable.extend_from_slice(&raw[2..]); + } + } + } + + hashable +} + +/// Full SHA-256 hash of the hashable portion of a raw packet. +/// +/// Equivalent to `sha256(get_hashable_part(raw, header_type))` but streams +/// directly into the hasher to avoid an intermediate allocation. +pub fn packet_hash(raw: &[u8], header_type: HeaderType) -> [u8; 32] { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update([raw[0] & 0x0F]); + let skip = match header_type { + HeaderType::Header2 => (TRUNCATED_HASHLENGTH / 8) + 2, + HeaderType::Header1 => 2, + }; + if raw.len() > skip { + hasher.update(&raw[skip..]); + } + hasher.finalize().into() +} + +/// [`packet_hash`] truncated to the first 16 bytes. +pub fn truncated_packet_hash(raw: &[u8], header_type: HeaderType) -> [u8; 16] { + let full = packet_hash(raw, header_type); + let mut out = [0u8; 16]; + out.copy_from_slice(&full[..16]); + out +} + +/// Return both full and truncated packet hashes from a single SHA-256 pass. +pub fn packet_hash_pair(raw: &[u8], header_type: HeaderType) -> ([u8; 32], [u8; 16]) { + let full = packet_hash(raw, header_type); + let mut trunc = [0u8; 16]; + trunc.copy_from_slice(&full[..16]); + (full, trunc) +} + +/// Derive the link id of a link-request packet. +/// +/// Mirrors Python `Link.link_id_from_lr_packet`: take the hashable part, +/// clip the payload to the 64-byte ECPUBSIZE (X25519 || Ed25519 public keys) +/// so trailing padding doesn't change the id, then truncate SHA-256 to 16 bytes. +pub fn link_id_from_raw(raw: &[u8], header_type: HeaderType) -> [u8; 16] { + const ECPUBSIZE: usize = 64; + let mut hashable = get_hashable_part(raw, header_type); + // Hashable layout: flags_nibble(1) || dest_hash(16) || context(1) || payload. + let header_in_hashable = 1 + 16 + 1; + let data_in_hashable = hashable.len().saturating_sub(header_in_hashable); + if data_in_hashable > ECPUBSIZE { + let diff = data_in_hashable - ECPUBSIZE; + hashable.truncate(hashable.len() - diff); + } + truncated_hash(&hashable) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + #[test] + fn test_hashable_part_header1() { + let mut raw = vec![0u8; 19]; + raw[0] = 0x71; + raw[1] = 5; + + let hashable = get_hashable_part(&raw, HeaderType::Header1); + // Upper nibble of flags is stripped. + assert_eq!(hashable[0], 0x01); + assert_eq!(hashable.len(), 1 + 17); + } + + #[test] + fn test_hashable_part_header2() { + let mut raw = vec![0u8; 35]; + raw[0] = 0x50; + + let hashable = get_hashable_part(&raw, HeaderType::Header2); + assert_eq!(hashable[0], 0x00); + // dest_hash(16) + context(1) survive; transport_id is skipped. + assert_eq!(hashable.len(), 1 + 17); + } + + #[test] + fn test_same_hash_different_routing() { + // Hop count is routing metadata and must not influence the hash. + let dest = [0xAA; 16]; + let context = 0x00u8; + let data = [0xBB; 10]; + + let mut h1_raw = Vec::new(); + h1_raw.push(0x00); + h1_raw.push(3); + h1_raw.extend_from_slice(&dest); + h1_raw.push(context); + h1_raw.extend_from_slice(&data); + + let mut h1_raw2 = h1_raw.clone(); + h1_raw2[1] = 7; + + let hash1 = packet_hash(&h1_raw, HeaderType::Header1); + let hash2 = packet_hash(&h1_raw2, HeaderType::Header1); + assert_eq!(hash1, hash2, "hops should not affect hash"); + } + + #[test] + fn test_truncated_hash_length() { + let raw = vec![0u8; 19]; + let hash = truncated_packet_hash(&raw, HeaderType::Header1); + assert_eq!(hash.len(), 16); + } +} diff --git a/crates/rns-wire/src/header.rs b/crates/rns-wire/src/header.rs new file mode 100644 index 0000000..452885b --- /dev/null +++ b/crates/rns-wire/src/header.rs @@ -0,0 +1,251 @@ +//! Packet header parsing and serialization. + +use alloc::vec::Vec; +use thiserror::Error; + +use crate::constants::{HEADER_MAXSIZE, HEADER_MINSIZE, TRUNCATED_HASHLENGTH}; +use crate::context::PacketContext; +use crate::flags::{HeaderType, PacketFlags}; + +/// Errors surfaced by header parsing. +#[allow(missing_docs)] +#[derive(Debug, Error)] +pub enum HeaderError { + #[error("raw packet too short: {0} bytes (minimum {HEADER_MINSIZE})")] + TooShort(usize), +} + +/// Parsed packet header. `transport_id` is `Some` exactly for Header2 packets. +#[allow(missing_docs)] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PacketHeader { + pub flags: PacketFlags, + pub hops: u8, + pub transport_id: Option<[u8; 16]>, + pub destination_hash: [u8; 16], + pub context: PacketContext, +} + +impl PacketHeader { + /// Serialize the header to wire bytes. + pub fn pack(&self) -> Vec { + let mut out = Vec::with_capacity(HEADER_MAXSIZE); + out.push(self.flags.pack()); + out.push(self.hops); + if let Some(ref tid) = self.transport_id { + out.extend_from_slice(tid); + } + out.extend_from_slice(&self.destination_hash); + out.push(self.context.to_byte()); + out + } + + /// Parse a header from the start of `raw`. + /// + /// Returns `(header, data_offset)` where `data_offset` is the first byte + /// of the payload. + pub fn unpack(raw: &[u8]) -> Result<(Self, usize), HeaderError> { + if raw.len() < HEADER_MINSIZE { + return Err(HeaderError::TooShort(raw.len())); + } + + let flags = PacketFlags::unpack(raw[0]).ok_or(HeaderError::TooShort(raw.len()))?; + let hops = raw[1]; + let hash_len = TRUNCATED_HASHLENGTH / 8; + + match flags.header_type { + HeaderType::Header1 => { + let mut dest_hash = [0u8; 16]; + dest_hash.copy_from_slice(&raw[2..2 + hash_len]); + + let context = PacketContext::from_byte(raw[2 + hash_len]); + + let data_offset = 2 + hash_len + 1; + + Ok(( + Self { + flags, + hops, + transport_id: None, + destination_hash: dest_hash, + context, + }, + data_offset, + )) + } + HeaderType::Header2 => { + if raw.len() < HEADER_MAXSIZE { + return Err(HeaderError::TooShort(raw.len())); + } + + let mut transport_id = [0u8; 16]; + transport_id.copy_from_slice(&raw[2..2 + hash_len]); + + let mut dest_hash = [0u8; 16]; + dest_hash.copy_from_slice(&raw[2 + hash_len..2 + hash_len * 2]); + + let context = PacketContext::from_byte(raw[2 + hash_len * 2]); + + let data_offset = 2 + hash_len * 2 + 1; + + Ok(( + Self { + flags, + hops, + transport_id: Some(transport_id), + destination_hash: dest_hash, + context, + }, + data_offset, + )) + } + } + } + + /// Serialized header size. + pub fn size(&self) -> usize { + if self.transport_id.is_some() { + HEADER_MAXSIZE + } else { + HEADER_MINSIZE + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::flags::*; + use alloc::vec; + + #[test] + fn test_pack_header1() { + let hdr = PacketHeader { + flags: PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: [0xAA; 16], + context: PacketContext::None, + }; + let packed = hdr.pack(); + assert_eq!(packed.len(), HEADER_MINSIZE); + assert_eq!(packed[0], 0x00); + assert_eq!(packed[1], 0x00); + assert_eq!(&packed[2..18], &[0xAA; 16]); + assert_eq!(packed[18], 0x00); + } + + #[test] + fn test_pack_header2() { + let hdr = PacketHeader { + flags: PacketFlags { + header_type: HeaderType::Header2, + context_flag: false, + transport_type: TransportType::Transport, + destination_type: DestinationType::Single, + packet_type: PacketType::Data, + }, + hops: 3, + transport_id: Some([0xBB; 16]), + destination_hash: [0xCC; 16], + context: PacketContext::None, + }; + let packed = hdr.pack(); + assert_eq!(packed.len(), HEADER_MAXSIZE); + assert_eq!(&packed[2..18], &[0xBB; 16]); + assert_eq!(&packed[18..34], &[0xCC; 16]); + } + + #[test] + fn test_unpack_header1() { + let mut raw = vec![0u8; 30]; + raw[0] = 0x01; + raw[1] = 5; + raw[2..18].copy_from_slice(&[0xDD; 16]); + raw[18] = 0x00; + + let (hdr, offset) = PacketHeader::unpack(&raw).unwrap(); + assert_eq!(hdr.flags.packet_type, PacketType::Announce); + assert_eq!(hdr.hops, 5); + assert_eq!(hdr.destination_hash, [0xDD; 16]); + assert_eq!(hdr.transport_id, None); + assert_eq!(hdr.context, PacketContext::None); + assert_eq!(offset, 19); + } + + #[test] + fn test_roundtrip_header1() { + let hdr = PacketHeader { + flags: PacketFlags { + header_type: HeaderType::Header1, + context_flag: true, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Plain, + packet_type: PacketType::Data, + }, + hops: 42, + transport_id: None, + destination_hash: [0x12; 16], + context: PacketContext::Channel, + }; + let packed = hdr.pack(); + let (unpacked, _) = PacketHeader::unpack(&packed).unwrap(); + assert_eq!(hdr, unpacked); + } + + #[test] + fn test_too_short() { + assert!(PacketHeader::unpack(&[0u8; 5]).is_err()); + } + + use proptest::prelude::*; + + fn any_packet_flags() -> impl Strategy { + // Bit 7 is reserved; only 0x00..=0x7F decode. + (0u8..=0x7F).prop_map(|byte| PacketFlags::unpack(byte).unwrap()) + } + + proptest! { + #[test] + fn proptest_header_pack_unpack_roundtrip( + flags in any_packet_flags(), + hops: u8, + transport_id: [u8; 16], + destination_hash: [u8; 16], + context_byte: u8, + ) { + let header = PacketHeader { + flags, + hops, + transport_id: match flags.header_type { + HeaderType::Header1 => None, + HeaderType::Header2 => Some(transport_id), + }, + destination_hash, + context: PacketContext::from_byte(context_byte), + }; + let packed = header.pack(); + let (unpacked, _offset) = PacketHeader::unpack(&packed).unwrap(); + prop_assert_eq!(&header, &unpacked); + prop_assert_eq!(unpacked.pack(), packed); + } + + #[test] + fn proptest_context_byte_preserving(byte: u8) { + let ctx = PacketContext::from_byte(byte); + prop_assert_eq!(ctx.to_byte(), byte); + } + + #[test] + fn proptest_flags_byte_preserving(byte in 0u8..=0x7F) { + let flags = PacketFlags::unpack(byte).unwrap(); + prop_assert_eq!(flags.pack(), byte); + } + } +} diff --git a/crates/rns-wire/src/lib.rs b/crates/rns-wire/src/lib.rs new file mode 100644 index 0000000..e0c9ed0 --- /dev/null +++ b/crates/rns-wire/src/lib.rs @@ -0,0 +1,19 @@ +//! Reticulum wire format: packets, headers, flags, receipts, proofs. +//! +//! Source of truth for packet bit-packing — must match the Python reference +//! ([`Packet.py`](https://github.com/markqvist/Reticulum/blob/master/RNS/Packet.py)) +//! exactly. `no_std + alloc` when `std` is off; `receipt` is `std`-only. +#![cfg_attr(not(feature = "std"), no_std)] +#![warn(missing_docs)] +extern crate alloc; + +pub mod constants; +pub mod context; +pub mod flags; +pub mod hash; +pub mod header; +pub mod packet; +pub mod proof; +#[cfg(feature = "std")] +pub mod receipt; +pub mod types; diff --git a/crates/rns-wire/src/packet.rs b/crates/rns-wire/src/packet.rs new file mode 100644 index 0000000..dce4785 --- /dev/null +++ b/crates/rns-wire/src/packet.rs @@ -0,0 +1,198 @@ +//! Full parsed-packet type: header + payload + cached hashes. + +use alloc::vec::Vec; +use thiserror::Error; + +use crate::constants::MTU; +use crate::hash::{packet_hash, truncated_packet_hash}; +use crate::header::{HeaderError, PacketHeader}; + +/// Errors surfaced by [`Packet::new`] and [`Packet::from_raw`]. +#[allow(missing_docs)] +#[derive(Debug, Error)] +pub enum PacketError { + #[error("packet exceeds MTU ({MTU} bytes): {0} bytes")] + ExceedsMtu(usize), + #[error("header error: {0}")] + Header(#[from] HeaderError), + #[error("packet too short")] + TooShort, +} + +/// A parsed Reticulum packet. +/// +/// `raw` is the on-wire representation; the payload is the trailing slice +/// `raw[data_offset..]`, exposed via [`Packet::data`]. `packet_hash` and +/// `truncated_hash` are cached at construction (see [`crate::hash`]). +#[allow(missing_docs)] +#[derive(Debug, Clone)] +pub struct Packet { + pub header: PacketHeader, + pub raw: Vec, + data_offset: usize, + pub packet_hash: [u8; 32], + pub truncated_hash: [u8; 16], +} + +impl Packet { + /// Payload bytes — the slice of `raw` after the packed header. + #[inline] + pub fn data(&self) -> &[u8] { + &self.raw[self.data_offset..] + } + + /// Build a packet from a header and payload, precomputing its hashes. + pub fn new(header: PacketHeader, data: Vec) -> Result { + let mut raw = header.pack(); + let data_offset = raw.len(); + raw.extend_from_slice(&data); + + if raw.len() > MTU { + return Err(PacketError::ExceedsMtu(raw.len())); + } + + let hash = packet_hash(&raw, header.flags.header_type); + let trunc = truncated_packet_hash(&raw, header.flags.header_type); + + Ok(Self { + header, + raw, + data_offset, + packet_hash: hash, + truncated_hash: trunc, + }) + } + + /// Parse a packet from borrowed wire bytes. Allocates one `Vec` to + /// own the buffer; callers that already own the buffer should use + /// [`Packet::from_raw_owned`] instead. + pub fn from_raw(raw: &[u8]) -> Result { + Self::from_raw_owned(raw.to_vec()) + } + + /// Parse a packet from owned wire bytes. Saves one allocation versus + /// [`Packet::from_raw`] when the caller already owns the buffer. + pub fn from_raw_owned(raw: Vec) -> Result { + if raw.len() < 19 { + return Err(PacketError::TooShort); + } + + let (header, data_offset) = PacketHeader::unpack(&raw)?; + let hash = packet_hash(&raw, header.flags.header_type); + let trunc = truncated_packet_hash(&raw, header.flags.header_type); + + Ok(Self { + header, + raw, + data_offset, + packet_hash: hash, + truncated_hash: trunc, + }) + } + + /// Increment the hop counter in both the header and the raw bytes. + /// + /// Saturates at 255 so a forwarded packet cannot wrap around. + pub fn increment_hops(&mut self) { + if self.header.hops < 255 { + self.header.hops += 1; + if self.raw.len() > 1 { + self.raw[1] = self.header.hops; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::PacketContext; + use crate::flags::*; + use alloc::vec; + + fn make_test_header() -> PacketHeader { + PacketHeader { + flags: PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Single, + packet_type: PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: [0xAA; 16], + context: PacketContext::None, + } + } + + #[test] + fn test_new_packet() { + let hdr = make_test_header(); + let data = vec![0x01, 0x02, 0x03]; + let pkt = Packet::new(hdr, data.clone()).unwrap(); + assert_eq!(pkt.data(), data.as_slice()); + assert_eq!(pkt.raw.len(), 19 + 3); + } + + #[test] + fn test_from_raw_roundtrip() { + let hdr = make_test_header(); + let data = vec![0xDE, 0xAD, 0xBE, 0xEF]; + let pkt1 = Packet::new(hdr, data).unwrap(); + let pkt2 = Packet::from_raw(&pkt1.raw).unwrap(); + + assert_eq!(pkt1.header, pkt2.header); + assert_eq!(pkt1.data(), pkt2.data()); + assert_eq!(pkt1.packet_hash, pkt2.packet_hash); + assert_eq!(pkt1.truncated_hash, pkt2.truncated_hash); + } + + #[test] + fn test_from_raw_owned_matches_borrowed() { + let hdr = make_test_header(); + let data = vec![0xCA, 0xFE, 0xBA, 0xBE]; + let pkt = Packet::new(hdr, data).unwrap(); + let raw = pkt.raw.clone(); + let owned = Packet::from_raw_owned(raw).unwrap(); + let borrowed = Packet::from_raw(&pkt.raw).unwrap(); + assert_eq!(owned.header, borrowed.header); + assert_eq!(owned.data(), borrowed.data()); + assert_eq!(owned.packet_hash, borrowed.packet_hash); + assert_eq!(owned.raw, pkt.raw); + } + + #[test] + fn test_exceeds_mtu() { + let hdr = make_test_header(); + let data = vec![0u8; MTU]; + assert!(Packet::new(hdr, data).is_err()); + } + + #[test] + fn test_increment_hops() { + let hdr = make_test_header(); + let mut pkt = Packet::new(hdr, vec![0x01]).unwrap(); + assert_eq!(pkt.header.hops, 0); + pkt.increment_hops(); + assert_eq!(pkt.header.hops, 1); + assert_eq!(pkt.raw[1], 1); + } + + #[test] + fn test_max_hops() { + let mut hdr = make_test_header(); + hdr.hops = 255; + let mut pkt = Packet::new(hdr, vec![0x01]).unwrap(); + pkt.increment_hops(); + assert_eq!(pkt.header.hops, 255); + } + + #[test] + fn test_hash_stability() { + let hdr = make_test_header(); + let pkt1 = Packet::new(hdr.clone(), vec![0x42; 10]).unwrap(); + let pkt2 = Packet::new(hdr, vec![0x42; 10]).unwrap(); + assert_eq!(pkt1.packet_hash, pkt2.packet_hash); + } +} diff --git a/crates/rns-wire/src/proof.rs b/crates/rns-wire/src/proof.rs new file mode 100644 index 0000000..5c6c4cd --- /dev/null +++ b/crates/rns-wire/src/proof.rs @@ -0,0 +1,97 @@ +//! Body of a PROOF packet (explicit or implicit form). + +use crate::constants::{EXPL_LENGTH, IMPL_LENGTH}; +use alloc::vec::Vec; + +/// Body of a PROOF packet. +#[allow(missing_docs)] +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProofData { + /// 96-byte form: packet hash followed by its Ed25519 signature. + Explicit { + packet_hash: [u8; 32], + signature: [u8; 64], + }, + /// 64-byte form: signature only; the hash is known from the matching receipt. + Implicit { signature: [u8; 64] }, +} + +impl ProofData { + /// Parse a proof body, dispatching on its 96- or 64-byte length. + pub fn from_bytes(data: &[u8]) -> Option { + match data.len() { + EXPL_LENGTH => { + let mut hash = [0u8; 32]; + hash.copy_from_slice(&data[..32]); + let mut sig = [0u8; 64]; + sig.copy_from_slice(&data[32..96]); + Some(Self::Explicit { + packet_hash: hash, + signature: sig, + }) + } + IMPL_LENGTH => { + let mut sig = [0u8; 64]; + sig.copy_from_slice(&data[..64]); + Some(Self::Implicit { signature: sig }) + } + _ => None, + } + } + + /// Serialize the proof body. + pub fn to_bytes(&self) -> Vec { + match self { + Self::Explicit { + packet_hash, + signature, + } => { + let mut out = Vec::with_capacity(EXPL_LENGTH); + out.extend_from_slice(packet_hash); + out.extend_from_slice(signature); + out + } + Self::Implicit { signature } => signature.to_vec(), + } + } + + /// Signature, present in both proof forms. + pub fn signature(&self) -> &[u8; 64] { + match self { + Self::Explicit { signature, .. } | Self::Implicit { signature } => signature, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_explicit_roundtrip() { + let proof = ProofData::Explicit { + packet_hash: [0xAA; 32], + signature: [0xBB; 64], + }; + let bytes = proof.to_bytes(); + assert_eq!(bytes.len(), 96); + let parsed = ProofData::from_bytes(&bytes).unwrap(); + assert_eq!(parsed, proof); + } + + #[test] + fn test_implicit_roundtrip() { + let proof = ProofData::Implicit { + signature: [0xCC; 64], + }; + let bytes = proof.to_bytes(); + assert_eq!(bytes.len(), 64); + let parsed = ProofData::from_bytes(&bytes).unwrap(); + assert_eq!(parsed, proof); + } + + #[test] + fn test_invalid_length() { + assert!(ProofData::from_bytes(&[0u8; 50]).is_none()); + } +} diff --git a/crates/rns-wire/src/receipt.rs b/crates/rns-wire/src/receipt.rs new file mode 100644 index 0000000..a166f6f --- /dev/null +++ b/crates/rns-wire/src/receipt.rs @@ -0,0 +1,180 @@ +//! Tracks sent packets until they are delivered, time out, or are culled. + +use std::time::{Duration, Instant}; + +pub use crate::constants::{EXPL_LENGTH, IMPL_LENGTH}; + +/// Lifecycle state of a tracked packet. +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ReceiptStatus { + Sent = 0x01, + Delivered = 0x02, + Failed = 0x00, + Culled = 0xFF, + /// Resource transfer in progress. + Receiving = 0x06, +} + +/// Tracks a sent packet until it is delivered, times out, or is culled. +#[allow(missing_docs)] +pub struct PacketReceipt { + pub hash: [u8; 32], + pub truncated_hash: [u8; 16], + pub status: ReceiptStatus, + pub sent_at: Instant, + pub concluded_at: Option, + pub timeout: Option, + pub callbacks: ReceiptCallbacks, +} + +/// Optional callbacks invoked when a receipt transitions out of `Sent`. +#[allow(missing_docs)] +#[derive(Default)] +pub struct ReceiptCallbacks { + pub delivery: Option, + pub timeout: Option, +} + +/// Callback invoked once when a packet receipt reaches a terminal state. +pub type ReceiptCallback = Box; + +impl PacketReceipt { + /// Create a new receipt in the `Sent` state, stamping `sent_at` to now. + pub fn new(hash: [u8; 32], truncated_hash: [u8; 16], timeout: Option) -> Self { + Self { + hash, + truncated_hash, + status: ReceiptStatus::Sent, + sent_at: Instant::now(), + concluded_at: None, + timeout, + callbacks: ReceiptCallbacks::default(), + } + } + + /// Transition to `Delivered` and fire the delivery callback. + pub fn deliver(&mut self) { + self.status = ReceiptStatus::Delivered; + self.concluded_at = Some(Instant::now()); + if let Some(cb) = self.callbacks.delivery.take() { + cb(self); + } + } + + /// Transition to `Failed` and fire the timeout callback. + pub fn fail(&mut self) { + self.status = ReceiptStatus::Failed; + self.concluded_at = Some(Instant::now()); + if let Some(cb) = self.callbacks.timeout.take() { + cb(self); + } + } + + /// Transition to `Culled` without firing any callback. + pub fn cull(&mut self) { + self.status = ReceiptStatus::Culled; + self.concluded_at = Some(Instant::now()); + } + + /// Measured round-trip time, if this receipt has concluded. + pub fn get_rtt(&self) -> Option { + self.concluded_at.map(|t| t.duration_since(self.sent_at)) + } + + /// Whether the configured timeout (if any) has elapsed since `sent_at`. + pub fn is_timed_out(&self) -> bool { + match self.timeout { + Some(timeout) => self.sent_at.elapsed() > timeout, + None => false, + } + } + + /// Register a callback to run once on delivery. + pub fn set_delivery_callback(&mut self, cb: impl FnOnce(&PacketReceipt) + Send + 'static) { + self.callbacks.delivery = Some(Box::new(cb)); + } + + /// Register a callback to run once on timeout. + pub fn set_timeout_callback(&mut self, cb: impl FnOnce(&PacketReceipt) + Send + 'static) { + self.callbacks.timeout = Some(Box::new(cb)); + } + + /// Validate a PROOF body and mark delivered on match. + /// Explicit (96): embedded hash must equal receipt hash. Implicit (64): + /// signature over the receipt hash. `verify` is Ed25519 verify with the + /// expected identity key. + pub fn validate_proof(&mut self, proof: &[u8], verify: F) -> bool + where + F: FnOnce(&[u8], &[u8]) -> bool, + { + if proof.len() == EXPL_LENGTH { + let proof_hash = &proof[..32]; + let signature = &proof[32..96]; + if proof_hash == self.hash && verify(signature, &self.hash) { + self.status = ReceiptStatus::Delivered; + self.concluded_at = Some(Instant::now()); + if let Some(cb) = self.callbacks.delivery.take() { + cb(self); + } + return true; + } + } else if proof.len() == IMPL_LENGTH { + let signature = &proof[..64]; + if verify(signature, &self.hash) { + self.status = ReceiptStatus::Delivered; + self.concluded_at = Some(Instant::now()); + if let Some(cb) = self.callbacks.delivery.take() { + cb(self); + } + return true; + } + } + false + } + + /// If the timeout has elapsed while still in `Sent`, transition to + /// `Failed` and fire the timeout callback. Returns whether a timeout fired. + pub fn check_timeout(&mut self) -> bool { + if self.is_timed_out() && self.status == ReceiptStatus::Sent { + self.status = ReceiptStatus::Failed; + self.concluded_at = Some(Instant::now()); + if let Some(cb) = self.callbacks.timeout.take() { + cb(self); + } + true + } else { + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_initial_state() { + let receipt = PacketReceipt::new([0; 32], [0; 16], Some(Duration::from_secs(10))); + assert_eq!(receipt.status, ReceiptStatus::Sent); + assert!(receipt.concluded_at.is_none()); + assert!(receipt.get_rtt().is_none()); + } + + #[test] + fn test_deliver() { + let mut receipt = PacketReceipt::new([0; 32], [0; 16], None); + receipt.deliver(); + assert_eq!(receipt.status, ReceiptStatus::Delivered); + assert!(receipt.concluded_at.is_some()); + assert!(receipt.get_rtt().is_some()); + } + + #[test] + fn test_fail() { + let mut receipt = PacketReceipt::new([0; 32], [0; 16], None); + receipt.fail(); + assert_eq!(receipt.status, ReceiptStatus::Failed); + } +} diff --git a/crates/rns-wire/src/types.rs b/crates/rns-wire/src/types.rs new file mode 100644 index 0000000..9f2d318 --- /dev/null +++ b/crates/rns-wire/src/types.rs @@ -0,0 +1,262 @@ +//! Semantic newtypes for fixed-length hashes and identifiers — distinct types +//! prevent silently mixing values with different meanings at call sites. + +use core::fmt; + +/// Define a newtype wrapping a fixed-size byte array. +macro_rules! hash_newtype { + ( + $(#[$meta:meta])* + $vis:vis struct $Name:ident([u8; $N:expr]); + ) => { + $(#[$meta])* + #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] + #[repr(transparent)] + $vis struct $Name(pub(crate) [u8; $N]); + + impl $Name { + /// Construct from a fixed-size byte array. + pub const fn new(bytes: [u8; $N]) -> Self { + Self(bytes) + } + + /// Construct from a slice, returning `None` on length mismatch. + pub fn from_slice(slice: &[u8]) -> Option { + if slice.len() == $N { + let mut arr = [0u8; $N]; + arr.copy_from_slice(slice); + Some(Self(arr)) + } else { + None + } + } + + /// Borrow the underlying byte array. + pub const fn as_bytes(&self) -> &[u8; $N] { + &self.0 + } + + /// Consume into the underlying byte array. + pub const fn into_bytes(self) -> [u8; $N] { + self.0 + } + + /// Byte length of this hash type. + pub const LEN: usize = $N; + } + + impl From<[u8; $N]> for $Name { + fn from(bytes: [u8; $N]) -> Self { + Self(bytes) + } + } + + impl From<&[u8; $N]> for $Name { + fn from(bytes: &[u8; $N]) -> Self { + Self(*bytes) + } + } + + impl From<$Name> for [u8; $N] { + fn from(val: $Name) -> [u8; $N] { + val.0 + } + } + + impl AsRef<[u8]> for $Name { + fn as_ref(&self) -> &[u8] { + &self.0 + } + } + + impl AsRef<[u8; $N]> for $Name { + fn as_ref(&self) -> &[u8; $N] { + &self.0 + } + } + + impl core::ops::Deref for $Name { + type Target = [u8; $N]; + fn deref(&self) -> &[u8; $N] { + &self.0 + } + } + + impl fmt::Display for $Name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for byte in &self.0 { + write!(f, "{:02x}", byte)?; + } + Ok(()) + } + } + + impl core::borrow::Borrow<[u8; $N]> for $Name { + fn borrow(&self) -> &[u8; $N] { + &self.0 + } + } + + impl fmt::Debug for $Name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Abbreviated for log readability: `TypeName(aabb..eeff)`. + write!(f, "{}(", stringify!($Name))?; + if $N <= 4 { + for byte in &self.0 { + write!(f, "{:02x}", byte)?; + } + } else { + for byte in &self.0[..2] { + write!(f, "{:02x}", byte)?; + } + write!(f, "..")?; + for byte in &self.0[$N-2..] { + write!(f, "{:02x}", byte)?; + } + } + write!(f, ")") + } + } + }; +} + +hash_newtype! { + /// Destination hash: `SHA-256(name_hash || identity_hash)[..16]`. + pub struct DestHash([u8; 16]); +} + +hash_newtype! { + /// Identifier for an active or pending link, derived from the link-request keys. + pub struct LinkId([u8; 16]); +} + +hash_newtype! { + /// Next-hop transport node's identity hash, carried in Header2 packets. + pub struct TransportId([u8; 16]); +} + +hash_newtype! { + /// Truncated hash of an identity's public keys. + pub struct IdentityHash([u8; 16]); +} + +hash_newtype! { + /// 16-byte packet hash used for duplicate detection and receipt lookup. + pub struct TruncatedHash([u8; 16]); +} + +hash_newtype! { + /// Full 32-byte SHA-256 packet hash. + pub struct FullHash([u8; 32]); +} + +hash_newtype! { + /// SHA-256 of an LXMF message, used for tracking and receipts. + pub struct MessageHash([u8; 32]); +} + +hash_newtype! { + /// 10-byte hash of an application name plus aspects. + pub struct NameHash([u8; 10]); +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::{format, vec}; + + #[test] + fn test_dest_hash_creation() { + let bytes = [0xAA; 16]; + let hash = DestHash::new(bytes); + assert_eq!(*hash.as_bytes(), bytes); + assert_eq!(hash.into_bytes(), bytes); + } + + #[test] + fn test_from_slice() { + let bytes = vec![0xBB; 16]; + let hash = DestHash::from_slice(&bytes).unwrap(); + assert_eq!(hash.0, [0xBB; 16]); + + assert!(DestHash::from_slice(&[0; 15]).is_none()); + assert!(DestHash::from_slice(&[0; 17]).is_none()); + } + + #[test] + fn test_display_hex() { + let hash = DestHash::new([ + 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, + 0xCD, 0xEF, + ]); + assert_eq!(format!("{}", hash), "0123456789abcdef0123456789abcdef"); + } + + #[test] + fn test_debug_truncated() { + let hash = DestHash::new([0xAA; 16]); + let debug = format!("{:?}", hash); + assert!(debug.starts_with("DestHash(")); + assert!(debug.contains("..")); + } + + #[test] + fn test_from_array() { + let bytes = [0xCC; 16]; + let hash: DestHash = bytes.into(); + assert_eq!(*hash, bytes); + } + + #[test] + fn test_into_array() { + let hash = DestHash::new([0xDD; 16]); + let bytes: [u8; 16] = hash.into(); + assert_eq!(bytes, [0xDD; 16]); + } + + #[test] + fn test_deref() { + let hash = DestHash::new([0xEE; 16]); + assert_eq!(hash[0], 0xEE); + assert_eq!(hash.len(), 16); + } + + #[test] + fn test_hash_map_key() { + use std::collections::HashMap; + let mut map = HashMap::new(); + let key = DestHash::new([0x11; 16]); + map.insert(key, "value"); + assert_eq!(map.get(&key), Some(&"value")); + } + + #[test] + fn test_type_safety() { + // DestHash and LinkId share a representation but are distinct types: + // `dest == link` would fail to compile. + let dest = DestHash::new([0xAA; 16]); + let link = LinkId::new([0xAA; 16]); + assert_eq!(dest, DestHash::new([0xAA; 16])); + assert_eq!(link, LinkId::new([0xAA; 16])); + } + + #[test] + fn test_full_hash() { + let hash = FullHash::new([0xFF; 32]); + assert_eq!(hash.len(), 32); + assert_eq!(FullHash::LEN, 32); + } + + #[test] + fn test_name_hash() { + let hash = NameHash::new([0x55; 10]); + assert_eq!(hash.len(), 10); + assert_eq!(NameHash::LEN, 10); + } + + #[test] + fn test_default() { + let hash = DestHash::default(); + assert_eq!(hash.0, [0; 16]); + } +}