mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
Compare commits
138
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6dd6b3ab3 | ||
|
|
3b91b36f3e | ||
|
|
3d7b989262 | ||
|
|
fdfbf09515 | ||
|
|
5bfbcef47f | ||
|
|
117f32e03e | ||
|
|
07f0ecd900 | ||
|
|
4b8bc21a9b | ||
|
|
6638c80c55 | ||
|
|
d2ad997caf | ||
|
|
d8ff9f85b7 | ||
|
|
069b653ee6 | ||
|
|
4158c5a8a9 | ||
|
|
ed66c62468 | ||
|
|
f5ec2fb16f | ||
|
|
01d0bb411b | ||
|
|
41587f80de | ||
|
|
83710bc24a | ||
|
|
69b5f40d2d | ||
|
|
7d749a4f8b | ||
|
|
51f4e56002 | ||
|
|
72e49affa0 | ||
|
|
8ead1d477c | ||
|
|
b27a7ce69f | ||
|
|
5460f013f8 | ||
|
|
442c9441a0 | ||
|
|
a5dcd3caf7 | ||
|
|
8a41710550 | ||
|
|
3fd3fa9077 | ||
|
|
2262f9ee7e | ||
|
|
f0b564be0b | ||
|
|
366ca6f02a | ||
|
|
ac98369011 | ||
|
|
849c23e624 | ||
|
|
db47d10d5a | ||
|
|
a5f06b6d00 | ||
|
|
b0cfa3be78 | ||
|
|
72ad363435 | ||
|
|
bb2c1eab65 | ||
|
|
21aa4f6308 | ||
|
|
f9b407ef5a | ||
|
|
924d27f4b1 | ||
|
|
36706c1eff | ||
|
|
5a0ea04ad0 | ||
|
|
104f425b4f | ||
|
|
c3b75f7577 | ||
|
|
c460a7c9d4 | ||
|
|
27f901ec5d | ||
|
|
ab529e875c | ||
|
|
7942aee235 | ||
|
|
cd58bbc0ac | ||
|
|
4ee47d40ac | ||
|
|
a8daa46958 | ||
|
|
eeb3e4589a | ||
|
|
132d7a2d79 | ||
|
|
27beef4564 | ||
|
|
6cd28f0337 | ||
|
|
4f011314d4 | ||
|
|
88677cef2f | ||
|
|
6181a18254 | ||
|
|
dda2470987 | ||
|
|
6c9792846e | ||
|
|
cc8927f0f9 | ||
|
|
a4083bd4fe | ||
|
|
ad279dfb67 | ||
|
|
1c63de4e0f | ||
|
|
a475caf407 | ||
|
|
f6afe585ce | ||
|
|
4623436c93 | ||
|
|
fac4dc870d | ||
|
|
4e427a7ad5 | ||
|
|
a65fd2097f | ||
|
|
26e4919ce1 | ||
|
|
bfb4bb4e14 | ||
|
|
8263bfbf4a | ||
|
|
da56d5559a | ||
|
|
6e11324b6b | ||
|
|
2f077af27b | ||
|
|
05e2cdff83 | ||
|
|
52c670e5fc | ||
|
|
4cbb7d8b59 | ||
|
|
84bfd4871d | ||
|
|
4df2e6581f | ||
|
|
8328393a5f | ||
|
|
b45f6b10de | ||
|
|
55d2d34488 | ||
|
|
73b250f36e | ||
|
|
1d4c1d6d7f | ||
|
|
d30626a098 | ||
|
|
f21f526b0a | ||
|
|
52cd1a0939 | ||
|
|
d9af1beece | ||
|
|
8b80ca88fd | ||
|
|
a2c2a256d4 | ||
|
|
112dfc1d2c | ||
|
|
f9a8f89ffd | ||
|
|
46449b21d3 | ||
|
|
08848509b6 | ||
|
|
6a4e3af78a | ||
|
|
ffe641b3af | ||
|
|
b89e434a00 | ||
|
|
0013707496 | ||
|
|
ade40c8283 | ||
|
|
20bee8bafd | ||
|
|
f1042c0bb4 | ||
|
|
9d45c9a61f | ||
|
|
a6c384f856 | ||
|
|
84b0f0175a | ||
|
|
8e7d588faf | ||
|
|
83c63b463e | ||
|
|
8ac7f9a625 | ||
|
|
c7f048bac5 | ||
|
|
7579873409 | ||
|
|
a8df6d0b36 | ||
|
|
eb2972510c | ||
|
|
6d1b43bfc4 | ||
|
|
bebb9a8fca | ||
|
|
497502596a | ||
|
|
491664d24c | ||
|
|
3e85c74917 | ||
|
|
68a83f83dc | ||
|
|
1ad1a12388 | ||
|
|
3758ae8bac | ||
|
|
15ae922535 | ||
|
|
5d0b6641cd | ||
|
|
d651a4bcea | ||
|
|
51def9d622 | ||
|
|
017b747eeb | ||
|
|
863d723531 | ||
|
|
673a9715d5 | ||
|
|
81672542ce | ||
|
|
c744831517 | ||
|
|
4cab54659c | ||
|
|
4ddbf01a2a | ||
|
|
fe665b2216 | ||
|
|
e83fa8e208 | ||
|
|
bc232d65da | ||
|
|
365bd02e75 |
No files matched your search
@@ -19,9 +19,11 @@ jobs:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
@@ -36,7 +38,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: clippy, rustfmt
|
||||
|
||||
@@ -39,11 +39,13 @@ jobs:
|
||||
env:
|
||||
ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ env.RELEASE_TAG }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
@@ -70,7 +72,7 @@ jobs:
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force
|
||||
- uses: actions/upload-artifact@v4
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ env.ARCHIVE_NAME }}
|
||||
path: |
|
||||
@@ -85,15 +87,15 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
- name: Generate checksums
|
||||
working-directory: release-assets
|
||||
run: sha256sum * > SHA256SUMS
|
||||
- uses: softprops/action-gh-release@v2
|
||||
- uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ env.RELEASE_TAG }}
|
||||
prerelease: true
|
||||
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
|
||||
files: release-assets/*
|
||||
+1
-1
@@ -6,4 +6,4 @@ __pycache__/
|
||||
/interop_artifacts/
|
||||
/rust_artifacts/
|
||||
proptest-regressions/
|
||||
/tools/
|
||||
/tools/*
|
||||
Generated
+263
-60
@@ -69,6 +69,12 @@ version = "1.0.102"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
|
||||
|
||||
[[package]]
|
||||
name = "arrayvec"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.89"
|
||||
@@ -98,6 +104,17 @@ version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bip39"
|
||||
version = "2.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
|
||||
dependencies = [
|
||||
"bitcoin_hashes",
|
||||
"serde",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
@@ -113,6 +130,15 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitcoin_hashes"
|
||||
version = "0.14.100"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9901a56e133a1fc86eeb1113e2591f45f4682451ca893bff494d2f88918e3f"
|
||||
dependencies = [
|
||||
"hex-conservative",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -252,21 +278,11 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
||||
|
||||
[[package]]
|
||||
name = "bzip2"
|
||||
version = "0.5.2"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
|
||||
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
|
||||
dependencies = [
|
||||
"bzip2-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bzip2-sys"
|
||||
version = "0.1.13+1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"libbz2-rs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -278,16 +294,6 @@ dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cesu8"
|
||||
version = "1.1.0"
|
||||
@@ -570,9 +576,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"der_derive",
|
||||
"flagset",
|
||||
"pem-rfc7468",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "des"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -580,6 +609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
@@ -655,10 +685,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
name = "flagset"
|
||||
version = "0.4.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
@@ -839,6 +869,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hex-conservative"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.12.4"
|
||||
@@ -1004,6 +1043,9 @@ name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
@@ -1011,6 +1053,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "libbz2-rs-sys"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.183"
|
||||
@@ -1027,24 +1075,10 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libudev"
|
||||
version = "0.3.0"
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"libudev-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libudev-sys"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"pkg-config",
|
||||
]
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
@@ -1082,6 +1116,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.0"
|
||||
@@ -1131,6 +1175,22 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint-dig"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"libm",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-traits",
|
||||
"rand 0.8.5",
|
||||
"smallvec",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.4.2"
|
||||
@@ -1142,6 +1202,26 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -1149,6 +1229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1250,6 +1331,15 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project"
|
||||
version = "1.1.11"
|
||||
@@ -1276,6 +1366,17 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs1"
|
||||
version = "0.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
|
||||
dependencies = [
|
||||
"der",
|
||||
"pkcs8",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
@@ -1481,7 +1582,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -1502,7 +1603,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1519,7 +1620,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bluer",
|
||||
"btleplug",
|
||||
@@ -1549,7 +1650,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1565,7 +1666,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1582,27 +1683,38 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-ratkey"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"bip39",
|
||||
"const-oid",
|
||||
"der",
|
||||
"des",
|
||||
"hex",
|
||||
"hkdf",
|
||||
"pcsc",
|
||||
"rand 0.8.5",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
"rns-link",
|
||||
"rsa",
|
||||
"serde",
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
"toml",
|
||||
"tracing",
|
||||
"x509-cert",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rns-runtime"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
"hmac",
|
||||
"md-5",
|
||||
"nix 0.29.0",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
@@ -1623,7 +1735,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-tools"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
@@ -1650,7 +1762,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1670,7 +1782,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"rns-crypto",
|
||||
@@ -1678,6 +1790,27 @@ dependencies = [
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsa"
|
||||
version = "0.9.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"digest",
|
||||
"num-bigint-dig",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
"pkcs1",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
"sha2",
|
||||
"signature",
|
||||
"spki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
@@ -1824,7 +1957,6 @@ dependencies = [
|
||||
"core-foundation",
|
||||
"core-foundation-sys",
|
||||
"io-kit-sys",
|
||||
"libudev",
|
||||
"mach2",
|
||||
"nix 0.26.4",
|
||||
"scopeguard",
|
||||
@@ -1832,6 +1964,17 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -1852,12 +1995,6 @@ dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
@@ -1874,6 +2011,7 @@ version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
@@ -1909,6 +2047,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
@@ -2043,6 +2187,42 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
|
||||
dependencies = [
|
||||
"tinyvec_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec_macros"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tls_codec"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
|
||||
dependencies = [
|
||||
"tls_codec_derive",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tls_codec_derive"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.50.0"
|
||||
@@ -2221,6 +2401,15 @@ version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-normalization"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
|
||||
dependencies = [
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.6"
|
||||
@@ -2774,6 +2963,20 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"der",
|
||||
"sha1",
|
||||
"signature",
|
||||
"spki",
|
||||
"tls_codec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xml"
|
||||
version = "1.2.1"
|
||||
|
||||
+17
-16
@@ -14,7 +14,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.9.2"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
rust-version = "1.85"
|
||||
@@ -24,9 +24,11 @@ rust-version = "1.85"
|
||||
x25519-dalek = { version = "2", features = ["static_secrets"] }
|
||||
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
|
||||
aes = "0.8"
|
||||
des = "0.8"
|
||||
cbc = { version = "0.1", features = ["alloc"] }
|
||||
hkdf = "0.12"
|
||||
hmac = "0.12"
|
||||
md-5 = "0.10"
|
||||
sha2 = "0.10"
|
||||
subtle = "2"
|
||||
zeroize = { version = "1", features = ["derive"] }
|
||||
@@ -46,16 +48,15 @@ serde_json = "1"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
# Compression
|
||||
bzip2 = "0.5"
|
||||
bzip2 = "0.6"
|
||||
|
||||
# Serial
|
||||
serialport = "4"
|
||||
|
||||
# BLE
|
||||
btleplug = "0.11"
|
||||
serialport = { version = "4", default-features = false }
|
||||
|
||||
# Networking
|
||||
if-addrs = "0.13"
|
||||
# AutoInterface requires fe80::/10 discovery addresses. if-addrs filters them
|
||||
# unless this feature is enabled, which leaves Linux/Windows with no adopted NICs.
|
||||
if-addrs = { version = "0.13", features = ["link-local"] }
|
||||
socket2 = { version = "0.5", features = ["all"] }
|
||||
|
||||
# CLI
|
||||
@@ -78,12 +79,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
|
||||
proptest = "1"
|
||||
|
||||
# Workspace crates
|
||||
rns-crypto = { path = "crates/rns-crypto", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity" }
|
||||
rns-transport = { path = "crates/rns-transport" }
|
||||
rns-link = { path = "crates/rns-link" }
|
||||
rns-protocol = { path = "crates/rns-protocol" }
|
||||
rns-interface = { path = "crates/rns-interface" }
|
||||
rns-runtime = { path = "crates/rns-runtime" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey" }
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "1.0.1", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "1.0.1", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "1.0.1" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "1.0.1" }
|
||||
rns-link = { path = "crates/rns-link", version = "1.0.1" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "1.0.1" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "1.0.1" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "1.0.1" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "1.0.1" }
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://reticulum.network/)
|
||||
[](https://reticulum.network/)
|
||||
[](#feature-status)
|
||||
|
||||
[Reticulum Manual](https://reticulum.network/manual/) |
|
||||
@@ -61,19 +61,19 @@ Debian, Ubuntu, and Raspberry Pi OS:
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y build-essential pkg-config libudev-dev
|
||||
sudo apt install -y build-essential pkg-config
|
||||
```
|
||||
|
||||
Fedora:
|
||||
|
||||
```bash
|
||||
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
|
||||
sudo dnf install gcc make pkgconf-pkg-config
|
||||
```
|
||||
|
||||
Arch:
|
||||
|
||||
```bash
|
||||
sudo pacman -S --needed base-devel pkgconf systemd
|
||||
sudo pacman -S --needed base-devel pkgconf
|
||||
```
|
||||
|
||||
##### Build the tools:
|
||||
|
||||
@@ -198,6 +198,19 @@ impl AnnounceData {
|
||||
packet_dest_hash: &[u8; 16],
|
||||
known_public_key: Option<&[u8; 64]>,
|
||||
) -> Result<Identity, AnnounceError> {
|
||||
let identity = self.verify_signature(packet_dest_hash)?;
|
||||
self.validate_destination_binding(packet_dest_hash, &identity, known_public_key)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
/// Verify the announce signature without checking destination-hash
|
||||
/// binding or first-seen key continuity.
|
||||
///
|
||||
/// Reticulum transport performs this lightweight precheck before announce
|
||||
/// ingress limiting, then runs full binding validation before learning the
|
||||
/// path. Keeping this as a distinct step lets transport match that order
|
||||
/// without duplicating announce wire-format logic.
|
||||
pub fn verify_signature(&self, packet_dest_hash: &[u8; 16]) -> Result<Identity, AnnounceError> {
|
||||
let identity = Identity::from_public_key(&self.public_key)
|
||||
.map_err(|_| AnnounceError::InvalidPublicKey)?;
|
||||
|
||||
@@ -224,6 +237,17 @@ impl AnnounceData {
|
||||
return Err(AnnounceError::SignatureInvalid);
|
||||
}
|
||||
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
/// Validate destination-hash binding and first-seen public-key continuity
|
||||
/// after [`verify_signature`] has succeeded.
|
||||
pub fn validate_destination_binding(
|
||||
&self,
|
||||
packet_dest_hash: &[u8; 16],
|
||||
identity: &Identity,
|
||||
known_public_key: Option<&[u8; 64]>,
|
||||
) -> Result<(), AnnounceError> {
|
||||
// Destination hash = SHA-256(name_hash || identity_hash) truncated to 16 bytes.
|
||||
let expected_hash = {
|
||||
let mut material = Vec::with_capacity(26);
|
||||
@@ -256,7 +280,7 @@ impl AnnounceData {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(identity)
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::persistence;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
|
||||
pub const DERIVED_KEY_LENGTH: usize = 64;
|
||||
@@ -33,6 +34,20 @@ pub enum IdentityError {
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
/// Delegate for an `Identity` whose private key is not in memory (e.g. a PIV
|
||||
/// hardware token). Implemented outside this crate (see `rns-ratkey`). Both
|
||||
/// operations must produce standard output — RFC 8032 Ed25519 / RFC 7748 X25519
|
||||
/// — so the resulting identity is wire-identical to a software one.
|
||||
pub trait LocalKeyBackend: Send + Sync {
|
||||
/// Ed25519 signature over `message`, or `None` if currently unavailable.
|
||||
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]>;
|
||||
/// X25519 ECDH shared secret with `peer_pub`, or `None` if unavailable.
|
||||
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]>;
|
||||
/// Drop any cached authentication so the next operation must re-authenticate
|
||||
/// (e.g. a hardware token re-locks its PIN). No-op for software backends.
|
||||
fn lock(&self) {}
|
||||
}
|
||||
|
||||
/// A Reticulum identity: X25519 keypair for encryption + Ed25519 keypair for signing.
|
||||
///
|
||||
/// Wire representation:
|
||||
@@ -45,6 +60,29 @@ pub struct Identity {
|
||||
pub_key: X25519PublicKey,
|
||||
sig_pub: Ed25519PublicKey,
|
||||
pub hash: [u8; 16],
|
||||
/// Set only for hardware-backed identities; `None` for all software ones.
|
||||
backend: Option<Arc<dyn LocalKeyBackend>>,
|
||||
}
|
||||
|
||||
impl Clone for Identity {
|
||||
/// Software identities clone their key material; hardware-backed identities
|
||||
/// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy.
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
prv: self
|
||||
.prv
|
||||
.as_ref()
|
||||
.map(|k| X25519PrivateKey::from_bytes(&k.to_bytes())),
|
||||
sig_prv: self
|
||||
.sig_prv
|
||||
.as_ref()
|
||||
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes())),
|
||||
pub_key: self.pub_key.clone(),
|
||||
sig_pub: self.sig_pub.clone(),
|
||||
hash: self.hash,
|
||||
backend: self.backend.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Identity {
|
||||
@@ -67,6 +105,7 @@ impl Identity {
|
||||
pub_key,
|
||||
sig_pub,
|
||||
hash,
|
||||
backend: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +130,7 @@ impl Identity {
|
||||
pub_key,
|
||||
sig_pub,
|
||||
hash,
|
||||
backend: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -114,9 +154,22 @@ impl Identity {
|
||||
pub_key,
|
||||
sig_pub,
|
||||
hash,
|
||||
backend: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Construct an identity whose private operations are served by `backend`
|
||||
/// (e.g. a hardware token). Public-key-only in memory; `sign` and `decrypt`
|
||||
/// delegate to the backend. Wire-identical to a software identity.
|
||||
pub fn from_backend(
|
||||
public_key: &[u8],
|
||||
backend: Arc<dyn LocalKeyBackend>,
|
||||
) -> Result<Self, IdentityError> {
|
||||
let mut id = Self::from_public_key(public_key)?;
|
||||
id.backend = Some(backend);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Load an identity from file, accepting either the current msgpack envelope
|
||||
/// or a legacy raw 64-byte private key.
|
||||
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
|
||||
@@ -167,15 +220,32 @@ impl Identity {
|
||||
self.prv.is_some() && self.sig_prv.is_some()
|
||||
}
|
||||
|
||||
/// True if private operations are served by a hardware backend.
|
||||
pub fn has_backend(&self) -> bool {
|
||||
self.backend.is_some()
|
||||
}
|
||||
|
||||
/// Re-lock the hardware backend (drop its cached authentication). No-op for
|
||||
/// software identities. The next private operation will fail until re-auth.
|
||||
pub fn lock(&self) {
|
||||
if let Some(b) = self.backend.as_ref() {
|
||||
b.lock();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_signing_key(&self) -> Option<Ed25519PrivateKey> {
|
||||
self.sig_prv
|
||||
.as_ref()
|
||||
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes()))
|
||||
}
|
||||
|
||||
/// Sign `message` with the Ed25519 key; `None` if this is a public-only identity.
|
||||
/// Sign `message` with the Ed25519 key, delegating to the hardware backend
|
||||
/// when the in-memory key is absent; `None` if neither is available.
|
||||
pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> {
|
||||
self.sig_prv.as_ref().map(|key| key.sign(message))
|
||||
match self.sig_prv.as_ref() {
|
||||
Some(key) => Some(key.sign(message)),
|
||||
None => self.backend.as_ref().and_then(|b| b.sign_ed25519(message)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
|
||||
@@ -251,8 +321,16 @@ impl Identity {
|
||||
return Err(IdentityError::DecryptionFailed);
|
||||
}
|
||||
|
||||
let prv = self.prv.as_ref().ok_or(IdentityError::DecryptionFailed)?;
|
||||
let mut shared = prv.exchange(&peer_pub);
|
||||
// Identity-key ECDH: in-memory key if present, else the hardware backend.
|
||||
let mut shared: [u8; 32] = if let Some(prv) = self.prv.as_ref() {
|
||||
prv.exchange(&peer_pub)
|
||||
} else if let Some(backend) = self.backend.as_ref() {
|
||||
backend
|
||||
.ecdh(&peer_pub_bytes)
|
||||
.ok_or(IdentityError::DecryptionFailed)?
|
||||
} else {
|
||||
return Err(IdentityError::DecryptionFailed);
|
||||
};
|
||||
let derived_result =
|
||||
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
|
||||
shared.zeroize();
|
||||
@@ -483,4 +561,55 @@ mod tests {
|
||||
let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap();
|
||||
assert!(pub_id.prove(b"test", true).is_err());
|
||||
}
|
||||
|
||||
// A software-keyed backend, standing in for a hardware token in tests.
|
||||
struct SoftwareBackend {
|
||||
sig: rns_crypto::ed25519::Ed25519PrivateKey,
|
||||
x: rns_crypto::x25519::X25519PrivateKey,
|
||||
}
|
||||
impl LocalKeyBackend for SoftwareBackend {
|
||||
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
|
||||
Some(self.sig.sign(message))
|
||||
}
|
||||
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
|
||||
let peer = rns_crypto::x25519::X25519PublicKey::from_bytes(peer_pub);
|
||||
Some(self.x.exchange(&peer))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backend_identity_is_wire_identical() {
|
||||
use std::sync::Arc;
|
||||
|
||||
// Build a backend from a software identity's keys, then a separate
|
||||
// backend-driven identity over the same public key.
|
||||
let sw = Identity::new();
|
||||
let prv = sw.get_private_key().unwrap();
|
||||
let mut x_bytes = [0u8; 32];
|
||||
x_bytes.copy_from_slice(&prv[..32]);
|
||||
let mut ed_bytes = [0u8; 32];
|
||||
ed_bytes.copy_from_slice(&prv[32..]);
|
||||
let backend = Arc::new(SoftwareBackend {
|
||||
sig: rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&ed_bytes),
|
||||
x: rns_crypto::x25519::X25519PrivateKey::from_bytes(&x_bytes),
|
||||
});
|
||||
|
||||
let hw = Identity::from_backend(&sw.get_public_key(), backend).unwrap();
|
||||
|
||||
// Same identity, but no extractable in-memory key.
|
||||
assert_eq!(hw.hash, sw.hash);
|
||||
assert!(!hw.has_private_key());
|
||||
assert!(hw.get_private_key().is_none());
|
||||
|
||||
// sign() delegates and is byte-identical (Ed25519 is deterministic).
|
||||
let msg = b"hardware parity";
|
||||
assert_eq!(hw.sign(msg), sw.sign(msg));
|
||||
assert!(hw.verify(msg, &hw.sign(msg).unwrap()));
|
||||
|
||||
// decrypt() delegates the ECDH to the backend; round-trips, and the
|
||||
// software identity decrypts the same ciphertext (identical key material).
|
||||
let ct = hw.encrypt(b"secret payload", None).unwrap();
|
||||
assert_eq!(hw.decrypt(&ct, None, false).unwrap(), b"secret payload");
|
||||
assert_eq!(sw.decrypt(&ct, None, false).unwrap(), b"secret payload");
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,8 @@ use std::path::Path;
|
||||
/// Write `data` to `path` via `<path>.tmp` + `rename`, fsyncing first.
|
||||
///
|
||||
/// On Unix the temp file is created with mode `0600` so that key material is
|
||||
/// not world-readable even during the write.
|
||||
/// not world-readable even during the write. After the rename the parent
|
||||
/// directory is fsynced best-effort so the rename itself survives power loss.
|
||||
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
let tmp_path = path.with_extension("tmp");
|
||||
|
||||
@@ -28,6 +29,14 @@ pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
}
|
||||
|
||||
fs::rename(&tmp_path, path)?;
|
||||
|
||||
#[cfg(unix)]
|
||||
if let Some(dir) = path.parent() {
|
||||
if let Ok(d) = fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -233,6 +233,7 @@ impl Default for RatchetRing {
|
||||
|
||||
/// Ratchet public key learned from a remote destination's announce, with
|
||||
/// the local receive time used for expiry.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ReceivedRatchet {
|
||||
pub ratchet_pub: [u8; 32],
|
||||
pub received_at: f64,
|
||||
|
||||
@@ -8,7 +8,8 @@ license.workspace = true
|
||||
[features]
|
||||
default = []
|
||||
serial = ["dep:serialport"]
|
||||
ble = ["dep:btleplug", "dep:futures", "dep:uuid"]
|
||||
rnode-tcp = []
|
||||
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
|
||||
ble_peer = ["ble"]
|
||||
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
|
||||
# and reverse-peering probes slow down in the background; BLE peer scan
|
||||
@@ -26,7 +27,7 @@ tracing = { workspace = true }
|
||||
socket2 = { workspace = true }
|
||||
if-addrs = { workspace = true }
|
||||
serialport = { workspace = true, optional = true }
|
||||
btleplug = { workspace = true, optional = true }
|
||||
btleplug = { version = "0.11", optional = true }
|
||||
futures = { version = "0.3", optional = true }
|
||||
uuid = { version = "1", optional = true }
|
||||
rand = { workspace = true }
|
||||
@@ -48,6 +49,10 @@ objc2-core-bluetooth = "0.2"
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
# Keepalive-tuning tests read socket options back via getsockopt.
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
# Android JNI (BLE Peripheral, USB Serial)
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
jni = "0.19"
|
||||
@@ -56,7 +61,7 @@ jni = "0.19"
|
||||
# Linux-only target dep so non-Linux builds don't pull in BlueZ. The
|
||||
# linux_peripheral module is gated by both `ble` feature and target_os.
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
bluer = { version = "0.17", features = ["bluetoothd"] }
|
||||
bluer = { version = "0.17", features = ["bluetoothd"], optional = true }
|
||||
|
||||
# Windows BLE Peripheral via WinRT GattServiceProvider (MSIX-packaged apps).
|
||||
# Windows-only target dep so cross-platform builds don't pull in WinRT
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -27,6 +28,60 @@ pub const KNOWN_VIDS: &[(u16, &str)] = &[
|
||||
(0x1915, "Nordic Semiconductor NRF52840"),
|
||||
];
|
||||
|
||||
type AndroidUsbRNodeStopRegistry = Mutex<HashMap<InterfaceId, mpsc::Sender<()>>>;
|
||||
|
||||
fn android_usb_rnode_stop_registry() -> &'static AndroidUsbRNodeStopRegistry {
|
||||
static REGISTRY: OnceLock<AndroidUsbRNodeStopRegistry> = OnceLock::new();
|
||||
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
struct AndroidUsbRNodeStopRegistryGuard {
|
||||
id: InterfaceId,
|
||||
}
|
||||
|
||||
impl Drop for AndroidUsbRNodeStopRegistryGuard {
|
||||
fn drop(&mut self) {
|
||||
android_usb_rnode_stop_registry()
|
||||
.lock()
|
||||
.expect("android_usb_rnode_stop_registry mutex poisoned")
|
||||
.remove(&self.id);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_android_usb_rnode_stop(
|
||||
id: InterfaceId,
|
||||
stop_tx: mpsc::Sender<()>,
|
||||
) -> AndroidUsbRNodeStopRegistryGuard {
|
||||
android_usb_rnode_stop_registry()
|
||||
.lock()
|
||||
.expect("android_usb_rnode_stop_registry mutex poisoned")
|
||||
.insert(id, stop_tx);
|
||||
AndroidUsbRNodeStopRegistryGuard { id }
|
||||
}
|
||||
|
||||
/// Ask an Android USB RNode interface to send upstream's detach sequence before
|
||||
/// runtime teardown aborts the task. Idempotent; unknown ids are ignored.
|
||||
pub fn stop_android_usb_rnode_interface(id: InterfaceId) {
|
||||
let stop_tx = android_usb_rnode_stop_registry()
|
||||
.lock()
|
||||
.expect("android_usb_rnode_stop_registry mutex poisoned")
|
||||
.get(&id)
|
||||
.cloned();
|
||||
let Some(stop_tx) = stop_tx else {
|
||||
tracing::debug!(id, "Android USB RNode stop requested for unknown interface");
|
||||
return;
|
||||
};
|
||||
match stop_tx.try_send(()) {
|
||||
Ok(()) => tracing::info!(id, "Android USB RNode stop signal sent"),
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
tracing::debug!(id, "Android USB RNode stop signal already pending")
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||
tracing::debug!(id, "Android USB RNode stop signal receiver already closed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct UsbSerialDevice {
|
||||
pub device_name: String,
|
||||
@@ -48,6 +103,12 @@ pub struct AndroidUsbConfig {
|
||||
pub coding_rate: u8,
|
||||
pub tx_power: u8,
|
||||
pub mode: InterfaceMode,
|
||||
/// Gate each TX on the radio's CMD_READY. Python default: off.
|
||||
pub flow_control: bool,
|
||||
/// Short-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
|
||||
pub st_alock: Option<f32>,
|
||||
/// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
|
||||
pub lt_alock: Option<f32>,
|
||||
}
|
||||
|
||||
impl AndroidUsbConfig {
|
||||
@@ -62,13 +123,15 @@ impl AndroidUsbConfig {
|
||||
coding_rate: 6,
|
||||
tx_power: 17,
|
||||
mode: InterfaceMode::Full,
|
||||
flow_control: false,
|
||||
st_alock: None,
|
||||
lt_alock: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use jni::JavaVM;
|
||||
use jni::objects::{GlobalRef, JObject, JValue};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
|
||||
static APP_CONTEXT: OnceLock<GlobalRef> = OnceLock::new();
|
||||
@@ -453,7 +516,7 @@ async fn open_usb_serial(
|
||||
|
||||
let cw = connected.clone();
|
||||
let vm = match JAVA_VM.get() {
|
||||
Some(v) => v.clone(),
|
||||
Some(v) => v,
|
||||
None => return Err("JavaVM not initialized for USB write loop".into()),
|
||||
};
|
||||
let cr_w = conn_ref.clone();
|
||||
@@ -487,7 +550,7 @@ async fn open_usb_serial(
|
||||
|
||||
let cr = connected.clone();
|
||||
let vm2 = match JAVA_VM.get() {
|
||||
Some(v) => v.clone(),
|
||||
Some(v) => v,
|
||||
None => return Err("JavaVM not initialized for USB read loop".into()),
|
||||
};
|
||||
tokio::task::spawn_blocking(move || {
|
||||
@@ -561,6 +624,9 @@ pub async fn spawn_android_usb_rnode_interface(
|
||||
rnode_cfg.coding_rate = config.coding_rate;
|
||||
rnode_cfg.tx_power = config.tx_power;
|
||||
rnode_cfg.mode = config.mode;
|
||||
rnode_cfg.flow_control = config.flow_control;
|
||||
rnode_cfg.st_alock = config.st_alock;
|
||||
rnode_cfg.lt_alock = config.lt_alock;
|
||||
let init_bytes = rnode::build_init_sequence(&rnode_cfg);
|
||||
if raw_write_tx.send(init_bytes).await.is_err() {
|
||||
return Err(InterfaceError::SendFailed(
|
||||
@@ -572,17 +638,32 @@ pub async fn spawn_android_usb_rnode_interface(
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
|
||||
let (tx, mut app_rx) = mpsc::channel::<Bytes>(64);
|
||||
let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1);
|
||||
let stop_guard = register_android_usb_rnode_stop(id, stop_tx);
|
||||
|
||||
let txb = shared_txb.clone();
|
||||
let wtx = raw_write_tx.clone();
|
||||
let write_name = name.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(payload) = app_rx.recv().await {
|
||||
let frame = kiss::frame(&payload);
|
||||
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
||||
if wtx.send(frame).await.is_err() {
|
||||
tracing::warn!(name = %write_name, "USB write channel closed");
|
||||
break;
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(payload) = app_rx.recv() => {
|
||||
let frame = kiss::frame(&payload);
|
||||
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
||||
if wtx.send(frame).await.is_err() {
|
||||
tracing::warn!(name = %write_name, "USB write channel closed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(_) = stop_rx.recv() => {
|
||||
if wtx.send(rnode::build_detach_sequence()).await.is_err() {
|
||||
tracing::warn!(name = %write_name, "USB detach sequence could not be queued");
|
||||
} else {
|
||||
tracing::info!(name = %write_name, "USB detach sequence queued");
|
||||
}
|
||||
break;
|
||||
}
|
||||
else => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -593,6 +674,7 @@ pub async fn spawn_android_usb_rnode_interface(
|
||||
let rxb = shared_rxb.clone();
|
||||
let online = connected.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let _stop_guard = stop_guard;
|
||||
let mut deframer = kiss::KissDeframer::new();
|
||||
let mut last_rssi: Option<f32> = None;
|
||||
let mut last_snr: Option<f32> = None;
|
||||
@@ -625,6 +707,7 @@ pub async fn spawn_android_usb_rnode_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode: config.mode,
|
||||
direction: InterfaceDirection {
|
||||
|
||||
@@ -237,14 +237,38 @@ impl Default for AutoInterfaceConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct PeerKey {
|
||||
ip: Ipv6Addr,
|
||||
scope_id: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum PeerScopeSource {
|
||||
Received,
|
||||
LocalCandidate,
|
||||
UnscopedNonLinkLocal,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PeerScopeCandidate {
|
||||
ifname: String,
|
||||
scope_id: u32,
|
||||
source: PeerScopeSource,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Peer {
|
||||
ip: Ipv6Addr,
|
||||
ifname: String,
|
||||
scope_id: u32,
|
||||
scope_source: PeerScopeSource,
|
||||
addr: SocketAddrV6,
|
||||
last_seen: Instant,
|
||||
last_reverse: Instant,
|
||||
}
|
||||
|
||||
type PeerTable = Arc<Mutex<HashMap<Ipv6Addr, Peer>>>;
|
||||
type PeerTable = Arc<Mutex<HashMap<PeerKey, Peer>>>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct DeduplicateEntry {
|
||||
@@ -334,6 +358,111 @@ fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr {
|
||||
)
|
||||
}
|
||||
|
||||
fn is_link_local_v6(addr: Ipv6Addr) -> bool {
|
||||
(addr.segments()[0] & 0xffc0) == 0xfe80
|
||||
}
|
||||
|
||||
fn peer_scope_candidates(
|
||||
peer_ip: Ipv6Addr,
|
||||
received_scope: u32,
|
||||
link_locals: &[(String, Ipv6Addr, u32)],
|
||||
) -> Vec<PeerScopeCandidate> {
|
||||
// Python Reticulum associates AutoInterface peers with the receiving
|
||||
// ifname and sends to fe80::peer%ifindex. Some platforms report scope 0
|
||||
// from a wildcard-bound socket, so expand link-local peers to scoped local
|
||||
// candidates instead of storing an unusable fe80::peer%0 address.
|
||||
if received_scope != 0 {
|
||||
let ifname = link_locals
|
||||
.iter()
|
||||
.find(|(_, _, scope_id)| *scope_id == received_scope)
|
||||
.map(|(name, _, _)| name.clone())
|
||||
.unwrap_or_else(|| format!("ifindex:{received_scope}"));
|
||||
return vec![PeerScopeCandidate {
|
||||
ifname,
|
||||
scope_id: received_scope,
|
||||
source: PeerScopeSource::Received,
|
||||
}];
|
||||
}
|
||||
|
||||
if !is_link_local_v6(peer_ip) {
|
||||
return vec![PeerScopeCandidate {
|
||||
ifname: String::new(),
|
||||
scope_id: 0,
|
||||
source: PeerScopeSource::UnscopedNonLinkLocal,
|
||||
}];
|
||||
}
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
for (ifname, _, scope_id) in link_locals {
|
||||
if *scope_id == 0
|
||||
|| candidates
|
||||
.iter()
|
||||
.any(|c: &PeerScopeCandidate| c.scope_id == *scope_id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
candidates.push(PeerScopeCandidate {
|
||||
ifname: ifname.clone(),
|
||||
scope_id: *scope_id,
|
||||
source: PeerScopeSource::LocalCandidate,
|
||||
});
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
fn upsert_peer_candidates(
|
||||
table: &mut HashMap<PeerKey, Peer>,
|
||||
peer_ip: Ipv6Addr,
|
||||
data_port: u16,
|
||||
received_scope: u32,
|
||||
link_locals: &[(String, Ipv6Addr, u32)],
|
||||
now: Instant,
|
||||
source: &'static str,
|
||||
) -> usize {
|
||||
let candidates = peer_scope_candidates(peer_ip, received_scope, link_locals);
|
||||
if candidates.is_empty() {
|
||||
tracing::warn!(
|
||||
peer = %peer_ip,
|
||||
received_scope,
|
||||
local_candidates = link_locals.len(),
|
||||
source,
|
||||
"auto: discovered link-local peer but no usable scope candidates are available"
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
let mut inserted = 0usize;
|
||||
for candidate in candidates {
|
||||
let key = PeerKey {
|
||||
ip: peer_ip,
|
||||
scope_id: candidate.scope_id,
|
||||
};
|
||||
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, candidate.scope_id);
|
||||
table
|
||||
.entry(key)
|
||||
.and_modify(|p| {
|
||||
p.ifname = candidate.ifname.clone();
|
||||
p.scope_id = candidate.scope_id;
|
||||
p.scope_source = candidate.source;
|
||||
p.addr = data_addr;
|
||||
p.last_seen = now;
|
||||
})
|
||||
.or_insert_with(|| {
|
||||
inserted += 1;
|
||||
Peer {
|
||||
ip: peer_ip,
|
||||
ifname: candidate.ifname,
|
||||
scope_id: candidate.scope_id,
|
||||
scope_source: candidate.source,
|
||||
addr: data_addr,
|
||||
last_seen: now,
|
||||
last_reverse: now,
|
||||
}
|
||||
});
|
||||
}
|
||||
inserted
|
||||
}
|
||||
|
||||
/// Derive `ff_T_S_:0:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX` from address-type nibble,
|
||||
/// scope nibble, and bytes 2..14 of `SHA-256(group_id)`.
|
||||
pub fn derive_multicast_address(
|
||||
@@ -779,9 +908,19 @@ fn get_link_local_addrs_android(
|
||||
}
|
||||
|
||||
fn iface_scope_id(iface: &if_addrs::Interface) -> u32 {
|
||||
iface
|
||||
.index
|
||||
.unwrap_or_else(|| iface_name_to_scope_id(&iface.name))
|
||||
if let Some(index) = iface.index {
|
||||
return index;
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let adapter_index = iface_name_to_scope_id(&iface.adapter_name);
|
||||
if adapter_index != 0 {
|
||||
return adapter_index;
|
||||
}
|
||||
}
|
||||
|
||||
iface_name_to_scope_id(&iface.name)
|
||||
}
|
||||
|
||||
/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`.
|
||||
@@ -841,6 +980,11 @@ fn bind_one(port: u16) -> std::io::Result<UdpSocket> {
|
||||
UdpSocket::from_std(sock.into())
|
||||
}
|
||||
|
||||
fn set_multicast_if_v6(sock: &UdpSocket, scope_id: u32) -> std::io::Result<()> {
|
||||
let sock_ref = socket2::SockRef::from(sock);
|
||||
sock_ref.set_multicast_if_v6(scope_id)
|
||||
}
|
||||
|
||||
/// Diagnostic: probe alternate ports to localize bind failures.
|
||||
#[cfg(target_os = "android")]
|
||||
fn probe_alternate_ports(base: u16) {
|
||||
@@ -927,11 +1071,20 @@ pub async fn spawn_auto_interface(
|
||||
tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound");
|
||||
|
||||
for (iface_name, _ll_addr, scope_id) in &initial_link_locals {
|
||||
if let Err(e) = set_multicast_if_v6(disc_sock.as_ref(), *scope_id) {
|
||||
tracing::warn!(
|
||||
iface = %iface_name,
|
||||
scope_id,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"failed to set IPv6 multicast outbound interface"
|
||||
);
|
||||
}
|
||||
if let Err(e) = disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
|
||||
// EPERM/EACCES on Apple is the canonical signal that the
|
||||
// multicast networking entitlement isn't provisioned (e.g. iOS
|
||||
// PermissionDenied covers EPERM/EACCES/Windows ERROR_ACCESS_DENIED.
|
||||
// Surfaced as an event so UIs can show pending Apple approval.
|
||||
// PermissionDenied (EPERM/EACCES, Windows ERROR_ACCESS_DENIED) on
|
||||
// Apple platforms is the canonical signal that the multicast
|
||||
// networking entitlement isn't provisioned. Surfaced as an event
|
||||
// so UIs can show pending Apple approval.
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
tracing::warn!(
|
||||
iface = %iface_name,
|
||||
@@ -1001,16 +1154,38 @@ pub async fn spawn_auto_interface(
|
||||
for (_name, ll_addr, scope_id) in &snapshot {
|
||||
let beacon = make_beacon(&group_id, ll_addr);
|
||||
let dest = SocketAddrV6::new(mcast_group, disc_port, 0, *scope_id);
|
||||
if let Err(e) = set_multicast_if_v6(disc_sock_send.as_ref(), *scope_id) {
|
||||
tracing::warn!(
|
||||
iface = %_name,
|
||||
ll = %ll_addr,
|
||||
scope_id,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"auto: failed to select multicast outbound interface"
|
||||
);
|
||||
}
|
||||
let res = disc_sock_send.send_to(&beacon, dest).await;
|
||||
tracing::debug!(
|
||||
iface = %_name,
|
||||
ll = %ll_addr,
|
||||
scope_id,
|
||||
dst = %dest,
|
||||
hash = %hex32(&beacon),
|
||||
sent = res.is_ok(),
|
||||
"auto-instr beacon TX"
|
||||
);
|
||||
match res {
|
||||
Ok(n) => tracing::debug!(
|
||||
iface = %_name,
|
||||
ll = %ll_addr,
|
||||
scope_id,
|
||||
dst = %dest,
|
||||
hash = %hex32(&beacon),
|
||||
sent_bytes = n,
|
||||
"auto-instr beacon TX"
|
||||
),
|
||||
Err(e) => tracing::warn!(
|
||||
iface = %_name,
|
||||
ll = %ll_addr,
|
||||
scope_id,
|
||||
dst = %dest,
|
||||
hash = %hex32(&beacon),
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"auto: beacon TX failed"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1024,12 +1199,17 @@ pub async fn spawn_auto_interface(
|
||||
let disc_sock_recv = disc_sock.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 256];
|
||||
// Python's read loops swallow exceptions and keep serving; Linux
|
||||
// surfaces transient async errors (ICMP unreachable) via recv_from,
|
||||
// so only sustained failure may kill the loop.
|
||||
let mut consecutive_errors = 0u32;
|
||||
loop {
|
||||
if !online_d.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
match disc_sock_recv.recv_from(&mut buf).await {
|
||||
Ok((n, src)) => {
|
||||
consecutive_errors = 0;
|
||||
if n < 32 {
|
||||
tracing::debug!(src = %src, n, "auto-instr mcast RX too short");
|
||||
continue;
|
||||
@@ -1037,28 +1217,29 @@ pub async fn spawn_auto_interface(
|
||||
if let SocketAddr::V6(src_v6) = src {
|
||||
let peer_ip = *src_v6.ip();
|
||||
// Match source LL against ours — non-empty means self-echo.
|
||||
let snapshot = { disc_link_locals.lock().await.clone() };
|
||||
let self_iface = {
|
||||
let snapshot = disc_link_locals.lock().await;
|
||||
snapshot
|
||||
.iter()
|
||||
.find(|(_, ll, _)| *ll == peer_ip)
|
||||
.map(|(name, _, _)| name.clone())
|
||||
};
|
||||
let is_self = self_iface.is_some();
|
||||
let received_hash = hex32(&buf[..32]);
|
||||
let expected = make_beacon(&auth_group_id, &peer_ip);
|
||||
let expected_hex = hex32(&expected);
|
||||
let match_ok = expected[..] == buf[..32];
|
||||
tracing::debug!(
|
||||
src = %src_v6,
|
||||
scope_id = src_v6.scope_id(),
|
||||
n,
|
||||
is_self,
|
||||
recv_hash = %received_hash,
|
||||
expected_hash = %expected_hex,
|
||||
match_ok,
|
||||
"auto-instr mcast RX"
|
||||
);
|
||||
// Hash hex strings only materialize when debug is on.
|
||||
if tracing::enabled!(tracing::Level::DEBUG) {
|
||||
tracing::debug!(
|
||||
src = %src_v6,
|
||||
scope_id = src_v6.scope_id(),
|
||||
n,
|
||||
is_self,
|
||||
recv_hash = %hex32(&buf[..32]),
|
||||
expected_hash = %hex32(&expected),
|
||||
match_ok,
|
||||
"auto-instr mcast RX"
|
||||
);
|
||||
}
|
||||
if let Some(ifname) = self_iface {
|
||||
// Self-echo: carrier confirmed; record for jobs task.
|
||||
let mut echoes = disc_echoes.lock().await;
|
||||
@@ -1068,26 +1249,36 @@ pub async fn spawn_auto_interface(
|
||||
if !match_ok {
|
||||
continue;
|
||||
}
|
||||
let scope = src_v6.scope_id();
|
||||
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
|
||||
let received_scope = src_v6.scope_id();
|
||||
let now = Instant::now();
|
||||
let mut table = peers_disc.lock().await;
|
||||
table
|
||||
.entry(peer_ip)
|
||||
.and_modify(|p| p.last_seen = now)
|
||||
.or_insert(Peer {
|
||||
addr: data_addr,
|
||||
last_seen: now,
|
||||
last_reverse: now,
|
||||
});
|
||||
tracing::debug!(peer = %peer_ip, "auto: peer discovered/refreshed");
|
||||
let inserted = upsert_peer_candidates(
|
||||
&mut table,
|
||||
peer_ip,
|
||||
data_port,
|
||||
received_scope,
|
||||
&snapshot,
|
||||
now,
|
||||
"multicast",
|
||||
);
|
||||
tracing::debug!(
|
||||
peer = %peer_ip,
|
||||
received_scope,
|
||||
inserted,
|
||||
peer_records = table.len(),
|
||||
"auto: peer discovered/refreshed"
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(src = %src, "auto-instr mcast RX non-v6 source");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "auto discovery recv error");
|
||||
break;
|
||||
consecutive_errors += 1;
|
||||
tracing::warn!(error = %e, consecutive_errors, "auto discovery recv error");
|
||||
if consecutive_errors >= 50 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1099,16 +1290,19 @@ pub async fn spawn_auto_interface(
|
||||
let unicast_group_id = config.group_id.clone();
|
||||
let unicast_link_locals = link_locals.clone();
|
||||
let unicast_disc_port = config.discovery_port + 1;
|
||||
if let Ok(unicast_sock) = UdpSocket::bind(SocketAddrV6::new(
|
||||
Ipv6Addr::UNSPECIFIED,
|
||||
unicast_disc_port,
|
||||
0,
|
||||
0,
|
||||
))
|
||||
.await
|
||||
{
|
||||
let unicast_sock = Arc::new(unicast_sock);
|
||||
|
||||
let unicast_sock = match bind_reusable_udp_v6(unicast_disc_port) {
|
||||
Ok(sock) => Some(Arc::new(sock)),
|
||||
Err(e) => {
|
||||
tracing::debug!(
|
||||
port = unicast_disc_port,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"auto: could not bind unicast discovery port"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(unicast_sock) = unicast_sock {
|
||||
let urecv_sock = unicast_sock.clone();
|
||||
let urecv_peers = peers_unicast.clone();
|
||||
let urecv_online = online_u.clone();
|
||||
@@ -1116,45 +1310,59 @@ pub async fn spawn_auto_interface(
|
||||
let urecv_link_locals = unicast_link_locals.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 256];
|
||||
let mut consecutive_errors = 0u32;
|
||||
loop {
|
||||
if !urecv_online.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
match urecv_sock.recv_from(&mut buf).await {
|
||||
Ok((n, src)) => {
|
||||
consecutive_errors = 0;
|
||||
if n < 32 {
|
||||
continue;
|
||||
}
|
||||
if let SocketAddr::V6(src_v6) = src {
|
||||
let peer_ip = *src_v6.ip();
|
||||
let is_self = {
|
||||
let snapshot = urecv_link_locals.lock().await;
|
||||
snapshot.iter().any(|(_, ll, _)| *ll == peer_ip)
|
||||
};
|
||||
let snapshot = { urecv_link_locals.lock().await.clone() };
|
||||
let is_self = { snapshot.iter().any(|(_, ll, _)| *ll == peer_ip) };
|
||||
if is_self {
|
||||
continue;
|
||||
}
|
||||
if !verify_beacon(&buf[..n], &urecv_group_id, &peer_ip) {
|
||||
continue;
|
||||
}
|
||||
let scope = src_v6.scope_id();
|
||||
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
|
||||
let received_scope = src_v6.scope_id();
|
||||
let now = Instant::now();
|
||||
let mut table = urecv_peers.lock().await;
|
||||
table
|
||||
.entry(peer_ip)
|
||||
.and_modify(|p| p.last_seen = now)
|
||||
.or_insert(Peer {
|
||||
addr: data_addr,
|
||||
last_seen: now,
|
||||
last_reverse: now,
|
||||
});
|
||||
tracing::debug!(peer = %peer_ip, "auto: unicast peer discovered");
|
||||
let inserted = upsert_peer_candidates(
|
||||
&mut table,
|
||||
peer_ip,
|
||||
data_port,
|
||||
received_scope,
|
||||
&snapshot,
|
||||
now,
|
||||
"unicast",
|
||||
);
|
||||
tracing::debug!(
|
||||
peer = %peer_ip,
|
||||
received_scope,
|
||||
inserted,
|
||||
peer_records = table.len(),
|
||||
"auto: unicast peer discovered"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!(error = %e, "auto unicast discovery recv error");
|
||||
break;
|
||||
consecutive_errors += 1;
|
||||
tracing::debug!(
|
||||
error = %e,
|
||||
consecutive_errors,
|
||||
"auto unicast discovery recv error"
|
||||
);
|
||||
if consecutive_errors >= 50 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1193,27 +1401,56 @@ pub async fn spawn_auto_interface(
|
||||
}
|
||||
let snapshot = { rev_link_locals.lock().await.clone() };
|
||||
let now = Instant::now();
|
||||
let mut table = rev_peers.lock().await;
|
||||
for (_ip, peer) in table.iter_mut() {
|
||||
if now.duration_since(peer.last_reverse).as_secs_f64()
|
||||
>= REVERSE_PEERING_INTERVAL
|
||||
{
|
||||
for (_name, ll_addr, scope_id) in &snapshot {
|
||||
let beacon = make_beacon(&rev_group_id, ll_addr);
|
||||
let dest =
|
||||
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
|
||||
let _ = unicast_sock.send_to(&beacon, dest).await;
|
||||
// Snapshot due peers under a short lock; sends happen lock-free
|
||||
// so discovery/data tasks aren't stalled by the fan-out.
|
||||
let due: Vec<(PeerKey, Peer)> = {
|
||||
let table = rev_peers.lock().await;
|
||||
table
|
||||
.iter()
|
||||
.filter(|(_, peer)| {
|
||||
now.duration_since(peer.last_reverse).as_secs_f64()
|
||||
>= REVERSE_PEERING_INTERVAL
|
||||
})
|
||||
.map(|(key, peer)| (*key, peer.clone()))
|
||||
.collect()
|
||||
};
|
||||
for (_, peer) in &due {
|
||||
let mut targets: Vec<_> = snapshot
|
||||
.iter()
|
||||
.filter(|(_, _, scope_id)| peer.scope_id == 0 || *scope_id == peer.scope_id)
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
targets = snapshot.iter().collect();
|
||||
}
|
||||
for (_name, ll_addr, scope_id) in targets {
|
||||
let beacon = make_beacon(&rev_group_id, ll_addr);
|
||||
let dest =
|
||||
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
|
||||
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
|
||||
tracing::debug!(
|
||||
peer = %peer.ip,
|
||||
peer_ifname = %peer.ifname,
|
||||
peer_scope_id = peer.scope_id,
|
||||
local_iface = %_name,
|
||||
local_scope_id = scope_id,
|
||||
dst = %dest,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"auto: reverse peering TX failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !due.is_empty() {
|
||||
let mut table = rev_peers.lock().await;
|
||||
for (key, _) in &due {
|
||||
if let Some(peer) = table.get_mut(key) {
|
||||
peer.last_reverse = now;
|
||||
}
|
||||
peer.last_reverse = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"auto: could not bind unicast discovery port {}",
|
||||
unicast_disc_port
|
||||
);
|
||||
}
|
||||
|
||||
// Periodic jobs: NIC re-enum, peer aging, carrier detection (every PEER_JOB_INTERVAL).
|
||||
@@ -1273,6 +1510,17 @@ pub async fn spawn_auto_interface(
|
||||
);
|
||||
}
|
||||
for (ifname, addr, scope_id) in &added {
|
||||
if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) {
|
||||
tracing::warn!(
|
||||
iface = %jobs_iface_name,
|
||||
nic = %ifname,
|
||||
addr = %addr,
|
||||
scope_id,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"AutoInterface failed to set multicast interface for new NIC"
|
||||
);
|
||||
}
|
||||
match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) {
|
||||
Ok(()) => tracing::info!(
|
||||
iface = %jobs_iface_name,
|
||||
@@ -1357,21 +1605,63 @@ pub async fn spawn_auto_interface(
|
||||
tokio::spawn(async move {
|
||||
while let Some(data) = rx.recv().await {
|
||||
let len = data.len();
|
||||
let prefix = hex_prefix(&data, 16);
|
||||
let table = peers_write.lock().await;
|
||||
let peer_count = table.len();
|
||||
for (_ip, peer) in table.iter() {
|
||||
let res = data_sock_w.send_to(&data, peer.addr).await;
|
||||
// Hex prefix only materializes when debug logging is active; the
|
||||
// error path below recomputes it (errors are rare).
|
||||
let debug_enabled = tracing::enabled!(tracing::Level::DEBUG);
|
||||
let prefix = if debug_enabled {
|
||||
hex_prefix(&data, 16)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
// Snapshot under a short lock so the discovery/jobs tasks are not
|
||||
// blocked while we await per-peer sends.
|
||||
let targets: Vec<Peer> = {
|
||||
let table = peers_write.lock().await;
|
||||
table.values().cloned().collect()
|
||||
};
|
||||
let peer_count = targets.len();
|
||||
if peer_count == 0 && debug_enabled {
|
||||
tracing::debug!(
|
||||
dst = %peer.addr,
|
||||
len,
|
||||
prefix = %prefix,
|
||||
peer_count,
|
||||
sent = res.is_ok(),
|
||||
"auto-instr data TX"
|
||||
"auto-instr data TX skipped: no discovered peers"
|
||||
);
|
||||
if res.is_ok() {
|
||||
task_txb.fetch_add(len as u64, Ordering::Relaxed);
|
||||
}
|
||||
for peer in &targets {
|
||||
let res = data_sock_w.send_to(&data, peer.addr).await;
|
||||
match res {
|
||||
Ok(n) => {
|
||||
if debug_enabled {
|
||||
tracing::debug!(
|
||||
peer = %peer.ip,
|
||||
ifname = %peer.ifname,
|
||||
scope_id = peer.scope_id,
|
||||
scope_source = ?peer.scope_source,
|
||||
dst = %peer.addr,
|
||||
len,
|
||||
sent_bytes = n,
|
||||
prefix = %prefix,
|
||||
peer_count,
|
||||
"auto-instr data TX"
|
||||
);
|
||||
}
|
||||
task_txb.fetch_add(len as u64, Ordering::Relaxed);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
peer = %peer.ip,
|
||||
ifname = %peer.ifname,
|
||||
scope_id = peer.scope_id,
|
||||
scope_source = ?peer.scope_source,
|
||||
dst = %peer.addr,
|
||||
len,
|
||||
prefix = %hex_prefix(&data, 16),
|
||||
peer_count,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"auto: data TX failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1382,9 +1672,11 @@ pub async fn spawn_auto_interface(
|
||||
let dedup = Arc::new(Mutex::new(MultiIfDedup::new()));
|
||||
let read_task = tokio::spawn(async move {
|
||||
let mut buf = [0u8; 2048];
|
||||
let mut consecutive_errors = 0u32;
|
||||
loop {
|
||||
match data_sock.recv_from(&mut buf).await {
|
||||
Ok((n, _src)) => {
|
||||
consecutive_errors = 0;
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
@@ -1415,8 +1707,12 @@ pub async fn spawn_auto_interface(
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "auto data recv error");
|
||||
break;
|
||||
consecutive_errors += 1;
|
||||
tracing::warn!(error = %e, consecutive_errors, "auto data recv error");
|
||||
if consecutive_errors >= 50 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1427,6 +1723,7 @@ pub async fn spawn_auto_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -1559,6 +1856,83 @@ mod tests {
|
||||
assert!(!verify_beacon(&beacon[..16], "reticulum", &addr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_scope_candidates_preserves_received_scope() {
|
||||
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
|
||||
let locals = vec![
|
||||
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
|
||||
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
|
||||
];
|
||||
|
||||
let candidates = peer_scope_candidates(peer, 22, &locals);
|
||||
|
||||
assert_eq!(candidates.len(), 1);
|
||||
assert_eq!(candidates[0].ifname, "eth0");
|
||||
assert_eq!(candidates[0].scope_id, 22);
|
||||
assert_eq!(candidates[0].source, PeerScopeSource::Received);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_scope_candidates_expands_zero_scope_for_link_local() {
|
||||
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
|
||||
let locals = vec![
|
||||
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
|
||||
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
|
||||
("duplicate".to_string(), Ipv6Addr::LOCALHOST, 22),
|
||||
];
|
||||
|
||||
let candidates = peer_scope_candidates(peer, 0, &locals);
|
||||
|
||||
assert_eq!(candidates.len(), 2);
|
||||
assert_eq!(candidates[0].ifname, "en0");
|
||||
assert_eq!(candidates[0].scope_id, 11);
|
||||
assert_eq!(candidates[0].source, PeerScopeSource::LocalCandidate);
|
||||
assert_eq!(candidates[1].ifname, "eth0");
|
||||
assert_eq!(candidates[1].scope_id, 22);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_peer_candidates_keys_same_ip_by_scope() {
|
||||
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
|
||||
let locals = vec![
|
||||
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
|
||||
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
|
||||
];
|
||||
let mut table = HashMap::new();
|
||||
|
||||
let inserted = upsert_peer_candidates(
|
||||
&mut table,
|
||||
peer,
|
||||
DATA_PORT,
|
||||
0,
|
||||
&locals,
|
||||
Instant::now(),
|
||||
"test",
|
||||
);
|
||||
|
||||
assert_eq!(inserted, 2);
|
||||
assert_eq!(table.len(), 2);
|
||||
assert!(table.contains_key(&PeerKey {
|
||||
ip: peer,
|
||||
scope_id: 11,
|
||||
}));
|
||||
assert!(table.contains_key(&PeerKey {
|
||||
ip: peer,
|
||||
scope_id: 22,
|
||||
}));
|
||||
assert_eq!(
|
||||
table
|
||||
.get(&PeerKey {
|
||||
ip: peer,
|
||||
scope_id: 11,
|
||||
})
|
||||
.unwrap()
|
||||
.addr
|
||||
.scope_id(),
|
||||
11
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_id_prefers_enumerated_interface_index() {
|
||||
let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
|
||||
@@ -1566,6 +1940,29 @@ mod tests {
|
||||
assert_eq!(iface_scope_id(&iface), 1234);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn if_addrs_link_local_feature_is_enabled() {
|
||||
let proc_addrs = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default();
|
||||
let host_has_link_local = proc_addrs.lines().any(|line| {
|
||||
line.split_whitespace()
|
||||
.nth(3)
|
||||
.is_some_and(|scope| scope.eq_ignore_ascii_case("20"))
|
||||
});
|
||||
if !host_has_link_local {
|
||||
return;
|
||||
}
|
||||
|
||||
let addrs = if_addrs::get_if_addrs().expect("list network interfaces");
|
||||
assert!(
|
||||
addrs.iter().any(|iface| {
|
||||
matches!(&iface.addr, if_addrs::IfAddr::V6(addr) if addr.is_link_local())
|
||||
}),
|
||||
"Linux has link-local IPv6 addresses in /proc/net/if_inet6, but if-addrs returned none; \
|
||||
keep the workspace if-addrs dependency feature `link-local` enabled"
|
||||
);
|
||||
}
|
||||
|
||||
fn test_interface(name: &str, ip: Ipv6Addr, index: Option<u32>) -> if_addrs::Interface {
|
||||
let addr = if_addrs::IfAddr::V6(if_addrs::Ifv6Addr {
|
||||
ip,
|
||||
|
||||
@@ -56,6 +56,10 @@ pub struct AX25KISSConfig {
|
||||
/// Honour CMD_READY from TNC.
|
||||
pub flow_control: bool,
|
||||
pub mode: InterfaceMode,
|
||||
/// Serial line params in Python config form (converted at open).
|
||||
pub data_bits: u8,
|
||||
pub parity: String,
|
||||
pub stop_bits: u8,
|
||||
}
|
||||
|
||||
impl AX25KISSConfig {
|
||||
@@ -74,6 +78,9 @@ impl AX25KISSConfig {
|
||||
slottime: 20,
|
||||
flow_control: false,
|
||||
mode: InterfaceMode::Full,
|
||||
data_bits: 8,
|
||||
parity: "N".to_string(),
|
||||
stop_bits: 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,10 +239,12 @@ pub async fn spawn_ax25kiss_interface(
|
||||
crate::traits::InterfaceError::SendFailed(format!("ax25kiss config: {}", e))
|
||||
})?;
|
||||
|
||||
let (data_bits, parity, stop_bits) =
|
||||
crate::serial::serial_params_from(config.data_bits, &config.parity, config.stop_bits);
|
||||
let port = serialport::new(&config.port, config.baud_rate)
|
||||
.data_bits(serialport::DataBits::Eight)
|
||||
.parity(serialport::Parity::None)
|
||||
.stop_bits(serialport::StopBits::One)
|
||||
.data_bits(data_bits)
|
||||
.parity(parity)
|
||||
.stop_bits(stop_bits)
|
||||
.timeout(Duration::from_millis(AX25_READ_TIMEOUT_MS))
|
||||
.open()
|
||||
.map_err(|e| {
|
||||
@@ -311,25 +320,13 @@ pub async fn spawn_ax25kiss_interface(
|
||||
ready_w.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
let online_ref = online_w.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Write;
|
||||
port_w.write_all(&framed)?;
|
||||
port_w.flush()?;
|
||||
Ok::<_, std::io::Error>(port_w)
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(Ok(p)) => {
|
||||
match crate::serial_io::blocking_write_all(port_w, framed).await {
|
||||
Ok(p) => {
|
||||
port_w = p;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(error = %e, "AX.25 KISS write error");
|
||||
online_ref.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "AX.25 KISS write task panicked");
|
||||
tracing::warn!(error = %e, "AX.25 KISS write error");
|
||||
online_w.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -348,18 +345,8 @@ pub async fn spawn_ax25kiss_interface(
|
||||
if !online_r.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Read;
|
||||
match port_r.read(&mut buf) {
|
||||
Ok(n) => Ok((port_r, buf, n)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
|
||||
Err(e) => Err((port_r, e)),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(Ok((p, b, n))) => {
|
||||
match crate::serial_io::poll_read(port_r, buf).await {
|
||||
Ok((p, b, n)) => {
|
||||
port_r = p;
|
||||
buf = b;
|
||||
if n > 0 {
|
||||
@@ -395,13 +382,8 @@ pub async fn spawn_ax25kiss_interface(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err((_p, e))) => {
|
||||
tracing::warn!(error = %e, "AX.25 KISS read error");
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "AX.25 KISS read task panicked");
|
||||
tracing::warn!(error = %e, "AX.25 KISS read error");
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
@@ -411,6 +393,7 @@ pub async fn spawn_ax25kiss_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
|
||||
@@ -291,6 +291,7 @@ pub async fn spawn_backbone_server(
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: client_id,
|
||||
parent_id: Some(id),
|
||||
name: client_name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -323,6 +324,7 @@ pub async fn spawn_backbone_server(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -490,6 +492,7 @@ pub async fn spawn_backbone_client(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
|
||||
+1577
-580
File diff suppressed because it is too large.
Load diff
@@ -46,9 +46,12 @@ const RECONNECT_WAIT_MAX: u64 = 120;
|
||||
/// `None` retries forever; teardown goes via `stop_ble_rnode_interface`.
|
||||
const MAX_RECONNECT_TRIES: Option<usize> = None;
|
||||
const SCAN_TIMEOUT: u64 = 3;
|
||||
const CONNECT_TIMEOUT: u64 = 5;
|
||||
/// Bounds disable-while-offline teardown latency to ~1s.
|
||||
const RUNNING_POLL: Duration = Duration::from_secs(1);
|
||||
#[cfg(target_os = "linux")]
|
||||
const RNODE_POST_BOND_SETTLE: Duration = Duration::from_millis(2600);
|
||||
const RNODE_NATIVE_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
const RNODE_NATIVE_HANDSHAKE_PROBE: Duration = Duration::from_millis(650);
|
||||
|
||||
/// `stop_ble_rnode_interface` flips false; the read_task removes the entry
|
||||
/// on its way out.
|
||||
@@ -117,38 +120,77 @@ async fn wait_or_shutdown(total: Duration, flag: &AtomicBool) -> bool {
|
||||
!flag.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// RNode can pack multiple frames in one read, so use the raw deframer for
|
||||
/// full-command extended KISS framing.
|
||||
async fn wait_for_rnode_handshake(
|
||||
fn is_rnode_handshake_frame(cmd: u8, frame: &[u8]) -> bool {
|
||||
(cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP))
|
||||
|| (cmd == rnode::CMD_FW_VERSION && !frame.is_empty())
|
||||
}
|
||||
|
||||
fn is_pairing_transition_error(error: &InterfaceError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
InterfaceError::SendFailed(message) if message.starts_with("BLE pairing in progress:")
|
||||
)
|
||||
}
|
||||
|
||||
/// Android's native bridge can come up immediately after SMP completes, while
|
||||
/// rsCardputer's RNode BLE stack is still settling. Probe detect a few times
|
||||
/// inside one connection attempt so a single dropped early frame does not cost
|
||||
/// a full reconnect backoff.
|
||||
async fn probe_native_rnode_handshake(
|
||||
tcp_read: &mut tokio::net::tcp::OwnedReadHalf,
|
||||
tcp_write: &mut tokio::net::tcp::OwnedWriteHalf,
|
||||
timeout: Duration,
|
||||
probe_interval: Duration,
|
||||
running_task: &AtomicBool,
|
||||
) -> bool {
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
let detect_seq = rnode::build_detect_sequence();
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let mut buf = [0u8; 1024];
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
let mut next_probe = std::time::Instant::now();
|
||||
|
||||
while std::time::Instant::now() < deadline {
|
||||
if !running_task.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
|
||||
let read = tokio::time::timeout(remaining.min(RUNNING_POLL), tcp_read.read(&mut buf)).await;
|
||||
|
||||
let now = std::time::Instant::now();
|
||||
if now >= next_probe {
|
||||
if let Err(e) = tcp_write.write_all(&detect_seq).await {
|
||||
tracing::warn!(error = %e, "BLE RNode native detect probe write failed");
|
||||
return false;
|
||||
}
|
||||
let _ = tcp_write.flush().await;
|
||||
next_probe = std::time::Instant::now() + probe_interval;
|
||||
}
|
||||
|
||||
let now = std::time::Instant::now();
|
||||
let read_budget = next_probe
|
||||
.min(deadline)
|
||||
.saturating_duration_since(now)
|
||||
.min(RUNNING_POLL);
|
||||
if read_budget.is_zero() {
|
||||
tokio::task::yield_now().await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let read = tokio::time::timeout(read_budget, tcp_read.read(&mut buf)).await;
|
||||
let n = match read {
|
||||
Ok(Ok(0)) => return false,
|
||||
Ok(Ok(n)) => n,
|
||||
Ok(Err(_)) => return false,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
for (cmd, frame) in deframer.feed(&buf[..n]) {
|
||||
if cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP) {
|
||||
return true;
|
||||
}
|
||||
if cmd == rnode::CMD_FW_VERSION && !frame.is_empty() {
|
||||
if is_rnode_handshake_frame(cmd, &frame) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
@@ -337,6 +379,10 @@ pub struct BleRNodeConfig {
|
||||
pub flow_control: bool,
|
||||
pub st_alock: Option<f32>,
|
||||
pub lt_alock: Option<f32>,
|
||||
/// Station-ID beacon: seconds between IDs, armed by data TX
|
||||
/// (Python `id_interval`/`id_callsign`, callsign max 32 bytes).
|
||||
pub id_interval: Option<u64>,
|
||||
pub id_callsign: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl BleRNodeConfig {
|
||||
@@ -350,13 +396,37 @@ impl BleRNodeConfig {
|
||||
coding_rate: 5,
|
||||
tx_power: 14,
|
||||
mode: InterfaceMode::Full,
|
||||
flow_control: true,
|
||||
// Python RNodeInterface defaults flow_control off.
|
||||
flow_control: false,
|
||||
st_alock: None,
|
||||
lt_alock: None,
|
||||
id_interval: None,
|
||||
id_callsign: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Station-ID beacon parameters, disabled for oversized callsigns
|
||||
/// (Python RNodeInterface.py:333-343).
|
||||
fn beacon_from_config(config: &BleRNodeConfig) -> Option<(Duration, Bytes)> {
|
||||
config
|
||||
.id_interval
|
||||
.zip(config.id_callsign.clone())
|
||||
.filter(|(_, callsign)| {
|
||||
let ok = callsign.len() <= rnode::CALLSIGN_MAX_LEN;
|
||||
if !ok {
|
||||
tracing::error!(
|
||||
name = %config.name,
|
||||
len = callsign.len(),
|
||||
"id_callsign exceeds {} bytes, beaconing disabled",
|
||||
rnode::CALLSIGN_MAX_LEN
|
||||
);
|
||||
}
|
||||
ok
|
||||
})
|
||||
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_adapter() -> Result<Adapter, InterfaceError> {
|
||||
// btleplug's Android global_adapter() panics without init; under
|
||||
// panic=abort that kills the app. Fail loudly so the UI can prompt.
|
||||
@@ -584,6 +654,11 @@ struct BleRNodeConnection {
|
||||
write_mtu: usize,
|
||||
}
|
||||
|
||||
enum NativeBridgeWrite {
|
||||
Packet(Bytes),
|
||||
Raw(Vec<u8>),
|
||||
}
|
||||
|
||||
async fn connect_rnode(
|
||||
adapter: &Adapter,
|
||||
ble_uri: &str,
|
||||
@@ -592,6 +667,18 @@ async fn connect_rnode(
|
||||
let peripheral = resolve_ble_target(adapter, ble_uri).await?;
|
||||
ble_diag(format!("[ble] resolved peripheral id={}", peripheral.id()));
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// BlueZ needs explicit pairing before we open a btleplug GATT
|
||||
// connection. If this creates a fresh bond, RNode intentionally
|
||||
// disconnects shortly afterwards; wait through that before connect().
|
||||
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
|
||||
if linux_trigger_pairing(bluer_addr).await? {
|
||||
ble_diag("[pair][linux] fresh bond complete — waiting for RNode post-pair disconnect");
|
||||
tokio::time::sleep(RNODE_POST_BOND_SETTLE).await;
|
||||
}
|
||||
}
|
||||
|
||||
let mut last_err = String::new();
|
||||
for attempt in 1..=3 {
|
||||
match peripheral.connect().await {
|
||||
@@ -654,21 +741,18 @@ async fn connect_rnode(
|
||||
rx_char.properties, tx_char.properties
|
||||
));
|
||||
|
||||
// SMP must run BEFORE subscribe on desktop / Apple platforms — reading
|
||||
// the encrypted TX char kicks off SMP and drops L2CAP, which kills any
|
||||
// pending subscribe. iOS/macOS share CoreBluetooth; Windows uses WinRT
|
||||
// GATT (auto-prompt on encrypted-char reads). Same trigger shape works
|
||||
// for all three. Linux uses bluer's explicit `Device::pair()` instead —
|
||||
// BlueZ does not auto-prompt SMP from an encrypted-char read.
|
||||
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))]
|
||||
// SMP must run BEFORE subscribe on desktop / Apple / Android platforms —
|
||||
// reading the encrypted TX char kicks off SMP and drops L2CAP, which
|
||||
// kills any pending subscribe. iOS/macOS share CoreBluetooth; Windows
|
||||
// (WinRT) and Android auto-prompt and retry on encrypted-char reads.
|
||||
// Linux used explicit BlueZ pairing before `connect()`, above.
|
||||
#[cfg(any(
|
||||
target_os = "ios",
|
||||
target_os = "macos",
|
||||
target_os = "windows",
|
||||
target_os = "android"
|
||||
))]
|
||||
desktop_trigger_pairing(&peripheral, &tx_char).await?;
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// peripheral.address() returns a BDAddr → MAC string; the helper
|
||||
// also accepts BlueZ D-Bus paths for callers that pass `id()`.
|
||||
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
|
||||
linux_trigger_pairing(bluer_addr).await?;
|
||||
}
|
||||
|
||||
ble_diag("[ble] subscribe TX start");
|
||||
peripheral.subscribe(&tx_char).await.map_err(|e| {
|
||||
@@ -707,7 +791,21 @@ async fn connect_rnode(
|
||||
/// pairing flow when the characteristic requires authentication). Linux
|
||||
/// uses `linux_trigger_pairing` instead — BlueZ requires an explicit
|
||||
/// `Device::pair()` plus a registered Agent for the passkey callback.
|
||||
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))]
|
||||
///
|
||||
/// Android behaves like Windows: a GATT op on an auth-required char makes
|
||||
/// the platform start bonding (system passkey dialog) and retry the op
|
||||
/// internally once bonded. Without this read-first step the subscribe()
|
||||
/// CCCD write fails instantly with insufficient-auth while the bond is
|
||||
/// still running — first add fails, second connect works. If the stack
|
||||
/// errors instead of blocking, the error maps to "BLE pairing in
|
||||
/// progress" and the reconnect loop retries on a 1s cadence until the
|
||||
/// bond lands.
|
||||
#[cfg(any(
|
||||
target_os = "ios",
|
||||
target_os = "macos",
|
||||
target_os = "windows",
|
||||
target_os = "android"
|
||||
))]
|
||||
async fn desktop_trigger_pairing(
|
||||
peripheral: &Peripheral,
|
||||
tx_char: &btleplug::api::Characteristic,
|
||||
@@ -896,7 +994,7 @@ fn parse_linux_ble_address(addr: &str) -> Result<bluer::Address, InterfaceError>
|
||||
/// daemon stops retrying SMP instead of re-invoking `request_passkey`
|
||||
/// every ~60s.
|
||||
#[cfg(target_os = "linux")]
|
||||
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), InterfaceError> {
|
||||
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<bool, InterfaceError> {
|
||||
let overall_start = std::time::Instant::now();
|
||||
|
||||
// Reuse the cached session so the second-and-subsequent attempts skip
|
||||
@@ -927,7 +1025,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
|
||||
"[pair][linux] already bonded with {bluer_addr} (is_paired check {:.2}s)",
|
||||
t_paired.elapsed().as_secs_f32()
|
||||
));
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
ble_diag(format!(
|
||||
"[pair][linux] is_paired=false in {:.2}s",
|
||||
@@ -1049,7 +1147,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
|
||||
}
|
||||
}
|
||||
let _ = linux_pairing_finished_sender().send(LinuxPairingFinished { attempt_id, status });
|
||||
outcome
|
||||
outcome.map(|()| true)
|
||||
}
|
||||
|
||||
/// WithoutResponse is fire-and-forget at the ATT layer; the radio still
|
||||
@@ -1069,6 +1167,14 @@ pub(crate) async fn ble_write(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ble_send_radio_off(conn: &BleRNodeConnection) {
|
||||
let seq = rnode::build_detach_sequence();
|
||||
match ble_write(&conn.peripheral, &conn.rx_char, &seq, conn.write_mtu).await {
|
||||
Ok(()) => ble_diag("[ble] detach sent before disconnect"),
|
||||
Err(e) => ble_diag(format!("[ble] detach before disconnect failed: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-reconnect across drops; resolve_ble_target re-runs every retry so
|
||||
/// iOS RPA rotation heals automatically.
|
||||
pub async fn spawn_ble_rnode_interface(
|
||||
@@ -1105,11 +1211,14 @@ pub async fn spawn_ble_rnode_interface(
|
||||
flow_control: config.flow_control,
|
||||
st_alock: config.st_alock,
|
||||
lt_alock: config.lt_alock,
|
||||
id_interval: config.id_interval,
|
||||
id_callsign: config.id_callsign.clone(),
|
||||
};
|
||||
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let flow_control = config.flow_control;
|
||||
let beacon = beacon_from_config(&config);
|
||||
let ble_uri = config.ble_uri.clone();
|
||||
let log_name = name.clone();
|
||||
let running_task = running.clone();
|
||||
@@ -1154,9 +1263,11 @@ pub async fn spawn_ble_rnode_interface(
|
||||
let conn = match connect_rnode(&adapter, &ble_uri).await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let pairing_transition = is_pairing_transition_error(&e);
|
||||
let retry_wait = if pairing_transition { 1 } else { backoff };
|
||||
tracing::warn!(name = %log_name, error = %e, "BLE RNode connect failed");
|
||||
ble_diag(format!(
|
||||
"[ble] connect_rnode err: {e} — retrying in {backoff}s (attempt {})",
|
||||
"[ble] connect_rnode err: {e} — retrying in {retry_wait}s (attempt {})",
|
||||
tries + 1
|
||||
));
|
||||
if reconnect_try_exhausted(&mut tries) {
|
||||
@@ -1164,10 +1275,14 @@ pub async fn spawn_ble_rnode_interface(
|
||||
ble_diag("[ble] max reconnect tries reached — giving up");
|
||||
return;
|
||||
}
|
||||
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
|
||||
if wait_or_shutdown(Duration::from_secs(retry_wait), &running_task).await {
|
||||
return;
|
||||
}
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
if pairing_transition {
|
||||
backoff = RECONNECT_WAIT;
|
||||
} else {
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -1228,8 +1343,37 @@ pub async fn spawn_ble_rnode_interface(
|
||||
let online_w = online_handle.clone();
|
||||
let ready_w = ready.clone();
|
||||
let txb_w = task_txb.clone();
|
||||
let beacon_w = beacon.clone();
|
||||
let write_handle = tokio::spawn(async move {
|
||||
while let Some(data) = conn_rx.recv().await {
|
||||
// Python first_tx semantics: armed by data TX, cleared when
|
||||
// the callsign beacon goes out (RNodeInterface.py:712-718).
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let data = if let Some((interval, ref callsign)) = beacon_w {
|
||||
match tokio::time::timeout(Duration::from_secs(1), conn_rx.recv()).await {
|
||||
Ok(Some(data)) => data,
|
||||
Ok(None) => break,
|
||||
Err(_) => {
|
||||
if first_tx.is_none_or(|t| t.elapsed() < interval) {
|
||||
continue;
|
||||
}
|
||||
tracing::debug!("BLE RNode transmitting station-ID beacon");
|
||||
callsign.clone()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match conn_rx.recv().await {
|
||||
Some(data) => data,
|
||||
None => break,
|
||||
}
|
||||
};
|
||||
if let Some((_, ref callsign)) = beacon_w {
|
||||
if data == *callsign {
|
||||
first_tx = None;
|
||||
} else if first_tx.is_none() {
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
}
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
if flow_control {
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
@@ -1286,16 +1430,21 @@ pub async fn spawn_ble_rnode_interface(
|
||||
let mut transport_closed = false;
|
||||
|
||||
'read: loop {
|
||||
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
|
||||
if !online_handle.load(Ordering::SeqCst) {
|
||||
break 'read;
|
||||
}
|
||||
if !running_task.load(Ordering::SeqCst) {
|
||||
ble_send_radio_off(&conn).await;
|
||||
break 'read;
|
||||
}
|
||||
|
||||
let notification = tokio::select! {
|
||||
n = notification_stream.next() => n,
|
||||
_ = tokio::time::sleep(Duration::from_secs(CONNECT_TIMEOUT)) => {
|
||||
_ = tokio::time::sleep(RUNNING_POLL) => {
|
||||
// Polling slice — bounds disable-while-connected
|
||||
// teardown latency.
|
||||
if !running_task.load(Ordering::SeqCst) {
|
||||
ble_send_radio_off(&conn).await;
|
||||
break 'read;
|
||||
}
|
||||
if conn.peripheral.is_connected().await.unwrap_or(false) {
|
||||
@@ -1368,6 +1517,7 @@ pub async fn spawn_ble_rnode_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -1425,11 +1575,14 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
flow_control: config.flow_control,
|
||||
st_alock: config.st_alock,
|
||||
lt_alock: config.lt_alock,
|
||||
id_interval: config.id_interval,
|
||||
id_callsign: config.id_callsign.clone(),
|
||||
};
|
||||
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let flow_control = config.flow_control;
|
||||
let beacon = beacon_from_config(&config);
|
||||
let ble_uri = config.ble_uri.clone();
|
||||
let log_name = name.clone();
|
||||
let running = register_running(id);
|
||||
@@ -1471,22 +1624,17 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
|
||||
let (mut tcp_read, mut tcp_write) = stream.into_split();
|
||||
|
||||
let detect_seq = rnode::build_detect_sequence();
|
||||
if let Err(e) = tcp_write.write_all(&detect_seq).await {
|
||||
tracing::warn!(error = %e, "BLE RNode native detect write failed");
|
||||
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
|
||||
return;
|
||||
}
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Without gating on DETECT_RESP + firmware version we'd flag
|
||||
// "online" while the radio is asleep or the BLE-NUS bridge
|
||||
// dropped a frame.
|
||||
let detected =
|
||||
wait_for_rnode_handshake(&mut tcp_read, Duration::from_secs(5), &running_task)
|
||||
.await;
|
||||
let detected = probe_native_rnode_handshake(
|
||||
&mut tcp_read,
|
||||
&mut tcp_write,
|
||||
RNODE_NATIVE_HANDSHAKE_TIMEOUT,
|
||||
RNODE_NATIVE_HANDSHAKE_PROBE,
|
||||
&running_task,
|
||||
)
|
||||
.await;
|
||||
if !detected {
|
||||
tracing::warn!(
|
||||
name = %log_name,
|
||||
@@ -1524,26 +1672,67 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
|
||||
let ready = Arc::new(AtomicBool::new(true));
|
||||
|
||||
let (conn_tx, mut conn_rx) = mpsc::channel::<Bytes>(256);
|
||||
let (conn_tx, mut conn_rx) = mpsc::channel::<NativeBridgeWrite>(256);
|
||||
let conn_tx_for_stop = conn_tx.clone();
|
||||
let online_w = online_handle.clone();
|
||||
let ready_w = ready.clone();
|
||||
let txb_w = task_txb.clone();
|
||||
let beacon_w = beacon.clone();
|
||||
let write_handle = tokio::spawn(async move {
|
||||
while let Some(data) = conn_rx.recv().await {
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
if flow_control {
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let msg = if let Some((interval, ref callsign)) = beacon_w {
|
||||
match tokio::time::timeout(Duration::from_secs(1), conn_rx.recv()).await {
|
||||
Ok(Some(msg)) => msg,
|
||||
Ok(None) => break,
|
||||
Err(_) => {
|
||||
if first_tx.is_none_or(|t| t.elapsed() < interval) {
|
||||
continue;
|
||||
}
|
||||
tracing::debug!(
|
||||
"BLE RNode (native) transmitting station-ID beacon"
|
||||
);
|
||||
NativeBridgeWrite::Packet(callsign.clone())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match conn_rx.recv().await {
|
||||
Some(msg) => msg,
|
||||
None => break,
|
||||
}
|
||||
};
|
||||
match msg {
|
||||
NativeBridgeWrite::Packet(data) => {
|
||||
if let Some((_, ref callsign)) = beacon_w {
|
||||
if data == *callsign {
|
||||
first_tx = None;
|
||||
} else if first_tx.is_none() {
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
}
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
if flow_control {
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let framed = kiss::frame(&data);
|
||||
if let Err(e) = tcp_write.write_all(&framed).await {
|
||||
tracing::warn!(error = %e, "BLE RNode native write error");
|
||||
online_w.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let framed = kiss::frame(&data);
|
||||
if let Err(e) = tcp_write.write_all(&framed).await {
|
||||
tracing::warn!(error = %e, "BLE RNode native write error");
|
||||
online_w.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
NativeBridgeWrite::Raw(data) => {
|
||||
if let Err(e) = tcp_write.write_all(&data).await {
|
||||
tracing::warn!(error = %e, "BLE RNode native raw write error");
|
||||
}
|
||||
let _ = tcp_write.flush().await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1554,7 +1743,7 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
let fwd_handle = tokio::spawn(async move {
|
||||
let mut guard = rx_ref.lock().await;
|
||||
while let Some(data) = guard.recv().await {
|
||||
if conn_tx.send(data).await.is_err() {
|
||||
if conn_tx.send(NativeBridgeWrite::Packet(data)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1567,7 +1756,14 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
let mut transport_closed = false;
|
||||
|
||||
'read: loop {
|
||||
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
|
||||
if !online_handle.load(Ordering::SeqCst) {
|
||||
break 'read;
|
||||
}
|
||||
if !running_task.load(Ordering::SeqCst) {
|
||||
let _ = conn_tx_for_stop
|
||||
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
break 'read;
|
||||
}
|
||||
|
||||
@@ -1589,6 +1785,10 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
// Idle LoRa silence is normal — only break if
|
||||
// shutdown flag cleared.
|
||||
if !running_task.load(Ordering::SeqCst) {
|
||||
let _ = conn_tx_for_stop
|
||||
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
break 'read;
|
||||
}
|
||||
continue;
|
||||
@@ -1648,6 +1848,7 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -1682,7 +1883,10 @@ mod tests {
|
||||
assert_eq!(cfg.spreading_factor, 7);
|
||||
assert_eq!(cfg.coding_rate, 5);
|
||||
assert_eq!(cfg.tx_power, 14);
|
||||
assert!(cfg.flow_control);
|
||||
assert!(
|
||||
!cfg.flow_control,
|
||||
"flow_control defaults off (Python parity)"
|
||||
);
|
||||
assert!(cfg.st_alock.is_none());
|
||||
assert!(cfg.lt_alock.is_none());
|
||||
}
|
||||
@@ -1988,6 +2192,8 @@ mod tests {
|
||||
flow_control: ble_cfg.flow_control,
|
||||
st_alock: ble_cfg.st_alock,
|
||||
lt_alock: ble_cfg.lt_alock,
|
||||
id_interval: ble_cfg.id_interval,
|
||||
id_callsign: ble_cfg.id_callsign.clone(),
|
||||
};
|
||||
let seq = rnode::build_init_sequence(&rnode_cfg);
|
||||
assert!(!seq.is_empty());
|
||||
@@ -2009,12 +2215,13 @@ mod tests {
|
||||
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));
|
||||
// Airtime locks are part of the init sequence, before RADIO_STATE_ON.
|
||||
let seq = rnode::build_init_sequence(&rnode_cfg);
|
||||
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames = deframer.feed(&seq);
|
||||
assert_eq!(frames.len(), 8); // 6 init + 2 airtime
|
||||
assert_eq!(frames.len(), 8); // 5 params + 2 airtime + radio on
|
||||
assert_eq!(frames.last().unwrap().0, rnode::CMD_RADIO_STATE);
|
||||
}
|
||||
|
||||
// ── process_rnode_response tests ──
|
||||
@@ -2055,7 +2262,7 @@ mod tests {
|
||||
fn test_response_rssi_updates() {
|
||||
let mut rssi = None;
|
||||
let mut snr = None;
|
||||
rnode::process_rnode_response(rnode::CMD_STAT_RSSI, &[0xBF], 1, &mut rssi, &mut snr);
|
||||
rnode::process_rnode_response(rnode::CMD_STAT_RSSI, &[92], 1, &mut rssi, &mut snr);
|
||||
assert_eq!(rssi, Some(-65.0));
|
||||
}
|
||||
|
||||
|
||||
+128
-52
@@ -262,6 +262,14 @@ async fn connect_to_sam(sam_host: &str, sam_port: u16) -> Result<TcpStream, SamE
|
||||
let addr = format!("{}:{}", sam_host, sam_port);
|
||||
let stream = TcpStream::connect(&addr).await.map_err(SamError::Io)?;
|
||||
let _ = stream.set_nodelay(true);
|
||||
// Python i2p_tunneled tuning: longer probes/timeout to absorb I2P latency.
|
||||
crate::socket_tuning::set_keepalive_tuned(
|
||||
&stream,
|
||||
std::time::Duration::from_secs(I2P_PROBE_AFTER),
|
||||
std::time::Duration::from_secs(I2P_PROBE_INTERVAL),
|
||||
I2P_PROBES as u32,
|
||||
std::time::Duration::from_secs(I2P_TCP_USER_TIMEOUT as u64),
|
||||
);
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
@@ -344,8 +352,7 @@ pub async fn spawn_i2p_client(
|
||||
let task_txb = shared_txb.clone();
|
||||
|
||||
let read_task = tokio::spawn(async move {
|
||||
let mut tries: usize = 0;
|
||||
let mut backoff = config.reconnect_delay;
|
||||
let mut pacer = ReconnectPacer::new(config.reconnect_delay, config.max_reconnect_tries);
|
||||
|
||||
loop {
|
||||
let session_id = generate_session_id();
|
||||
@@ -358,12 +365,14 @@ pub async fn spawn_i2p_client(
|
||||
error = %e,
|
||||
"I2P client: failed to connect to SAM bridge"
|
||||
);
|
||||
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -377,11 +386,14 @@ pub async fn spawn_i2p_client(
|
||||
error = %e,
|
||||
"I2P client: SAM HELLO failed"
|
||||
);
|
||||
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -407,11 +419,14 @@ pub async fn spawn_i2p_client(
|
||||
error = %e,
|
||||
"I2P client: SESSION CREATE failed"
|
||||
);
|
||||
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -425,11 +440,14 @@ pub async fn spawn_i2p_client(
|
||||
error = %e,
|
||||
"I2P client: failed to open stream connection to SAM"
|
||||
);
|
||||
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -443,11 +461,14 @@ pub async fn spawn_i2p_client(
|
||||
error = %e,
|
||||
"I2P client: SAM HELLO on stream socket failed"
|
||||
);
|
||||
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -465,11 +486,14 @@ pub async fn spawn_i2p_client(
|
||||
error = %e,
|
||||
"I2P client: STREAM CONNECT failed"
|
||||
);
|
||||
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -480,8 +504,7 @@ pub async fn spawn_i2p_client(
|
||||
);
|
||||
|
||||
online_task.store(true, Ordering::SeqCst);
|
||||
tries = 0;
|
||||
backoff = config.reconnect_delay;
|
||||
pacer.reset();
|
||||
|
||||
// BufReader may have prefetched past the handshake; flush its tail first.
|
||||
let buffered = stream_buf_reader.buffer().to_vec();
|
||||
@@ -526,25 +549,25 @@ pub async fn spawn_i2p_client(
|
||||
write_handle.abort();
|
||||
let _ = write_handle.await;
|
||||
|
||||
if let Some(max) = config.max_reconnect_tries {
|
||||
tries += 1;
|
||||
if tries >= max {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
return;
|
||||
}
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tracing::info!(
|
||||
name = %config.name,
|
||||
delay = backoff,
|
||||
delay = pacer.backoff,
|
||||
"I2P client: reconnecting"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -738,6 +761,7 @@ pub async fn spawn_i2p_server(
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: client_id,
|
||||
parent_id: Some(0),
|
||||
name: client_name,
|
||||
mode: config.mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -774,6 +798,7 @@ pub async fn spawn_i2p_server(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id: 0,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -863,13 +888,51 @@ async fn i2p_read_loop(
|
||||
online.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Increments `tries` (when bounded) and returns `true` if the cap was hit.
|
||||
fn check_max_tries(max: &Option<usize>, tries: &mut usize) -> bool {
|
||||
if let Some(limit) = max {
|
||||
*tries += 1;
|
||||
*tries >= *limit
|
||||
} else {
|
||||
false
|
||||
/// Reconnect pacing for the SAM client loop: bounded tries + exponential
|
||||
/// backoff, reset on every successful connect.
|
||||
struct ReconnectPacer {
|
||||
tries: usize,
|
||||
backoff: u64,
|
||||
initial: u64,
|
||||
max_tries: Option<usize>,
|
||||
}
|
||||
|
||||
impl ReconnectPacer {
|
||||
fn new(initial: u64, max_tries: Option<usize>) -> Self {
|
||||
Self {
|
||||
tries: 0,
|
||||
backoff: initial,
|
||||
initial,
|
||||
max_tries,
|
||||
}
|
||||
}
|
||||
|
||||
/// Count a failure; `true` means the bounded try cap was hit.
|
||||
fn give_up(&mut self) -> bool {
|
||||
if let Some(limit) = self.max_tries {
|
||||
self.tries += 1;
|
||||
self.tries >= limit
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Current delay, advancing the doubling (capped) for the next failure.
|
||||
fn next_backoff(&mut self) -> u64 {
|
||||
let current = self.backoff;
|
||||
self.backoff = (self.backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
current
|
||||
}
|
||||
|
||||
/// Sleep the current backoff, then double it (capped).
|
||||
async fn wait(&mut self) {
|
||||
let delay = self.next_backoff();
|
||||
tokio::time::sleep(std::time::Duration::from_secs(delay)).await;
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.tries = 0;
|
||||
self.backoff = self.initial;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -997,24 +1060,37 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_max_tries_unlimited() {
|
||||
let max = None;
|
||||
let mut tries = 0;
|
||||
assert!(!check_max_tries(&max, &mut tries));
|
||||
assert_eq!(tries, 0);
|
||||
fn test_pacer_unlimited_never_gives_up() {
|
||||
let mut pacer = ReconnectPacer::new(15, None);
|
||||
for _ in 0..100 {
|
||||
assert!(!pacer.give_up());
|
||||
}
|
||||
assert_eq!(pacer.tries, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_max_tries_limited() {
|
||||
let max = Some(3);
|
||||
let mut tries = 0;
|
||||
fn test_pacer_bounded_gives_up_at_cap() {
|
||||
let mut pacer = ReconnectPacer::new(15, Some(3));
|
||||
assert!(!pacer.give_up());
|
||||
assert!(!pacer.give_up());
|
||||
assert!(pacer.give_up());
|
||||
assert_eq!(pacer.tries, 3);
|
||||
}
|
||||
|
||||
assert!(!check_max_tries(&max, &mut tries));
|
||||
assert_eq!(tries, 1);
|
||||
assert!(!check_max_tries(&max, &mut tries));
|
||||
assert_eq!(tries, 2);
|
||||
assert!(check_max_tries(&max, &mut tries));
|
||||
assert_eq!(tries, 3);
|
||||
#[test]
|
||||
fn test_pacer_backoff_doubles_capped_and_resets() {
|
||||
let mut pacer = ReconnectPacer::new(15, Some(10));
|
||||
assert_eq!(pacer.next_backoff(), 15);
|
||||
assert_eq!(pacer.backoff, 30);
|
||||
for _ in 0..10 {
|
||||
pacer.next_backoff();
|
||||
}
|
||||
assert_eq!(pacer.backoff, RECONNECT_WAIT_MAX);
|
||||
|
||||
let _ = pacer.give_up();
|
||||
pacer.reset();
|
||||
assert_eq!(pacer.tries, 0);
|
||||
assert_eq!(pacer.backoff, 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -121,87 +121,31 @@ pub fn frame_with_command(cmd: u8, data: &[u8]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Classic KISS deframer: high nibble of the command byte is a TNC port, so
|
||||
/// frames are returned as `(command & CMD_MASK, data)`. Thin wrapper over
|
||||
/// [`RawKissDeframer`], which owns the framing state machine.
|
||||
pub struct KissDeframer {
|
||||
buffer: Vec<u8>,
|
||||
in_frame: bool,
|
||||
command: u8,
|
||||
/// Reusable scratch for unescape output.
|
||||
unescape_scratch: Vec<u8>,
|
||||
inner: RawKissDeframer,
|
||||
}
|
||||
|
||||
impl KissDeframer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
|
||||
in_frame: false,
|
||||
command: CMD_UNKNOWN,
|
||||
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
|
||||
inner: RawKissDeframer::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns complete frames as (command, data) pairs.
|
||||
pub fn feed(&mut self, data: &[u8]) -> Vec<(u8, Vec<u8>)> {
|
||||
let mut frames = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < data.len() {
|
||||
match data[i..].iter().position(|&b| b == FEND) {
|
||||
Some(rel) => {
|
||||
let hit = i + rel;
|
||||
if self.in_frame {
|
||||
self.append_in_frame(&data[i..hit]);
|
||||
if !self.buffer.is_empty() {
|
||||
self.unescape_scratch.clear();
|
||||
unescape_into(&self.buffer, &mut self.unescape_scratch);
|
||||
let frame_data = std::mem::replace(
|
||||
&mut self.unescape_scratch,
|
||||
Vec::with_capacity(DEFRAME_BUF_CAPACITY),
|
||||
);
|
||||
frames.push((self.command & CMD_MASK, frame_data));
|
||||
}
|
||||
self.buffer.clear();
|
||||
}
|
||||
self.in_frame = true;
|
||||
self.command = CMD_UNKNOWN;
|
||||
i = hit + 1;
|
||||
}
|
||||
None => {
|
||||
if self.in_frame {
|
||||
self.append_in_frame(&data[i..]);
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
}
|
||||
let mut frames = self.inner.feed(data);
|
||||
for frame in &mut frames {
|
||||
frame.0 &= CMD_MASK;
|
||||
}
|
||||
frames
|
||||
}
|
||||
|
||||
/// Append `chunk` to the in-frame buffer. The first byte after a FEND is
|
||||
/// the command byte (consumed separately); subsequent bytes are payload
|
||||
/// up to `MAX_FRAME_SIZE`. Overflow drops the in-progress frame and waits
|
||||
/// for the next FEND to resync — matching the previous byte-loop.
|
||||
fn append_in_frame(&mut self, chunk: &[u8]) {
|
||||
let mut chunk = chunk;
|
||||
if self.command == CMD_UNKNOWN {
|
||||
if let Some((&first, rest)) = chunk.split_first() {
|
||||
self.command = first;
|
||||
chunk = rest;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
|
||||
self.buffer.clear();
|
||||
self.in_frame = false;
|
||||
self.command = CMD_UNKNOWN;
|
||||
return;
|
||||
}
|
||||
self.buffer.extend_from_slice(chunk);
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.buffer.clear();
|
||||
self.in_frame = false;
|
||||
self.command = CMD_UNKNOWN;
|
||||
self.inner.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +165,7 @@ pub struct RawKissDeframer {
|
||||
buffer: Vec<u8>,
|
||||
in_frame: bool,
|
||||
command: u8,
|
||||
/// Reusable scratch for unescape output.
|
||||
unescape_scratch: Vec<u8>,
|
||||
}
|
||||
|
||||
@@ -270,6 +215,10 @@ impl RawKissDeframer {
|
||||
frames
|
||||
}
|
||||
|
||||
/// Append `chunk` to the in-frame buffer. The first byte after a FEND is
|
||||
/// the command byte (consumed separately); subsequent bytes are payload
|
||||
/// up to `MAX_FRAME_SIZE`. Overflow drops the in-progress frame and waits
|
||||
/// for the next FEND to resync — matching the previous byte-loop.
|
||||
fn append_in_frame(&mut self, chunk: &[u8]) {
|
||||
let mut chunk = chunk;
|
||||
if self.command == CMD_UNKNOWN {
|
||||
|
||||
@@ -28,6 +28,10 @@ pub struct KissInterfaceConfig {
|
||||
pub txtail: Option<u8>,
|
||||
/// Honour CMD_READY from TNC.
|
||||
pub flow_control: bool,
|
||||
/// Station-ID beacon: seconds between IDs, counted from the first data
|
||||
/// TX after the previous beacon (Python `id_interval`/`id_callsign`).
|
||||
pub id_interval: Option<u64>,
|
||||
pub id_callsign: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl KissInterfaceConfig {
|
||||
@@ -45,10 +49,22 @@ impl KissInterfaceConfig {
|
||||
txdelay: None,
|
||||
txtail: None,
|
||||
flow_control: false,
|
||||
id_interval: None,
|
||||
id_callsign: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Beacon frame payload: callsign zero-padded to the 15-byte minimum
|
||||
/// (Python KISSInterface.py:350-353).
|
||||
pub fn beacon_frame_payload(id_callsign: &[u8]) -> Vec<u8> {
|
||||
let mut frame = id_callsign.to_vec();
|
||||
while frame.len() < 15 {
|
||||
frame.push(0x00);
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
pub async fn spawn_kiss_interface(
|
||||
config: KissInterfaceConfig,
|
||||
id: InterfaceId,
|
||||
@@ -113,9 +129,49 @@ pub async fn spawn_kiss_interface(
|
||||
let online_w = online.clone();
|
||||
let ready_w = ready.clone();
|
||||
let txb_w = shared_txb.clone();
|
||||
let beacon = config
|
||||
.id_interval
|
||||
.zip(config.id_callsign.clone())
|
||||
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)));
|
||||
tokio::spawn(async move {
|
||||
let mut port_w = port_write;
|
||||
while let Some(data) = rx.recv().await {
|
||||
// Python first_tx semantics: armed by the first data TX after a
|
||||
// beacon; cleared when the beacon goes out.
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let data = if let Some((interval, ref callsign)) = beacon {
|
||||
match tokio::time::timeout(Duration::from_secs(1), rx.recv()).await {
|
||||
Ok(Some(data)) => data,
|
||||
Ok(None) => break,
|
||||
Err(_) => {
|
||||
let due = first_tx.is_some_and(|t| t.elapsed() >= interval);
|
||||
if !due {
|
||||
continue;
|
||||
}
|
||||
tracing::debug!("KISS transmitting station-ID beacon");
|
||||
Bytes::from(beacon_frame_payload(callsign))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match rx.recv().await {
|
||||
Some(data) => data,
|
||||
None => break,
|
||||
}
|
||||
};
|
||||
|
||||
// Python KISSInterface.py:267-271 compares the unpadded callsign,
|
||||
// so a padded (<15 byte) beacon re-arms the timer and beacons
|
||||
// repeat every id_interval once anything has been sent. Kept
|
||||
// bug-for-bug for parity.
|
||||
let is_beacon = beacon
|
||||
.as_ref()
|
||||
.is_some_and(|(_, callsign)| data == *callsign);
|
||||
if is_beacon {
|
||||
first_tx = None;
|
||||
} else if first_tx.is_none() {
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
|
||||
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
// Flow control: bounded wait so a stuck TNC can't hang transmit.
|
||||
if flow_control {
|
||||
@@ -132,25 +188,13 @@ pub async fn spawn_kiss_interface(
|
||||
}
|
||||
}
|
||||
let framed = kiss::frame(&data);
|
||||
let online_ref = online_w.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Write;
|
||||
port_w.write_all(&framed)?;
|
||||
port_w.flush()?;
|
||||
Ok::<_, std::io::Error>(port_w)
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(Ok(p)) => {
|
||||
match crate::serial_io::blocking_write_all(port_w, framed).await {
|
||||
Ok(p) => {
|
||||
port_w = p;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(error = %e, "KISS write error");
|
||||
online_ref.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "KISS write task panicked");
|
||||
tracing::warn!(error = %e, "KISS write error");
|
||||
online_w.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -169,18 +213,8 @@ pub async fn spawn_kiss_interface(
|
||||
if !online_r.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Read;
|
||||
match port_r.read(&mut buf) {
|
||||
Ok(n) => Ok((port_r, buf, n)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
|
||||
Err(e) => Err((port_r, e)),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(Ok((p, b, n))) => {
|
||||
match crate::serial_io::poll_read(port_r, buf).await {
|
||||
Ok((p, b, n)) => {
|
||||
port_r = p;
|
||||
buf = b;
|
||||
if n > 0 {
|
||||
@@ -217,13 +251,8 @@ pub async fn spawn_kiss_interface(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err((_p, e))) => {
|
||||
tracing::warn!(error = %e, "KISS read error");
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "KISS read task panicked");
|
||||
tracing::warn!(error = %e, "KISS read error");
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
@@ -233,6 +262,7 @@ pub async fn spawn_kiss_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -261,6 +291,20 @@ mod tests {
|
||||
assert_eq!(cfg.baud_rate, 9600);
|
||||
assert!(!cfg.flow_control);
|
||||
assert_eq!(cfg.mode, InterfaceMode::Full);
|
||||
assert!(cfg.id_interval.is_none() && cfg.id_callsign.is_none());
|
||||
}
|
||||
|
||||
/// Python KISSInterface.py:350-353 — beacon payload is the callsign
|
||||
/// zero-padded to 15 bytes; longer callsigns pass through unchanged.
|
||||
#[test]
|
||||
fn test_beacon_frame_payload_padding() {
|
||||
let short = beacon_frame_payload(b"MYCALL-0");
|
||||
assert_eq!(short.len(), 15);
|
||||
assert_eq!(&short[..8], b"MYCALL-0");
|
||||
assert!(short[8..].iter().all(|&b| b == 0));
|
||||
|
||||
let long = beacon_frame_payload(b"AVERYLONGCALLSIGN");
|
||||
assert_eq!(long, b"AVERYLONGCALLSIGN");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Network interface implementations for Reticulum.
|
||||
//! Each module provides a spawn function returning a Tokio task driving a
|
||||
//! concrete transport; [`traits::Interface`] is the common abstraction.
|
||||
//! concrete transport; [`traits::InterfaceHandle`] is the common handle the
|
||||
//! runtime registers with the transport actor.
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub mod android_usb;
|
||||
@@ -32,6 +33,8 @@ pub mod rnode_admin;
|
||||
pub mod rnode_multi;
|
||||
#[cfg(feature = "serial")]
|
||||
pub mod serial;
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
mod serial_io;
|
||||
pub mod socket_tuning;
|
||||
pub mod tcp;
|
||||
pub mod traits;
|
||||
|
||||
+124
-192
@@ -148,6 +148,94 @@ async fn local_write_loop<W: AsyncWriteExt + Unpin>(
|
||||
online.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Per-stream wiring shared by both platform variants: write loop, read task,
|
||||
/// and the connection's `InterfaceHandle`. `dereg_on_disconnect` is set for
|
||||
/// accepted server-side clients so transport drops them immediately on EOF.
|
||||
fn wire_local_stream<R, W>(
|
||||
id: InterfaceId,
|
||||
name: String,
|
||||
parent_id: Option<InterfaceId>,
|
||||
reader: R,
|
||||
writer: W,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
dereg_on_disconnect: bool,
|
||||
) -> InterfaceHandle
|
||||
where
|
||||
R: AsyncReadExt + Unpin + Send + 'static,
|
||||
W: AsyncWriteExt + Unpin + Send + 'static,
|
||||
{
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let rxb = Arc::new(AtomicU64::new(0));
|
||||
let txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, rx) = mpsc::channel::<Bytes>(256);
|
||||
|
||||
tokio::spawn(local_write_loop(writer, rx, online.clone(), txb.clone()));
|
||||
|
||||
let online_r = online.clone();
|
||||
let rxb_r = rxb.clone();
|
||||
let task_name = name.clone();
|
||||
let dereg_tx = transport_tx.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
local_read_loop(reader, id, transport_tx, online_r, rxb_r).await;
|
||||
if dereg_on_disconnect {
|
||||
tracing::info!(name = %task_name, "local client disconnected");
|
||||
// Proactively notify so transport drops immediately.
|
||||
let _ = dereg_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
InterfaceHandle {
|
||||
id,
|
||||
parent_id,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle for the listener pseudo-interface (id 0): inbound-only, no
|
||||
/// per-byte counters of its own.
|
||||
fn server_listener_handle(
|
||||
name: String,
|
||||
online: Arc<AtomicBool>,
|
||||
tx: mpsc::Sender<Bytes>,
|
||||
read_task: tokio::task::JoinHandle<()>,
|
||||
) -> InterfaceHandle {
|
||||
InterfaceHandle {
|
||||
id: 0,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: false,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod platform {
|
||||
use super::*;
|
||||
@@ -238,49 +326,16 @@ mod platform {
|
||||
let client_name = format!("{}/client_{}", config.name, client_id);
|
||||
tracing::info!(name = %client_name, "local client connected");
|
||||
|
||||
let c_online = Arc::new(AtomicBool::new(true));
|
||||
let c_rxb = Arc::new(AtomicU64::new(0));
|
||||
let c_txb = Arc::new(AtomicU64::new(0));
|
||||
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
|
||||
let (reader, writer) = stream.into_split();
|
||||
|
||||
let c_online2 = c_online.clone();
|
||||
let c_txb2 = c_txb.clone();
|
||||
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
|
||||
|
||||
let c_online3 = c_online.clone();
|
||||
let c_rxb2 = c_rxb.clone();
|
||||
let transport_tx2 = transport_tx.clone();
|
||||
let dereg_tx = transport_tx.clone();
|
||||
let cname = client_name.clone();
|
||||
let read_handle = tokio::spawn(async move {
|
||||
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
|
||||
.await;
|
||||
tracing::info!(name = %cname, "local client disconnected");
|
||||
// Proactively notify so transport drops immediately.
|
||||
let _ = dereg_tx
|
||||
.send(TransportMessage::DeregisterInterface { id: client_id })
|
||||
.await;
|
||||
});
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: client_id,
|
||||
name: client_name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
tx: c_tx,
|
||||
read_task: read_handle,
|
||||
};
|
||||
let handle = wire_local_stream(
|
||||
client_id,
|
||||
client_name,
|
||||
Some(0),
|
||||
reader,
|
||||
writer,
|
||||
transport_tx.clone(),
|
||||
true,
|
||||
);
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
tracing::warn!("local handle registry closed");
|
||||
break;
|
||||
@@ -295,27 +350,7 @@ mod platform {
|
||||
online2.store(false, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
let server_rxb = Arc::new(AtomicU64::new(0));
|
||||
let server_txb = Arc::new(AtomicU64::new(0));
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id: 0,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: false,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(server_rxb),
|
||||
txb: Some(server_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
Ok(server_listener_handle(name, online, tx, read_task))
|
||||
}
|
||||
|
||||
pub async fn spawn_local_client_impl(
|
||||
@@ -326,41 +361,16 @@ mod platform {
|
||||
let stream = connect_unix_stream(&config.socket_path).await?;
|
||||
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
|
||||
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, rx) = mpsc::channel::<Bytes>(256);
|
||||
let (reader, writer) = stream.into_split();
|
||||
|
||||
let online_w = online.clone();
|
||||
let task_txb = shared_txb.clone();
|
||||
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
|
||||
|
||||
let online_r = online.clone();
|
||||
let task_rxb = shared_rxb.clone();
|
||||
let name = config.name.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
|
||||
});
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
Ok(wire_local_stream(
|
||||
id,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
config.name.clone(),
|
||||
None,
|
||||
reader,
|
||||
writer,
|
||||
transport_tx,
|
||||
false,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,49 +414,16 @@ mod platform {
|
||||
let client_name = format!("{}/client_{}", config.name, client_id);
|
||||
tracing::info!(name = %client_name, peer = %peer, "local client connected (TCP)");
|
||||
|
||||
let c_online = Arc::new(AtomicBool::new(true));
|
||||
let c_rxb = Arc::new(AtomicU64::new(0));
|
||||
let c_txb = Arc::new(AtomicU64::new(0));
|
||||
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
|
||||
let (reader, writer) = stream.into_split();
|
||||
|
||||
let c_online2 = c_online.clone();
|
||||
let c_txb2 = c_txb.clone();
|
||||
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
|
||||
|
||||
let c_online3 = c_online.clone();
|
||||
let c_rxb2 = c_rxb.clone();
|
||||
let transport_tx2 = transport_tx.clone();
|
||||
let dereg_tx = transport_tx.clone();
|
||||
let cname = client_name.clone();
|
||||
let read_handle = tokio::spawn(async move {
|
||||
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
|
||||
.await;
|
||||
tracing::info!(name = %cname, "local client disconnected");
|
||||
// See unix variant — notify proactively to avoid zombies.
|
||||
let _ = dereg_tx
|
||||
.send(TransportMessage::DeregisterInterface { id: client_id })
|
||||
.await;
|
||||
});
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: client_id,
|
||||
name: client_name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
tx: c_tx,
|
||||
read_task: read_handle,
|
||||
};
|
||||
let handle = wire_local_stream(
|
||||
client_id,
|
||||
client_name,
|
||||
Some(0),
|
||||
reader,
|
||||
writer,
|
||||
transport_tx.clone(),
|
||||
true,
|
||||
);
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
tracing::warn!("local handle registry closed");
|
||||
break;
|
||||
@@ -461,27 +438,7 @@ mod platform {
|
||||
online2.store(false, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
let server_rxb = Arc::new(AtomicU64::new(0));
|
||||
let server_txb = Arc::new(AtomicU64::new(0));
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id: 0,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: false,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(server_rxb),
|
||||
txb: Some(server_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
Ok(server_listener_handle(name, online, tx, read_task))
|
||||
}
|
||||
|
||||
pub async fn spawn_local_client_impl(
|
||||
@@ -493,41 +450,16 @@ mod platform {
|
||||
let stream = TcpStream::connect(&addr).await?;
|
||||
tracing::info!(name = %config.name, addr = %addr, "local client connected (TCP fallback)");
|
||||
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, rx) = mpsc::channel::<Bytes>(256);
|
||||
let (reader, writer) = stream.into_split();
|
||||
|
||||
let online_w = online.clone();
|
||||
let task_txb = shared_txb.clone();
|
||||
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
|
||||
|
||||
let online_r = online.clone();
|
||||
let task_rxb = shared_rxb.clone();
|
||||
let name = config.name.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
|
||||
});
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
Ok(wire_local_stream(
|
||||
id,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
config.name.clone(),
|
||||
None,
|
||||
reader,
|
||||
writer,
|
||||
transport_tx,
|
||||
false,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -189,6 +189,7 @@ pub async fn spawn_pipe_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
|
||||
+1050
-157
File diff suppressed because it is too large.
Load diff
@@ -176,6 +176,10 @@ pub struct RNodeMultiConfig {
|
||||
pub flow_control: bool,
|
||||
/// Up to `MAX_SUBINTERFACES` radios on this device.
|
||||
pub subinterfaces: Vec<SubInterfaceConfig>,
|
||||
/// Station-ID beacon, parent-level: when due, the callsign is sent on
|
||||
/// all subinterfaces (Python RNodeMultiInterface.py:849-859).
|
||||
pub id_interval: Option<u64>,
|
||||
pub id_callsign: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl RNodeMultiConfig {
|
||||
@@ -186,6 +190,8 @@ impl RNodeMultiConfig {
|
||||
baud_rate: 115200,
|
||||
flow_control: false,
|
||||
subinterfaces: Vec::new(),
|
||||
id_interval: None,
|
||||
id_callsign: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -265,13 +271,38 @@ struct SubInterfaceSignal {
|
||||
last_snr: Option<f32>,
|
||||
}
|
||||
|
||||
/// Device-level + per-sub online state shared by the writer and reader tasks.
|
||||
#[derive(Clone)]
|
||||
struct OnlineFlags {
|
||||
device: Arc<AtomicBool>,
|
||||
subs: Arc<Vec<Arc<AtomicBool>>>,
|
||||
}
|
||||
|
||||
impl OnlineFlags {
|
||||
/// Device failure takes every sub-interface down with it.
|
||||
fn trip_device(&self) {
|
||||
self.device.store(false, Ordering::SeqCst);
|
||||
for sub in self.subs.iter() {
|
||||
sub.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// True while the device is up and at least one sub remains registered —
|
||||
/// once false the shared reader exits and releases the serial port.
|
||||
fn device_running(&self) -> bool {
|
||||
self.device.load(Ordering::SeqCst) && self.subs.iter().any(|sub| sub.load(Ordering::SeqCst))
|
||||
}
|
||||
}
|
||||
|
||||
const RNODE_READ_TIMEOUT_MS: u64 = 100;
|
||||
|
||||
/// Spawn one RNodeMulti over a single serial port.
|
||||
///
|
||||
/// Returns one `InterfaceHandle` per configured sub-interface. Each handle has
|
||||
/// its own tx channel and `InterfaceId`; all of them share one serial
|
||||
/// connection and one online flag, so the whole device goes up or down atomically.
|
||||
/// its own tx channel, `InterfaceId`, and online flag; all of them share one
|
||||
/// serial connection. Tearing down one sub leaves the others running; the
|
||||
/// shared reader exits (releasing the port) when the device fails or every
|
||||
/// sub has been deregistered.
|
||||
///
|
||||
/// `ids.len()` must equal `config.subinterfaces.len()`.
|
||||
pub async fn spawn_rnode_multi_interface(
|
||||
@@ -351,6 +382,19 @@ pub async fn spawn_rnode_multi_interface(
|
||||
|
||||
let num_subs = config.subinterfaces.len();
|
||||
|
||||
// Per-sub online flags: deregistering one sub must not kill the shared
|
||||
// device, but the reader must release the serial port once ALL subs are
|
||||
// gone; device-level failure trips every sub flag.
|
||||
let sub_onlines: Arc<Vec<Arc<AtomicBool>>> = Arc::new(
|
||||
(0..num_subs)
|
||||
.map(|_| Arc::new(AtomicBool::new(true)))
|
||||
.collect(),
|
||||
);
|
||||
let flags = OnlineFlags {
|
||||
device: online.clone(),
|
||||
subs: sub_onlines.clone(),
|
||||
};
|
||||
|
||||
// All sub-interface handles funnel into one writer so CMD_SEL_INT framing
|
||||
// stays ordered relative to each data frame.
|
||||
let (write_tx, mut write_rx) = mpsc::channel::<WriteRequest>(256);
|
||||
@@ -410,11 +454,12 @@ pub async fn spawn_rnode_multi_interface(
|
||||
);
|
||||
|
||||
// The real read loop is shared by all sub-interfaces; each handle just
|
||||
// needs a JoinHandle that exits when the device goes offline.
|
||||
let online_sub = online.clone();
|
||||
// needs a JoinHandle that exits when its sub or the device goes offline.
|
||||
let online_sub = sub_onlines[i].clone();
|
||||
let device_sub = online.clone();
|
||||
let sub_read_task = tokio::spawn(async move {
|
||||
loop {
|
||||
if !online_sub.load(Ordering::SeqCst) {
|
||||
if !online_sub.load(Ordering::SeqCst) || !device_sub.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
@@ -423,6 +468,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
|
||||
handles.push(InterfaceHandle {
|
||||
id: ids[i],
|
||||
parent_id: None,
|
||||
name: sub_name,
|
||||
mode: sub_cfg.mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -433,7 +479,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
},
|
||||
bitrate,
|
||||
mtu: rns_wire::constants::MTU as u32,
|
||||
online: online.clone(),
|
||||
online: sub_onlines[i].clone(),
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
tx: sub_tx,
|
||||
@@ -448,15 +494,81 @@ pub async fn spawn_rnode_multi_interface(
|
||||
.try_clone()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?;
|
||||
let online_w = online.clone();
|
||||
let flags_w = flags.clone();
|
||||
let ready = Arc::new(AtomicBool::new(true));
|
||||
let ready_w = ready.clone();
|
||||
|
||||
// Python RNodeMultiInterface.py:281-291 — oversized callsigns disable
|
||||
// beaconing; when due, the callsign goes out on all subinterfaces.
|
||||
let beacon: Option<(Duration, Bytes)> = config
|
||||
.id_interval
|
||||
.zip(config.id_callsign.clone())
|
||||
.filter(|(_, callsign)| {
|
||||
let ok = callsign.len() <= rnode::CALLSIGN_MAX_LEN;
|
||||
if !ok {
|
||||
tracing::error!(
|
||||
name = %config.name,
|
||||
len = callsign.len(),
|
||||
"id_callsign exceeds {} bytes, beaconing disabled",
|
||||
rnode::CALLSIGN_MAX_LEN
|
||||
);
|
||||
}
|
||||
ok
|
||||
})
|
||||
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)));
|
||||
let beacon_vports: Vec<u8> = config.subinterfaces.iter().map(|s| s.vport).collect();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut port_w = port_write;
|
||||
while let Some(req) = write_rx.recv().await {
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let req = if let Some((interval, ref callsign)) = beacon {
|
||||
match tokio::time::timeout(Duration::from_secs(1), write_rx.recv()).await {
|
||||
Ok(Some(req)) => req,
|
||||
Ok(None) => break,
|
||||
Err(_) => {
|
||||
if first_tx.is_none_or(|t| t.elapsed() < interval)
|
||||
|| !online_w.load(Ordering::SeqCst)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
tracing::debug!(
|
||||
"RNodeMulti transmitting station-ID beacon on all subinterfaces"
|
||||
);
|
||||
first_tx = None;
|
||||
let mut frames = Vec::new();
|
||||
for &vport in &beacon_vports {
|
||||
frames
|
||||
.extend_from_slice(&build_subinterface_data_frame(vport, callsign));
|
||||
}
|
||||
match crate::serial_io::blocking_write_all(port_w, frames).await {
|
||||
Ok(p) => {
|
||||
port_w = p;
|
||||
continue;
|
||||
}
|
||||
Err(_) => {
|
||||
flags_w.trip_device();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match write_rx.recv().await {
|
||||
Some(req) => req,
|
||||
None => break,
|
||||
}
|
||||
};
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
if let Some((_, ref callsign)) = beacon {
|
||||
if req.data == *callsign {
|
||||
first_tx = None;
|
||||
} else if first_tx.is_none() {
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
if req.flow_control {
|
||||
// Bound CMD_READY wait at ~5 s so a stuck TNC can't block tx.
|
||||
@@ -471,32 +583,20 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
|
||||
let frame = build_subinterface_data_frame(req.index, &req.data);
|
||||
let online_ref = online_w.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Write;
|
||||
port_w.write_all(&frame)?;
|
||||
port_w.flush()?;
|
||||
Ok::<_, std::io::Error>(port_w)
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(Ok(p)) => {
|
||||
match crate::serial_io::blocking_write_all(port_w, frame).await {
|
||||
Ok(p) => {
|
||||
port_w = p;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(error = %e, "RNodeMulti write error");
|
||||
online_ref.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "RNodeMulti write task panicked");
|
||||
tracing::warn!(error = %e, "RNodeMulti write error");
|
||||
flags_w.trip_device();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let online_r = online.clone();
|
||||
let flags_r = flags;
|
||||
let ready_r = ready;
|
||||
let parent_name = config.name.clone();
|
||||
|
||||
@@ -527,22 +627,12 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let mut interfaces_buf: Vec<u8> = Vec::new();
|
||||
|
||||
loop {
|
||||
if !online_r.load(Ordering::SeqCst) {
|
||||
if !flags_r.device_running() {
|
||||
break;
|
||||
}
|
||||
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Read;
|
||||
match port_r.read(&mut buf) {
|
||||
Ok(n) => Ok((port_r, buf, n)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
|
||||
Err(e) => Err((port_r, e)),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(Ok((p, b, n))) => {
|
||||
match crate::serial_io::poll_read(port_r, buf).await {
|
||||
Ok((p, b, n)) => {
|
||||
port_r = p;
|
||||
buf = b;
|
||||
if n == 0 {
|
||||
@@ -572,7 +662,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
parent = %parent_name,
|
||||
"transport channel closed"
|
||||
);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
flags_r.trip_device();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
@@ -596,7 +686,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
|
||||
rnode::CMD_STAT_RSSI => {
|
||||
if !frame.is_empty() {
|
||||
let rssi = frame[0] as i8 as f32;
|
||||
let rssi = rnode::decode_rssi_byte(frame[0]);
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
{
|
||||
@@ -606,7 +696,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
rnode::CMD_STAT_SNR => {
|
||||
if !frame.is_empty() {
|
||||
let snr = frame[0] as i8 as f32 / 4.0;
|
||||
let snr = rnode::decode_snr_byte(frame[0]);
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
{
|
||||
@@ -801,39 +891,16 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
}
|
||||
|
||||
CMD_ERROR => {
|
||||
if !frame.is_empty() {
|
||||
match frame[0] {
|
||||
ERROR_INITRADIO => {
|
||||
tracing::error!(
|
||||
parent = %parent_name,
|
||||
"RNodeMulti hardware initialisation error"
|
||||
);
|
||||
}
|
||||
ERROR_TXFAILED => {
|
||||
tracing::error!(
|
||||
parent = %parent_name,
|
||||
"RNodeMulti hardware TX error"
|
||||
);
|
||||
}
|
||||
code => {
|
||||
tracing::error!(
|
||||
parent = %parent_name,
|
||||
code = format!("0x{:02X}", code),
|
||||
"RNodeMulti hardware error"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No CMD_ERROR arm: 0x90 collides with CMD_INT5_DATA
|
||||
// and is consumed by the vport demux above — same
|
||||
// collision as Python RNodeMultiInterface.
|
||||
rnode::CMD_RESET => {
|
||||
if frame.first().copied() == Some(0xF8) {
|
||||
tracing::error!(
|
||||
parent = %parent_name,
|
||||
"RNodeMulti device reset detected"
|
||||
);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
flags_r.trip_device();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -848,22 +915,13 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err((_p, e))) => {
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
error = %e,
|
||||
"RNodeMulti read error"
|
||||
);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
error = %e,
|
||||
"RNodeMulti read task panicked"
|
||||
);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
flags_r.trip_device();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -893,6 +951,48 @@ mod tests {
|
||||
assert!(cfg.subinterfaces.iter().all(|sub| !sub.flow_control));
|
||||
}
|
||||
|
||||
/// T1-3: the shared serial reader runs while the device is up and at
|
||||
/// least one sub-interface remains registered. Deregistering one sub
|
||||
/// must NOT stop the device; deregistering all must (port release);
|
||||
/// device failure trips every sub flag.
|
||||
#[test]
|
||||
fn test_online_flags_reader_exit_semantics() {
|
||||
let flags = OnlineFlags {
|
||||
device: Arc::new(AtomicBool::new(true)),
|
||||
subs: Arc::new(vec![
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
]),
|
||||
};
|
||||
assert!(flags.device_running());
|
||||
|
||||
// One sub deregistered (actor flips its flag): device keeps serving.
|
||||
flags.subs[0].store(false, Ordering::SeqCst);
|
||||
assert!(flags.device_running());
|
||||
|
||||
// Last sub deregistered: reader must exit and release the port.
|
||||
flags.subs[1].store(false, Ordering::SeqCst);
|
||||
assert!(!flags.device_running());
|
||||
|
||||
// Device failure path: every sub flag goes down with the device.
|
||||
let flags2 = OnlineFlags {
|
||||
device: Arc::new(AtomicBool::new(true)),
|
||||
subs: Arc::new(vec![Arc::new(AtomicBool::new(true))]),
|
||||
};
|
||||
flags2.trip_device();
|
||||
assert!(!flags2.device.load(Ordering::SeqCst));
|
||||
assert!(!flags2.subs[0].load(Ordering::SeqCst));
|
||||
assert!(!flags2.device_running());
|
||||
}
|
||||
|
||||
/// The multi reader decodes STAT_RSSI/STAT_SNR via the shared rnode
|
||||
/// helpers — Python formula: RSSI = raw byte − 157, SNR = signed × 0.25.
|
||||
#[test]
|
||||
fn test_multi_rssi_snr_decode_matches_python() {
|
||||
assert_eq!(rnode::decode_rssi_byte(67), -90.0);
|
||||
assert_eq!(rnode::decode_snr_byte(0xF6), -2.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subinterface_init_sequence() {
|
||||
let sub_cfg = SubInterfaceConfig::new("radio0", 0, 868_000_000);
|
||||
|
||||
@@ -46,6 +46,36 @@ impl SerialConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Map Python-style serial config values (`databits`/`parity`/`stopbits`)
|
||||
/// to serialport enums. Parity accepts `e`/`even` and `o`/`odd`
|
||||
/// (case-insensitive); anything else is none, matching the reference.
|
||||
pub fn serial_params_from(
|
||||
data_bits: u8,
|
||||
parity: &str,
|
||||
stop_bits: u8,
|
||||
) -> (
|
||||
serialport::DataBits,
|
||||
serialport::Parity,
|
||||
serialport::StopBits,
|
||||
) {
|
||||
let data = match data_bits {
|
||||
5 => serialport::DataBits::Five,
|
||||
6 => serialport::DataBits::Six,
|
||||
7 => serialport::DataBits::Seven,
|
||||
_ => serialport::DataBits::Eight,
|
||||
};
|
||||
let parity = match parity.to_ascii_lowercase().as_str() {
|
||||
"e" | "even" => serialport::Parity::Even,
|
||||
"o" | "odd" => serialport::Parity::Odd,
|
||||
_ => serialport::Parity::None,
|
||||
};
|
||||
let stop = match stop_bits {
|
||||
2 => serialport::StopBits::Two,
|
||||
_ => serialport::StopBits::One,
|
||||
};
|
||||
(data, parity, stop)
|
||||
}
|
||||
|
||||
pub async fn spawn_serial_interface(
|
||||
config: SerialConfig,
|
||||
id: InterfaceId,
|
||||
@@ -84,25 +114,13 @@ pub async fn spawn_serial_interface(
|
||||
while let Some(data) = rx.recv().await {
|
||||
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
let framed = hdlc::frame(&data);
|
||||
let online_ref = online_w.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Write;
|
||||
port_w.write_all(&framed)?;
|
||||
port_w.flush()?;
|
||||
Ok::<_, std::io::Error>(port_w)
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(Ok(p)) => {
|
||||
match crate::serial_io::blocking_write_all(port_w, framed).await {
|
||||
Ok(p) => {
|
||||
port_w = p;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(error = %e, "serial write error");
|
||||
online_ref.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "serial write task panicked");
|
||||
tracing::warn!(error = %e, "serial write error");
|
||||
online_w.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -120,18 +138,8 @@ pub async fn spawn_serial_interface(
|
||||
if !online_r.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Read;
|
||||
match port_r.read(&mut buf) {
|
||||
Ok(n) => Ok((port_r, buf, n)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
|
||||
Err(e) => Err((port_r, e)),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(Ok((p, b, n))) => {
|
||||
match crate::serial_io::poll_read(port_r, buf).await {
|
||||
Ok((p, b, n)) => {
|
||||
port_r = p;
|
||||
buf = b;
|
||||
if n > 0 {
|
||||
@@ -155,13 +163,8 @@ pub async fn spawn_serial_interface(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err((_p, e))) => {
|
||||
tracing::warn!(error = %e, "serial read error");
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "serial read task panicked");
|
||||
tracing::warn!(error = %e, "serial read error");
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
@@ -171,6 +174,7 @@ pub async fn spawn_serial_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Blocking-I/O shuttles shared by the serial-family interfaces (Serial,
|
||||
//! KISS, AX.25 KISS, RNodeMulti). No mature async serial driver exists, so
|
||||
//! each read/write moves the port through `spawn_blocking` and back.
|
||||
|
||||
/// One bounded blocking read. Serial idle timeouts surface as `n == 0` so
|
||||
/// the caller's loop can re-check its exit flag. A panicked blocking task
|
||||
/// folds into an `io::Error`.
|
||||
pub(crate) async fn poll_read<P>(
|
||||
mut port: P,
|
||||
mut buf: [u8; 1024],
|
||||
) -> Result<(P, [u8; 1024], usize), std::io::Error>
|
||||
where
|
||||
P: std::io::Read + Send + 'static,
|
||||
{
|
||||
let result = tokio::task::spawn_blocking(move || match port.read(&mut buf) {
|
||||
Ok(n) => Ok((port, buf, n)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port, buf, 0)),
|
||||
Err(e) => Err(e),
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(read_result) => read_result,
|
||||
Err(join_err) => Err(std::io::Error::other(join_err)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One blocking `write_all` + `flush`, returning the port for the next call.
|
||||
pub(crate) async fn blocking_write_all<P>(mut port: P, data: Vec<u8>) -> Result<P, std::io::Error>
|
||||
where
|
||||
P: std::io::Write + Send + 'static,
|
||||
{
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
port.write_all(&data)?;
|
||||
port.flush()?;
|
||||
Ok::<_, std::io::Error>(port)
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(write_result) => write_result,
|
||||
Err(join_err) => Err(std::io::Error::other(join_err)),
|
||||
}
|
||||
}
|
||||
@@ -1,61 +1,77 @@
|
||||
//! Shared TCP socket tuning for [`crate::tcp`] and [`crate::backbone`].
|
||||
//! Shared TCP socket tuning for [`crate::tcp`], [`crate::backbone`],
|
||||
//! [`crate::i2p`], and [`crate::rnode`] (TCP transport).
|
||||
//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux
|
||||
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT.
|
||||
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT. All helpers are generic over
|
||||
//! the raw-fd/raw-socket borrow, so they accept tokio and std streams alike.
|
||||
//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key.
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
|
||||
/// Borrow the raw fd/socket as a `socket2::Socket` without taking ownership
|
||||
/// (`ManuallyDrop` keeps the destructor from closing it).
|
||||
#[cfg(unix)]
|
||||
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_ref().as_raw_fd();
|
||||
fn with_socket2<S: std::os::fd::AsRawFd, R>(
|
||||
stream: &S,
|
||||
f: impl FnOnce(&socket2::Socket) -> R,
|
||||
) -> R {
|
||||
use std::os::fd::FromRawFd;
|
||||
// SAFETY: we borrow the fd without taking ownership (ManuallyDrop ensures
|
||||
// the socket2::Socket destructor does not close the fd).
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
sock.set_keepalive(true)?;
|
||||
Ok(())
|
||||
let sock =
|
||||
std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(stream.as_raw_fd()) });
|
||||
f(&sock)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_ref().as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
sock.set_keepalive(true)?;
|
||||
Ok(())
|
||||
fn with_socket2<S: std::os::windows::io::AsRawSocket, R>(
|
||||
stream: &S,
|
||||
f: impl FnOnce(&socket2::Socket) -> R,
|
||||
) -> R {
|
||||
use std::os::windows::io::FromRawSocket;
|
||||
// SAFETY: same borrow-without-ownership contract as the unix variant.
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe {
|
||||
socket2::Socket::from_raw_socket(stream.as_raw_socket())
|
||||
});
|
||||
f(&sock)
|
||||
}
|
||||
|
||||
/// Platform bound for streams the tuning helpers accept: anything exposing
|
||||
/// the raw socket handle (tokio `TcpStream`, std `TcpStream`, …).
|
||||
#[cfg(unix)]
|
||||
pub trait RawStream: std::os::fd::AsRawFd {}
|
||||
#[cfg(unix)]
|
||||
impl<T: std::os::fd::AsRawFd> RawStream for T {}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub trait RawStream: std::os::windows::io::AsRawSocket {}
|
||||
#[cfg(windows)]
|
||||
impl<T: std::os::windows::io::AsRawSocket> RawStream for T {}
|
||||
|
||||
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
|
||||
pub fn set_keepalive<S: RawStream>(stream: &S) -> std::io::Result<()> {
|
||||
with_socket2(stream, |sock| sock.set_keepalive(true))
|
||||
}
|
||||
|
||||
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
|
||||
#[cfg(unix)]
|
||||
pub fn set_keepalive_tuned(
|
||||
stream: &TcpStream,
|
||||
pub fn set_keepalive_tuned<S: RawStream>(
|
||||
stream: &S,
|
||||
idle: Duration,
|
||||
intvl: Duration,
|
||||
retries: u32,
|
||||
user_timeout: Duration,
|
||||
) {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_ref().as_raw_fd();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
|
||||
with_socket2(stream, |sock| {
|
||||
apply_tuned_keepalive(sock, idle, intvl, retries, user_timeout)
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_keepalive_tuned(
|
||||
stream: &TcpStream,
|
||||
idle: Duration,
|
||||
intvl: Duration,
|
||||
retries: u32,
|
||||
user_timeout: Duration,
|
||||
) {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_ref().as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
|
||||
/// Raise TCP send/recv buffers; best-effort.
|
||||
pub fn set_socket_buffers<S: RawStream>(stream: &S, size: usize) {
|
||||
with_socket2(stream, |sock| {
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
});
|
||||
}
|
||||
|
||||
fn apply_tuned_keepalive(
|
||||
@@ -88,23 +104,24 @@ fn apply_tuned_keepalive(
|
||||
let _ = user_timeout;
|
||||
}
|
||||
|
||||
/// Raise TCP send/recv buffers; best-effort.
|
||||
#[cfg(unix)]
|
||||
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_ref().as_raw_fd();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_ref().as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
/// Resolve interface name to its IPv4 broadcast address; `None` if the
|
||||
/// interface is missing or has no broadcast-capable IPv4. Python UDP
|
||||
/// `device =` semantics (`get_broadcast_for_if`).
|
||||
pub fn iface_broadcast_for(name: &str) -> Option<std::net::Ipv4Addr> {
|
||||
let ifaces = match if_addrs::get_if_addrs() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
ifaces.into_iter().filter(|i| i.name == name).find_map(|i| {
|
||||
if let if_addrs::IfAddr::V4(v4) = i.addr {
|
||||
v4.broadcast
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
|
||||
@@ -143,7 +160,7 @@ pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
#[tokio::test]
|
||||
async fn keepalive_and_buffers_apply_without_panic() {
|
||||
@@ -177,6 +194,37 @@ mod tests {
|
||||
set_socket_buffers(&client, 131_072);
|
||||
}
|
||||
|
||||
/// The same generic helpers must accept blocking std streams.
|
||||
#[test]
|
||||
fn std_keepalive_and_buffers_apply_without_panic() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let accept = std::thread::spawn(move || listener.accept().unwrap().0);
|
||||
let client = std::net::TcpStream::connect(addr).unwrap();
|
||||
let server = accept.join().unwrap();
|
||||
|
||||
set_keepalive(&server).expect("server set_keepalive");
|
||||
set_keepalive(&client).expect("client set_keepalive");
|
||||
|
||||
set_keepalive_tuned(
|
||||
&server,
|
||||
Duration::from_secs(5),
|
||||
Duration::from_secs(2),
|
||||
12,
|
||||
Duration::from_secs(24),
|
||||
);
|
||||
set_keepalive_tuned(
|
||||
&client,
|
||||
Duration::from_secs(5),
|
||||
Duration::from_secs(2),
|
||||
12,
|
||||
Duration::from_secs(24),
|
||||
);
|
||||
|
||||
set_socket_buffers(&server, 131_072);
|
||||
set_socket_buffers(&client, 131_072);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iface_addr_for_loopback_resolves() {
|
||||
// Loopback name varies by OS; iterate candidates.
|
||||
|
||||
+166
-27
@@ -15,15 +15,27 @@ pub const RECONNECT_WAIT_INITIAL: u64 = 5;
|
||||
pub const RECONNECT_WAIT_MAX: u64 = 300;
|
||||
pub const DEFAULT_CONNECT_TIMEOUT: u64 = 5;
|
||||
pub const DEFAULT_TCP_USER_TIMEOUT: u32 = 24;
|
||||
/// I2P tunnels need a longer `TCP_USER_TIMEOUT` to absorb latency spikes.
|
||||
pub const I2P_TCP_USER_TIMEOUT: u32 = 45;
|
||||
|
||||
pub const TCP_HW_MTU: u32 = 262144;
|
||||
|
||||
// Python TCPClientInterface: TCP_PROBE_AFTER / TCP_PROBE_INTERVAL / TCP_PROBES.
|
||||
// Dead-peer detection: 5s idle + 12 probes × 2s ≈ 29s.
|
||||
pub const TCP_KEEPIDLE: u32 = 5;
|
||||
pub const TCP_KEEPINTVL: u32 = 2;
|
||||
pub const TCP_KEEPCNT: u32 = 12;
|
||||
|
||||
/// Tuned keepalive (idle/interval/count + Linux `TCP_USER_TIMEOUT`) for plain
|
||||
/// TCP client and accepted sockets, matching Python `set_timeouts_linux`.
|
||||
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream) {
|
||||
crate::socket_tuning::set_keepalive_tuned(
|
||||
stream,
|
||||
std::time::Duration::from_secs(TCP_KEEPIDLE as u64),
|
||||
std::time::Duration::from_secs(TCP_KEEPINTVL as u64),
|
||||
TCP_KEEPCNT,
|
||||
std::time::Duration::from_secs(DEFAULT_TCP_USER_TIMEOUT as u64),
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TcpClientConfig {
|
||||
pub name: String,
|
||||
@@ -33,6 +45,8 @@ pub struct TcpClientConfig {
|
||||
pub connect_timeout_secs: u64,
|
||||
pub max_reconnect_tries: Option<usize>,
|
||||
pub mode: InterfaceMode,
|
||||
/// Override HW MTU for link MTU discovery (Python `fixed_mtu`, >= 500).
|
||||
pub fixed_mtu: Option<u32>,
|
||||
}
|
||||
|
||||
impl TcpClientConfig {
|
||||
@@ -45,6 +59,7 @@ impl TcpClientConfig {
|
||||
connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT,
|
||||
max_reconnect_tries: None,
|
||||
mode: InterfaceMode::Full,
|
||||
fixed_mtu: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +72,9 @@ pub struct TcpServerConfig {
|
||||
pub kiss_framing: bool,
|
||||
pub prefer_ipv6: bool,
|
||||
pub mode: InterfaceMode,
|
||||
/// Bind to this network device's address instead of `listen_ip`
|
||||
/// (Python `device =` option).
|
||||
pub device: Option<String>,
|
||||
}
|
||||
|
||||
impl TcpServerConfig {
|
||||
@@ -68,10 +86,30 @@ impl TcpServerConfig {
|
||||
kiss_framing: false,
|
||||
prefer_ipv6: false,
|
||||
mode: InterfaceMode::Full,
|
||||
device: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// First usable address on `device`, honouring `prefer_ipv6`. Python
|
||||
/// `TCPServerInterface.get_address_for_if` equivalent.
|
||||
fn address_for_device(device: &str, prefer_ipv6: bool) -> Option<std::net::IpAddr> {
|
||||
let addrs = if_addrs::get_if_addrs().ok()?;
|
||||
let on_dev: Vec<std::net::IpAddr> = addrs
|
||||
.iter()
|
||||
.filter(|a| a.name == device)
|
||||
.map(|a| a.ip())
|
||||
.collect();
|
||||
if prefer_ipv6 && let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
|
||||
return Some(*v6);
|
||||
}
|
||||
on_dev
|
||||
.iter()
|
||||
.find(|ip| ip.is_ipv4())
|
||||
.or_else(|| on_dev.first())
|
||||
.copied()
|
||||
}
|
||||
|
||||
pub struct TcpInterfaceState {
|
||||
pub online: AtomicBool,
|
||||
pub detached: AtomicBool,
|
||||
@@ -86,28 +124,14 @@ pub struct TcpInterfaceState {
|
||||
|
||||
impl TcpInterfaceState {
|
||||
pub fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
online: AtomicBool::new(false),
|
||||
detached: AtomicBool::new(false),
|
||||
rx_bytes: AtomicU64::new(0),
|
||||
tx_bytes: AtomicU64::new(0),
|
||||
rx_packets: AtomicU64::new(0),
|
||||
tx_packets: AtomicU64::new(0),
|
||||
shared_rxb: None,
|
||||
shared_txb: None,
|
||||
})
|
||||
Arc::new(Self::default())
|
||||
}
|
||||
|
||||
pub fn with_shared_counters(rxb: Arc<AtomicU64>, txb: Arc<AtomicU64>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
online: AtomicBool::new(false),
|
||||
detached: AtomicBool::new(false),
|
||||
rx_bytes: AtomicU64::new(0),
|
||||
tx_bytes: AtomicU64::new(0),
|
||||
rx_packets: AtomicU64::new(0),
|
||||
tx_packets: AtomicU64::new(0),
|
||||
shared_rxb: Some(rxb),
|
||||
shared_txb: Some(txb),
|
||||
..Self::default()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -151,7 +175,7 @@ pub fn frame_for_tcp(data: &[u8], kiss_framing: bool) -> Vec<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
use crate::socket_tuning::{set_keepalive, set_socket_buffers};
|
||||
use crate::socket_tuning::set_socket_buffers;
|
||||
|
||||
async fn tcp_read_loop(
|
||||
mut reader: tokio::net::tcp::OwnedReadHalf,
|
||||
@@ -274,6 +298,7 @@ pub async fn spawn_tcp_client(
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let kiss_framing = config.kiss_framing;
|
||||
let fixed_mtu = config.fixed_mtu;
|
||||
|
||||
// Wrap rx so it survives reconnects; forwarder task feeds per-connection channel.
|
||||
let rx = Arc::new(tokio::sync::Mutex::new(rx));
|
||||
@@ -303,6 +328,11 @@ pub async fn spawn_tcp_client(
|
||||
tries += 1;
|
||||
if tries >= max {
|
||||
tracing::warn!(name = %config.name, "max reconnect tries reached");
|
||||
// Same dereg as the post-connect give-up below —
|
||||
// otherwise the actor keeps a zombie entry.
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -316,6 +346,9 @@ pub async fn spawn_tcp_client(
|
||||
tries += 1;
|
||||
if tries >= max {
|
||||
tracing::warn!(name = %config.name, "max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -325,9 +358,7 @@ pub async fn spawn_tcp_client(
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = set_keepalive(&stream) {
|
||||
tracing::debug!(error = %e, "failed to set TCP keepalive");
|
||||
}
|
||||
set_tcp_keepalive_tuned(&stream);
|
||||
|
||||
// Nagle off for low-latency packets; larger buffers for bulk transfers.
|
||||
let _ = stream.set_nodelay(true);
|
||||
@@ -391,6 +422,7 @@ pub async fn spawn_tcp_client(
|
||||
let bitrate: u64 = 10_000_000;
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -400,7 +432,8 @@ pub async fn spawn_tcp_client(
|
||||
repeat: false,
|
||||
},
|
||||
bitrate,
|
||||
mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU),
|
||||
mtu: fixed_mtu
|
||||
.unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU)),
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
@@ -419,6 +452,7 @@ pub async fn spawn_tcp_client(
|
||||
async fn spawn_tcp_accepted(
|
||||
stream: TcpStream,
|
||||
id: InterfaceId,
|
||||
parent_id: InterfaceId,
|
||||
name: String,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
kiss_framing: bool,
|
||||
@@ -433,9 +467,7 @@ async fn spawn_tcp_accepted(
|
||||
let state = TcpInterfaceState::with_shared_counters(shared_rxb.clone(), shared_txb.clone());
|
||||
state.online.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Err(e) = set_keepalive(&stream) {
|
||||
tracing::debug!(error = %e, "failed to set keepalive on accepted socket");
|
||||
}
|
||||
set_tcp_keepalive_tuned(&stream);
|
||||
let _ = stream.set_nodelay(true);
|
||||
set_socket_buffers(&stream, 131072);
|
||||
|
||||
@@ -459,6 +491,7 @@ async fn spawn_tcp_accepted(
|
||||
let bitrate: u64 = 10_000_000;
|
||||
InterfaceHandle {
|
||||
id,
|
||||
parent_id: Some(parent_id),
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -486,7 +519,17 @@ pub async fn spawn_tcp_server(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let addr = format!("{}:{}", config.listen_ip, config.listen_port);
|
||||
let addr = match config.device.as_deref() {
|
||||
Some(device) => {
|
||||
let ip = address_for_device(device, config.prefer_ipv6).ok_or_else(|| {
|
||||
crate::traits::InterfaceError::SendFailed(format!(
|
||||
"no usable address on device '{device}'"
|
||||
))
|
||||
})?;
|
||||
std::net::SocketAddr::new(ip, config.listen_port).to_string()
|
||||
}
|
||||
None => format!("{}:{}", config.listen_ip, config.listen_port),
|
||||
};
|
||||
let listener = TcpListener::bind(&addr).await?;
|
||||
let local_addr = listener.local_addr()?;
|
||||
tracing::info!(name = %config.name, addr = %local_addr, "TCP server listening");
|
||||
@@ -510,6 +553,7 @@ pub async fn spawn_tcp_server(
|
||||
let handle = spawn_tcp_accepted(
|
||||
stream,
|
||||
client_id,
|
||||
id,
|
||||
client_name,
|
||||
transport_tx.clone(),
|
||||
kiss_framing,
|
||||
@@ -533,6 +577,7 @@ pub async fn spawn_tcp_server(
|
||||
let bitrate: u64 = 10_000_000;
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -570,6 +615,97 @@ mod tests {
|
||||
assert!(!config.prefer_ipv6);
|
||||
}
|
||||
|
||||
/// T1-2 regression: the client/accept paths must apply the TUNED keepalive
|
||||
/// (idle 5s + 12 probes × 2s ≈ 29s dead-peer parity with Python), not just
|
||||
/// SO_KEEPALIVE. Reads the options back via getsockopt.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn tuned_keepalive_applies_python_probe_values() {
|
||||
use std::os::fd::AsRawFd;
|
||||
|
||||
fn get_opt(fd: i32, level: i32, name: i32) -> i32 {
|
||||
let mut val: libc::c_int = 0;
|
||||
let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
|
||||
let rc = unsafe {
|
||||
libc::getsockopt(
|
||||
fd,
|
||||
level,
|
||||
name,
|
||||
&mut val as *mut _ as *mut libc::c_void,
|
||||
&mut len,
|
||||
)
|
||||
};
|
||||
assert_eq!(rc, 0, "getsockopt({level},{name}) failed");
|
||||
val
|
||||
}
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (accepted, client) = tokio::join!(listener.accept(), TcpStream::connect(addr));
|
||||
let client = client.unwrap();
|
||||
let (server, _) = accepted.unwrap();
|
||||
|
||||
for stream in [&client, &server] {
|
||||
set_tcp_keepalive_tuned(stream);
|
||||
let fd = stream.as_ref().as_raw_fd();
|
||||
// BSD getsockopt returns the option bit, not 1 — assert enabled.
|
||||
assert_ne!(get_opt(fd, libc::SOL_SOCKET, libc::SO_KEEPALIVE), 0);
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE);
|
||||
#[cfg(target_os = "macos")]
|
||||
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE);
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
assert_eq!(idle, TCP_KEEPIDLE as i32);
|
||||
assert_eq!(
|
||||
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
|
||||
TCP_KEEPINTVL as i32
|
||||
);
|
||||
assert_eq!(
|
||||
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
|
||||
TCP_KEEPCNT as i32
|
||||
);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
assert_eq!(
|
||||
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT),
|
||||
(DEFAULT_TCP_USER_TIMEOUT * 1000) as i32
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// T1-11: exhausting max_reconnect_tries before the FIRST successful
|
||||
/// connect must send DeregisterInterface, same as the post-connect path —
|
||||
/// otherwise the actor keeps a zombie entry forever.
|
||||
#[tokio::test]
|
||||
async fn test_initial_connect_give_up_sends_deregister() {
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(8);
|
||||
|
||||
// Bind-then-drop: the port refuses connections immediately.
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
|
||||
let mut config = TcpClientConfig::new("tcp-giveup", &addr.ip().to_string(), addr.port());
|
||||
config.max_reconnect_tries = Some(1);
|
||||
config.connect_timeout_secs = 2;
|
||||
|
||||
let handle = spawn_tcp_client(config, 77, transport_tx, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let msg = tokio::time::timeout(std::time::Duration::from_secs(10), transport_rx.recv())
|
||||
.await
|
||||
.expect("expected DeregisterInterface before timeout")
|
||||
.expect("transport channel closed");
|
||||
match msg {
|
||||
TransportMessage::DeregisterInterface { id } => assert_eq!(id, 77),
|
||||
other => panic!("expected DeregisterInterface, got {other:?}"),
|
||||
}
|
||||
handle.read_task.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_frame_for_tcp_hdlc() {
|
||||
let data = b"test packet";
|
||||
@@ -629,6 +765,7 @@ mod tests {
|
||||
connect_timeout_secs: 5,
|
||||
max_reconnect_tries: Some(1),
|
||||
mode: InterfaceMode::Full,
|
||||
fixed_mtu: None,
|
||||
};
|
||||
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone(), None)
|
||||
.await
|
||||
@@ -713,6 +850,7 @@ mod tests {
|
||||
connect_timeout_secs: 1,
|
||||
max_reconnect_tries: Some(2),
|
||||
mode: InterfaceMode::Full,
|
||||
fixed_mtu: None,
|
||||
};
|
||||
|
||||
let handle = spawn_tcp_client(config, 99, transport_tx, None)
|
||||
@@ -756,6 +894,7 @@ mod tests {
|
||||
connect_timeout_secs: 5,
|
||||
max_reconnect_tries: Some(1),
|
||||
mode: InterfaceMode::Full,
|
||||
fixed_mtu: None,
|
||||
};
|
||||
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone(), None)
|
||||
.await
|
||||
|
||||
@@ -9,6 +9,9 @@ pub type InterfaceId = u64;
|
||||
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
|
||||
pub struct InterfaceHandle {
|
||||
pub id: InterfaceId,
|
||||
/// Parent interface for dynamically spawned children such as accepted TCP,
|
||||
/// Backbone or I2P peers.
|
||||
pub parent_id: Option<InterfaceId>,
|
||||
pub name: String,
|
||||
pub mode: InterfaceMode,
|
||||
pub direction: InterfaceDirection,
|
||||
@@ -79,50 +82,6 @@ pub struct InterfaceDirection {
|
||||
pub repeat: bool,
|
||||
}
|
||||
|
||||
/// Interface statistics.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct InterfaceStats {
|
||||
pub rx_bytes: u64,
|
||||
pub tx_bytes: u64,
|
||||
pub rx_packets: u64,
|
||||
pub tx_packets: u64,
|
||||
pub online: bool,
|
||||
pub bitrate: u64,
|
||||
pub mtu: u32,
|
||||
}
|
||||
|
||||
/// Base trait for all network interfaces.
|
||||
pub trait Interface: Send + Sync {
|
||||
fn process_incoming(&self, data: &[u8]);
|
||||
|
||||
fn process_outgoing(&self, data: &[u8]) -> Result<(), InterfaceError>;
|
||||
|
||||
fn get_stats(&self) -> InterfaceStats;
|
||||
|
||||
fn detach(&mut self);
|
||||
|
||||
fn name(&self) -> &str;
|
||||
|
||||
fn mode(&self) -> InterfaceMode;
|
||||
|
||||
/// Interface bitrate in bits/sec.
|
||||
fn bitrate(&self) -> u64;
|
||||
|
||||
fn mtu(&self) -> u32 {
|
||||
rns_wire::constants::MTU as u32
|
||||
}
|
||||
|
||||
fn online(&self) -> bool;
|
||||
|
||||
/// 16-byte interface identifier: truncated SHA-256 of the interface name.
|
||||
fn get_hash(&self) -> [u8; 16] {
|
||||
let full = rns_crypto::sha::full_hash(self.name().as_bytes());
|
||||
let mut h = [0u8; 16];
|
||||
h.copy_from_slice(&full[..16]);
|
||||
h
|
||||
}
|
||||
}
|
||||
|
||||
/// Select an MTU for the given bitrate; `None` below 62.5 kbps minimum.
|
||||
pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
|
||||
if bitrate >= 1_000_000_000 {
|
||||
@@ -154,21 +113,39 @@ pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
|
||||
pub const NAME_HASH_LENGTH: usize = 10;
|
||||
|
||||
// Ingress control constants — must match Reticulum reference.
|
||||
pub const IA_FREQ_SAMPLES: usize = 128;
|
||||
pub const OA_FREQ_SAMPLES: usize = 128;
|
||||
pub const IA_FREQ_SAMPLES: usize = 48;
|
||||
pub const OA_FREQ_SAMPLES: usize = 48;
|
||||
pub const IP_FREQ_SAMPLES: usize = 48;
|
||||
pub const OP_FREQ_SAMPLES: usize = 48;
|
||||
pub const AR_MINFREQ_HZ: f64 = 0.1;
|
||||
pub const PR_MINFREQ_HZ: f64 = 0.1;
|
||||
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
|
||||
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
|
||||
pub const MAX_HELD_ANNOUNCES: usize = 256;
|
||||
/// Duration a new interface stays in "new" state (seconds).
|
||||
pub const IC_NEW_TIME: f64 = 7200.0;
|
||||
/// Burst threshold for new interfaces (announces/sec).
|
||||
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
|
||||
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
|
||||
/// Burst threshold for established interfaces (announces/sec).
|
||||
pub const IC_BURST_FREQ: f64 = 35.0;
|
||||
pub const IC_BURST_FREQ: f64 = 10.0;
|
||||
/// Burst threshold for new interfaces (path requests/sec).
|
||||
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
|
||||
/// Burst threshold for established interfaces (path requests/sec).
|
||||
pub const IC_PR_BURST_FREQ: f64 = 8.0;
|
||||
/// Burst detection window duration (seconds).
|
||||
pub const IC_BURST_HOLD: f64 = 60.0;
|
||||
pub const IC_BURST_HOLD: f64 = 15.0;
|
||||
/// Penalty duration after a detected burst (seconds).
|
||||
pub const IC_BURST_PENALTY: f64 = 15.0;
|
||||
/// Interval between released held announces (seconds).
|
||||
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
|
||||
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
|
||||
/// Minimum samples required before incoming frequency is considered defined.
|
||||
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
|
||||
/// Minimum samples required for burst clearing / PR egress limiting.
|
||||
pub const IC_BURST_MIN_SAMPLES: usize = 6;
|
||||
/// Optional outgoing path-request limiter threshold (requests/sec).
|
||||
pub const EC_PR_FREQ: f64 = 5.0;
|
||||
/// Whether outgoing path-request limiting is active by default.
|
||||
pub const EGRESS_CONTROL: bool = false;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum InterfaceError {
|
||||
@@ -239,13 +216,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_ingress_control_constants() {
|
||||
assert_eq!(IA_FREQ_SAMPLES, 128);
|
||||
assert_eq!(OA_FREQ_SAMPLES, 128);
|
||||
assert_eq!(IC_BURST_FREQ, 35.0);
|
||||
assert_eq!(IC_BURST_FREQ_NEW, 6.0);
|
||||
assert_eq!(IC_BURST_HOLD, 60.0);
|
||||
assert_eq!(IA_FREQ_SAMPLES, 48);
|
||||
assert_eq!(OA_FREQ_SAMPLES, 48);
|
||||
assert_eq!(IP_FREQ_SAMPLES, 48);
|
||||
assert_eq!(OP_FREQ_SAMPLES, 48);
|
||||
assert_eq!(AR_MINFREQ_HZ, 0.1);
|
||||
assert_eq!(PR_MINFREQ_HZ, 0.1);
|
||||
assert_eq!(AR_FREQ_DECAY, 10.0);
|
||||
assert_eq!(PR_FREQ_DECAY, 10.0);
|
||||
assert_eq!(IC_BURST_FREQ, 10.0);
|
||||
assert_eq!(IC_BURST_FREQ_NEW, 3.0);
|
||||
assert_eq!(IC_PR_BURST_FREQ, 8.0);
|
||||
assert_eq!(IC_PR_BURST_FREQ_NEW, 3.0);
|
||||
assert_eq!(IC_BURST_HOLD, 15.0);
|
||||
assert_eq!(IC_BURST_PENALTY, 15.0);
|
||||
assert_eq!(IC_NEW_TIME, 7200.0);
|
||||
assert_eq!(IC_HELD_RELEASE_INTERVAL, 2.0);
|
||||
assert_eq!(IC_HELD_RELEASE_INTERVAL, 5.0);
|
||||
assert_eq!(IC_DEQUE_MIN_SAMPLE, 2);
|
||||
assert_eq!(IC_BURST_MIN_SAMPLES, 6);
|
||||
assert_eq!(EC_PR_FREQ, 5.0);
|
||||
const { assert!(!EGRESS_CONTROL) };
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,28 @@ pub async fn spawn_udp_interface(
|
||||
id: InterfaceId,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let listen_ip = config.listen_ip.as_deref().unwrap_or("0.0.0.0");
|
||||
// Python UDPInterface `device =`: fill unset listen/forward IPs with the
|
||||
// NIC's IPv4 broadcast address; a device that can't be resolved is a
|
||||
// config error, not a silent fallback to wildcard.
|
||||
let mut listen_ip_cfg = config.listen_ip.clone();
|
||||
let mut forward_ip_cfg = config.forward_ip.clone();
|
||||
if let Some(device) = config.device.as_deref() {
|
||||
if listen_ip_cfg.is_none() || forward_ip_cfg.is_none() {
|
||||
let bcast = crate::socket_tuning::iface_broadcast_for(device).ok_or_else(|| {
|
||||
crate::traits::InterfaceError::SendFailed(format!(
|
||||
"UDP device '{device}' not found or has no IPv4 broadcast address"
|
||||
))
|
||||
})?;
|
||||
if listen_ip_cfg.is_none() {
|
||||
listen_ip_cfg = Some(bcast.to_string());
|
||||
}
|
||||
if forward_ip_cfg.is_none() {
|
||||
forward_ip_cfg = Some(bcast.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let listen_ip = listen_ip_cfg.as_deref().unwrap_or("0.0.0.0");
|
||||
let listen_port = config.listen_port.unwrap_or(0);
|
||||
let bind_addr = format!("{}:{}", listen_ip, listen_port);
|
||||
let socket = Arc::new(UdpSocket::bind(&bind_addr).await?);
|
||||
@@ -73,7 +94,7 @@ pub async fn spawn_udp_interface(
|
||||
let task_rxb = shared_rxb.clone();
|
||||
let task_txb = shared_txb.clone();
|
||||
|
||||
let forward_addr: Option<SocketAddr> = match (&config.forward_ip, config.forward_port) {
|
||||
let forward_addr: Option<SocketAddr> = match (&forward_ip_cfg, config.forward_port) {
|
||||
(Some(ip), Some(port)) => {
|
||||
let addr_str = format!("{}:{}", ip, port);
|
||||
match addr_str.parse() {
|
||||
@@ -145,6 +166,7 @@ pub async fn spawn_udp_interface(
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode,
|
||||
direction: InterfaceDirection {
|
||||
@@ -184,6 +206,38 @@ mod tests {
|
||||
assert_eq!(HW_MTU, 1064);
|
||||
}
|
||||
|
||||
/// T1-11: `device =` was parsed then silently ignored. A device that
|
||||
/// cannot be resolved must now fail the spawn with a clear error.
|
||||
#[tokio::test]
|
||||
async fn test_udp_device_unresolvable_errors() {
|
||||
let (transport_tx, _rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let mut cfg = UdpInterfaceConfig::new("udp-dev");
|
||||
cfg.device = Some("definitely-not-a-real-interface-zzz".to_string());
|
||||
let err = match spawn_udp_interface(cfg, 1, transport_tx).await {
|
||||
Err(e) => e,
|
||||
Ok(_) => panic!("unresolvable device must error"),
|
||||
};
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("definitely-not-a-real-interface-zzz")
|
||||
);
|
||||
}
|
||||
|
||||
/// Explicit listen/forward IPs take precedence — the device is not
|
||||
/// resolved at all, so the spawn succeeds regardless of the NIC name.
|
||||
#[tokio::test]
|
||||
async fn test_udp_device_ignored_when_ips_explicit() {
|
||||
let (transport_tx, _rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let mut cfg = UdpInterfaceConfig::new("udp-dev-explicit")
|
||||
.listen("127.0.0.1", 0)
|
||||
.forward("127.0.0.1", 19999);
|
||||
cfg.device = Some("definitely-not-a-real-interface-zzz".to_string());
|
||||
let handle = spawn_udp_interface(cfg, 2, transport_tx)
|
||||
.await
|
||||
.expect("explicit IPs bypass device resolution");
|
||||
handle.read_task.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_udp_config_defaults() {
|
||||
let cfg = UdpInterfaceConfig::new("udp0");
|
||||
|
||||
@@ -149,6 +149,17 @@ mod tests {
|
||||
use super::*;
|
||||
use std::thread;
|
||||
|
||||
fn instant_before_now(elapsed: Duration) -> Instant {
|
||||
if let Some(instant) = Instant::now().checked_sub(elapsed) {
|
||||
instant
|
||||
} else {
|
||||
thread::sleep(elapsed);
|
||||
Instant::now()
|
||||
.checked_sub(elapsed)
|
||||
.expect("elapsed duration should be representable after waiting")
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtt_scaling() {
|
||||
let mut ks = KeepaliveState::new(true);
|
||||
@@ -225,11 +236,13 @@ mod tests {
|
||||
#[test]
|
||||
fn test_jitter_desynchronizes_keepalives() {
|
||||
let links: Vec<KeepaliveState> = (0..20)
|
||||
.map(|_| {
|
||||
.map(|i| {
|
||||
let mut ks = KeepaliveState::new(true);
|
||||
ks.update_from_rtt(Duration::from_millis(500));
|
||||
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
|
||||
ks.jitter_offset = Duration::from_millis(500);
|
||||
ks.jitter_negative = i % 2 == 0;
|
||||
// Push last_inbound just past the interval boundary.
|
||||
ks.last_inbound = Instant::now() - ks.keepalive_interval;
|
||||
ks.last_inbound = instant_before_now(ks.keepalive_interval);
|
||||
ks
|
||||
})
|
||||
.collect();
|
||||
@@ -237,10 +250,12 @@ mod tests {
|
||||
let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count();
|
||||
|
||||
let links_past: Vec<KeepaliveState> = (0..20)
|
||||
.map(|_| {
|
||||
.map(|i| {
|
||||
let mut ks = KeepaliveState::new(true);
|
||||
ks.update_from_rtt(Duration::from_millis(500));
|
||||
ks.last_inbound = Instant::now() - ks.keepalive_interval * 2;
|
||||
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
|
||||
ks.jitter_offset = Duration::from_millis(500);
|
||||
ks.jitter_negative = i % 2 == 0;
|
||||
ks.last_inbound = instant_before_now(Duration::from_secs(6));
|
||||
ks
|
||||
})
|
||||
.collect();
|
||||
|
||||
+93
-55
@@ -385,6 +385,49 @@ impl Link {
|
||||
destination_hash: [u8; 16],
|
||||
hops: u8,
|
||||
) -> Result<(Self, Vec<u8>), HandshakeError> {
|
||||
let identity_ed25519_pub = identity_signing_key.public_key().to_bytes();
|
||||
Self::new_responder_inner(
|
||||
request_data,
|
||||
&identity_ed25519_pub,
|
||||
destination_hash,
|
||||
hops,
|
||||
Some(identity_signing_key),
|
||||
|signed_data| Some(identity_signing_key.sign(signed_data)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Create an inbound link proof using an external signer (e.g. YubiKey/PIV).
|
||||
pub fn new_responder_with<F>(
|
||||
request_data: &[u8],
|
||||
identity_ed25519_pub: &[u8; 32],
|
||||
destination_hash: [u8; 16],
|
||||
hops: u8,
|
||||
sign_fn: F,
|
||||
) -> Result<(Self, Vec<u8>), HandshakeError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
Self::new_responder_inner(
|
||||
request_data,
|
||||
identity_ed25519_pub,
|
||||
destination_hash,
|
||||
hops,
|
||||
None,
|
||||
sign_fn,
|
||||
)
|
||||
}
|
||||
|
||||
fn new_responder_inner<F>(
|
||||
request_data: &[u8],
|
||||
identity_ed25519_pub: &[u8; 32],
|
||||
destination_hash: [u8; 16],
|
||||
hops: u8,
|
||||
identity_signing_key: Option<&Ed25519PrivateKey>,
|
||||
sign_fn: F,
|
||||
) -> Result<(Self, Vec<u8>), HandshakeError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
let request = LinkRequestData::unpack(request_data)?;
|
||||
let link_id = compute_link_id(&destination_hash, request_data);
|
||||
|
||||
@@ -404,16 +447,21 @@ impl Link {
|
||||
|
||||
// The proof binds the link to the responder's long-term identity key, not
|
||||
// its ephemeral one — that's what lets the initiator authenticate us.
|
||||
let identity_ed25519_pub = identity_signing_key.public_key().to_bytes();
|
||||
let signalling =
|
||||
SignallingData::new(request.signalling.mode, rns_wire::constants::MTU as u32);
|
||||
let proof = LinkProofData::create(
|
||||
identity_signing_key,
|
||||
&responder_keys.x25519_pub.to_bytes(),
|
||||
&identity_ed25519_pub,
|
||||
&link_id,
|
||||
let responder_x25519_pub = responder_keys.x25519_pub.to_bytes();
|
||||
let sig_bytes = signalling.pack();
|
||||
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
|
||||
signed_data.extend_from_slice(&link_id);
|
||||
signed_data.extend_from_slice(&responder_x25519_pub);
|
||||
signed_data.extend_from_slice(identity_ed25519_pub);
|
||||
signed_data.extend_from_slice(&sig_bytes);
|
||||
let signature = sign_fn(&signed_data).ok_or(HandshakeError::InvalidSignature)?;
|
||||
let proof = LinkProofData {
|
||||
signature,
|
||||
responder_x25519_pub,
|
||||
signalling,
|
||||
);
|
||||
};
|
||||
let proof_data = proof.pack();
|
||||
|
||||
let timeout_secs = ESTABLISHMENT_TIMEOUT_PER_HOP * (hops.max(1) as f64) + KEEPALIVE_DEFAULT;
|
||||
@@ -429,9 +477,7 @@ impl Link {
|
||||
ephemeral_keys: Some(responder_keys),
|
||||
peer_x25519_pub: Some(request.peer_x25519_pub),
|
||||
peer_ed25519_pub: Some(request.peer_ed25519_pub),
|
||||
sig_prv: Some(Ed25519PrivateKey::from_bytes(
|
||||
&identity_signing_key.to_bytes(),
|
||||
)),
|
||||
sig_prv: identity_signing_key.map(|key| Ed25519PrivateKey::from_bytes(&key.to_bytes())),
|
||||
session_keys: Some(session_keys),
|
||||
request_time: now,
|
||||
rtt: None,
|
||||
@@ -538,21 +584,9 @@ impl Link {
|
||||
identity_pub_key: &[u8; 64],
|
||||
identity_signing_key: &Ed25519PrivateKey,
|
||||
) -> Result<Vec<u8>, LinkCryptoError> {
|
||||
if !self.is_initiator || self.state != LinkState::Active {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
}
|
||||
|
||||
let mut signed_data = Vec::with_capacity(16 + 64);
|
||||
signed_data.extend_from_slice(&self.link_id);
|
||||
signed_data.extend_from_slice(identity_pub_key);
|
||||
|
||||
let signature = identity_signing_key.sign(&signed_data);
|
||||
|
||||
let mut proof_data = Vec::with_capacity(128);
|
||||
proof_data.extend_from_slice(identity_pub_key);
|
||||
proof_data.extend_from_slice(&signature);
|
||||
|
||||
self.encrypt(&proof_data)
|
||||
self.identify_with_fallible(identity_pub_key, |message| {
|
||||
Some(identity_signing_key.sign(message))
|
||||
})
|
||||
}
|
||||
|
||||
/// Identify with an external signer (e.g. hardware identity).
|
||||
@@ -565,6 +599,18 @@ impl Link {
|
||||
) -> Result<Vec<u8>, LinkCryptoError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> [u8; 64],
|
||||
{
|
||||
self.identify_with_fallible(identity_pub_key, |message| Some(sign_fn(message)))
|
||||
}
|
||||
|
||||
/// Identify with an external signer that can be unavailable.
|
||||
pub fn identify_with_fallible<F>(
|
||||
&self,
|
||||
identity_pub_key: &[u8; 64],
|
||||
sign_fn: F,
|
||||
) -> Result<Vec<u8>, LinkCryptoError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
if !self.is_initiator || self.state != LinkState::Active {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
@@ -574,7 +620,7 @@ impl Link {
|
||||
signed_data.extend_from_slice(&self.link_id);
|
||||
signed_data.extend_from_slice(identity_pub_key);
|
||||
|
||||
let signature = sign_fn(&signed_data);
|
||||
let signature = sign_fn(&signed_data).ok_or(LinkCryptoError::EncryptionFailed)?;
|
||||
|
||||
let mut proof_data = Vec::with_capacity(128);
|
||||
proof_data.extend_from_slice(identity_pub_key);
|
||||
@@ -878,17 +924,7 @@ impl Link {
|
||||
packet_hash: &[u8; 32],
|
||||
identity_signing_key: &Ed25519PrivateKey,
|
||||
) -> Result<Vec<u8>, LinkCryptoError> {
|
||||
if self.state != LinkState::Active && self.state != LinkState::Stale {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
}
|
||||
|
||||
let signature = identity_signing_key.sign(packet_hash);
|
||||
|
||||
let mut proof = Vec::with_capacity(96);
|
||||
proof.extend_from_slice(packet_hash);
|
||||
proof.extend_from_slice(&signature);
|
||||
|
||||
Ok(proof)
|
||||
self.prove_packet_with_fallible(packet_hash, |hash| Some(identity_signing_key.sign(hash)))
|
||||
}
|
||||
|
||||
/// Sign a received link packet with this link's ephemeral signing key.
|
||||
@@ -899,23 +935,13 @@ impl Link {
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
) -> Result<Vec<u8>, LinkCryptoError> {
|
||||
if self.state != LinkState::Active && self.state != LinkState::Stale {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
}
|
||||
|
||||
let signature = if let Some(signature) = self.sign(packet_hash) {
|
||||
signature
|
||||
} else if let Some(ephemeral_keys) = self.ephemeral_keys.as_ref() {
|
||||
ephemeral_keys.ed25519_prv.sign(packet_hash)
|
||||
} else {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
};
|
||||
|
||||
let mut proof = Vec::with_capacity(96);
|
||||
proof.extend_from_slice(packet_hash);
|
||||
proof.extend_from_slice(&signature);
|
||||
|
||||
Ok(proof)
|
||||
self.prove_packet_with_fallible(packet_hash, |hash| {
|
||||
self.sign(hash).or_else(|| {
|
||||
self.ephemeral_keys
|
||||
.as_ref()
|
||||
.map(|keys| keys.ed25519_prv.sign(hash))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Variant of [`Link::prove_packet`] for external signers.
|
||||
@@ -926,12 +952,24 @@ impl Link {
|
||||
) -> Result<Vec<u8>, LinkCryptoError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> [u8; 64],
|
||||
{
|
||||
self.prove_packet_with_fallible(packet_hash, |hash| Some(sign_fn(hash)))
|
||||
}
|
||||
|
||||
/// Variant of [`Link::prove_packet_with`] for signers that can be unavailable.
|
||||
pub fn prove_packet_with_fallible<F>(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
sign_fn: F,
|
||||
) -> Result<Vec<u8>, LinkCryptoError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
if self.state != LinkState::Active && self.state != LinkState::Stale {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
}
|
||||
|
||||
let signature = sign_fn(packet_hash);
|
||||
let signature = sign_fn(packet_hash).ok_or(LinkCryptoError::EncryptionFailed)?;
|
||||
|
||||
let mut proof = Vec::with_capacity(96);
|
||||
proof.extend_from_slice(packet_hash);
|
||||
|
||||
@@ -571,6 +571,16 @@ impl InboundResource {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
// `total_parts` is attacker-controlled wire input; unchecked it sizes the
|
||||
// parts Vec directly (24 B per slot — a remote multi-GB alloc bomb). Real
|
||||
// transfers satisfy total_parts == ceil(total_size / sdu); MIN_PART_SIZE
|
||||
// is a generous lower bound on any negotiated SDU (real MDU ≈ 475).
|
||||
const MIN_PART_SIZE: usize = 32;
|
||||
let max_parts = total_size.div_ceil(MIN_PART_SIZE).saturating_add(16);
|
||||
if total_parts > max_parts {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
state: ResourceState::Transferring,
|
||||
parts: vec![None; total_parts],
|
||||
@@ -1253,6 +1263,7 @@ pub struct OutboundTransfer {
|
||||
/// Scopes the search range when servicing RESOURCE_REQ lookups.
|
||||
pub receiver_min_consecutive_height: usize,
|
||||
pub sent_parts: usize,
|
||||
sent_part_indices: HashSet<usize>,
|
||||
req_hashlist: HashSet<[u8; 32]>,
|
||||
}
|
||||
|
||||
@@ -1301,6 +1312,7 @@ impl OutboundTransfer {
|
||||
window_max_sent: 0,
|
||||
receiver_min_consecutive_height: 0,
|
||||
sent_parts: 0,
|
||||
sent_part_indices: HashSet::new(),
|
||||
req_hashlist: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -1351,6 +1363,9 @@ impl OutboundTransfer {
|
||||
if let Some(part_data) = part_data {
|
||||
self.last_part_sent = Some(Instant::now());
|
||||
self.resource.state = ResourceState::Transferring;
|
||||
if self.sent_part_indices.insert(part_idx) {
|
||||
self.sent_parts += 1;
|
||||
}
|
||||
|
||||
if self.window_cursor >= window_end {
|
||||
// Last part in the window is now in flight; stop
|
||||
@@ -1548,6 +1563,9 @@ impl OutboundTransfer {
|
||||
{
|
||||
if let Some(part_data) = self.resource.get_part(i) {
|
||||
actions.push(TransferAction::SendPart(i, part_data.to_vec()));
|
||||
if self.sent_part_indices.insert(i) {
|
||||
self.sent_parts += 1;
|
||||
}
|
||||
sent_count += 1;
|
||||
}
|
||||
}
|
||||
@@ -1736,13 +1754,16 @@ impl OutboundTransfer {
|
||||
buf
|
||||
}
|
||||
|
||||
/// Fraction of parts confirmed, in `0.0..=1.0`.
|
||||
/// Fraction of unique parts transmitted, in `0.0..=1.0`.
|
||||
///
|
||||
/// Upstream Reticulum reports initiator-side progress from `sent_parts`,
|
||||
/// while receiver HMUs/proofs still decide completion. This keeps UI
|
||||
/// progress useful on large resources before a full segment proof arrives.
|
||||
pub fn progress(&self) -> f64 {
|
||||
let confirmed = self.confirmed_parts.iter().filter(|&&c| c).count();
|
||||
if self.resource.num_parts() == 0 {
|
||||
return 1.0;
|
||||
}
|
||||
confirmed as f64 / self.resource.num_parts() as f64
|
||||
self.sent_parts.min(self.resource.num_parts()) as f64 / self.resource.num_parts() as f64
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2104,10 +2125,19 @@ impl InboundTransfer {
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
|
||||
// Parse hashes from the hashmap data and insert into our map_hashes
|
||||
// Parse hashes from the hashmap data and insert into our map_hashes.
|
||||
// `segment` is wire-supplied: indices are bounded by total_parts
|
||||
// (Python preallocates hashmap to total_parts, so out-of-range
|
||||
// writes are impossible there) — anything beyond is hostile.
|
||||
let hashes_count = hashmap_data.len() / MAPHASH_LEN;
|
||||
for i in 0..hashes_count {
|
||||
let idx = i + segment * hashmap_max_len;
|
||||
let idx = match segment
|
||||
.checked_mul(hashmap_max_len)
|
||||
.and_then(|base| base.checked_add(i))
|
||||
{
|
||||
Some(idx) if idx < self.resource.total_parts => idx,
|
||||
_ => break,
|
||||
};
|
||||
let start = i * MAPHASH_LEN;
|
||||
let end = start + MAPHASH_LEN;
|
||||
if end <= hashmap_data.len() {
|
||||
@@ -2750,6 +2780,54 @@ mod tests {
|
||||
assert_eq!(proof.len(), 64); // resource_hash(32) + expected_proof(32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inbound_rejects_part_count_inconsistent_with_size() {
|
||||
// AF-2026-04.1: wire-controlled num_parts must not size the parts Vec
|
||||
// unchecked — total_size=1024 with 10M parts is a ~240 MB alloc bomb.
|
||||
let result = InboundTransfer::from_advertisement(
|
||||
10_000_000,
|
||||
1024,
|
||||
1000,
|
||||
[0xAA; RANDOM_HASH_SIZE],
|
||||
[0xBB; 32],
|
||||
ResourceFlags::default(),
|
||||
Vec::new(),
|
||||
Duration::from_millis(100),
|
||||
);
|
||||
assert!(matches!(result, Err(ResourceError::TooLarge)));
|
||||
|
||||
// Same bound at the InboundResource layer directly.
|
||||
let result = InboundResource::new(
|
||||
usize::MAX,
|
||||
1024,
|
||||
1000,
|
||||
[0xAA; RANDOM_HASH_SIZE],
|
||||
[0xBB; 32],
|
||||
ResourceFlags::default(),
|
||||
Vec::new(),
|
||||
);
|
||||
assert!(matches!(result, Err(ResourceError::TooLarge)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inbound_accepts_max_legitimate_part_count() {
|
||||
// Worst legitimate case: max-size transfer split at the real SDU.
|
||||
let max_total_size =
|
||||
MAX_EFFICIENT_SIZE + RANDOM_HASH_SIZE + rns_crypto::TOKEN_OVERHEAD + 16;
|
||||
let parts = max_total_size.div_ceil(SDU);
|
||||
let result = InboundResource::new(
|
||||
parts,
|
||||
max_total_size,
|
||||
MAX_EFFICIENT_SIZE,
|
||||
[0xAA; RANDOM_HASH_SIZE],
|
||||
[0xBB; 32],
|
||||
ResourceFlags::default(),
|
||||
Vec::new(),
|
||||
);
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap().total_parts, parts);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inbound_transfer_hmu_generation() {
|
||||
let data = vec![0u8; 2000]; // Multiple parts
|
||||
@@ -2821,6 +2899,55 @@ mod tests {
|
||||
assert_eq!(transfer.progress(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transfer_progress_tracks_unique_sent_parts() {
|
||||
let data = vec![0x55; SDU * 2 + 100];
|
||||
let mut sender =
|
||||
OutboundTransfer::new(data.clone(), false, Duration::from_millis(50)).unwrap();
|
||||
assert!(sender.resource.num_parts() > 1);
|
||||
|
||||
assert!(matches!(
|
||||
sender.tick(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
|
||||
let first_progress = match sender.tick() {
|
||||
TransferAction::SendPart(_, _) => sender.progress(),
|
||||
other => panic!("expected first part, got {other:?}"),
|
||||
};
|
||||
assert!(first_progress > 0.0);
|
||||
assert!(first_progress < 1.0);
|
||||
|
||||
let mut receiver = InboundTransfer::from_advertisement(
|
||||
sender.resource.num_parts(),
|
||||
sender.resource.total_size,
|
||||
data.len(),
|
||||
sender.resource.random_hash,
|
||||
sender.resource.resource_hash,
|
||||
ResourceFlags {
|
||||
compressed: false,
|
||||
..Default::default()
|
||||
},
|
||||
sender.resource.map_hashes.clone(),
|
||||
Duration::from_millis(50),
|
||||
)
|
||||
.unwrap();
|
||||
let TransferAction::SendRequest(request) = receiver.request_next() else {
|
||||
panic!("expected receiver request");
|
||||
};
|
||||
|
||||
let first_count = sender.sent_parts;
|
||||
let _ = sender.handle_request(&request);
|
||||
let after_request = sender.sent_parts;
|
||||
let _ = sender.handle_request(&request);
|
||||
|
||||
assert!(after_request >= first_count);
|
||||
assert_eq!(
|
||||
sender.sent_parts, after_request,
|
||||
"duplicate requests must not inflate visible send progress"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_full_transfer_roundtrip() {
|
||||
// Simulate a complete transfer: sender → receiver
|
||||
@@ -4023,6 +4150,80 @@ mod tests {
|
||||
assert!(matches!(action, TransferAction::SendRequest(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hashmap_update_rejects_out_of_range_segment() {
|
||||
// Wire-supplied `segment` must not grow map_hashes past total_parts.
|
||||
let data = vec![0u8; 2000];
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let total_parts = outbound.num_parts();
|
||||
|
||||
let mut inbound = InboundTransfer::from_advertisement(
|
||||
total_parts,
|
||||
outbound.total_size,
|
||||
data.len(),
|
||||
outbound.random_hash,
|
||||
outbound.resource_hash,
|
||||
ResourceFlags {
|
||||
compressed: false,
|
||||
..Default::default()
|
||||
},
|
||||
outbound.map_hashes[..2].to_vec(),
|
||||
Duration::from_millis(100),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Hostile segment index: would previously push ~segment*74 zero
|
||||
// entries into map_hashes. Must be ignored without growth or panic.
|
||||
inbound.hashmap_update(1_000_000, &outbound.map_hashes[0]);
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
|
||||
// Overflowing segment*hashmap_max_len must not panic either.
|
||||
inbound.hashmap_update(usize::MAX, &outbound.map_hashes[0]);
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hashmap_update_second_segment_bounded_by_total_parts() {
|
||||
// Resource large enough that its hashmap spans >1 segment: segment 1
|
||||
// writes land, but never past total_parts even if overfull.
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let data = vec![0xCD; (hashmap_max_len + 12) * SDU];
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let total_parts = outbound.num_parts();
|
||||
assert!(total_parts > hashmap_max_len);
|
||||
|
||||
let mut inbound = InboundTransfer::from_advertisement(
|
||||
total_parts,
|
||||
outbound.total_size,
|
||||
data.len(),
|
||||
outbound.random_hash,
|
||||
outbound.resource_hash,
|
||||
ResourceFlags {
|
||||
compressed: false,
|
||||
..Default::default()
|
||||
},
|
||||
outbound.map_hashes[..hashmap_max_len].to_vec(),
|
||||
Duration::from_millis(100),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Segment 1 carrying a deliberately overfull hash list: valid tail
|
||||
// entries land, writes stop exactly at total_parts.
|
||||
let mut overfull = Vec::new();
|
||||
for i in hashmap_max_len..total_parts {
|
||||
overfull.extend_from_slice(&outbound.map_hashes[i]);
|
||||
}
|
||||
overfull.extend_from_slice(&[0xEE; MAPHASH_LEN * 8]);
|
||||
inbound.hashmap_update(1, &overfull);
|
||||
|
||||
assert_eq!(inbound.resource.map_hashes.len(), total_parts);
|
||||
assert_eq!(
|
||||
inbound.resource.map_hashes[total_parts - 1],
|
||||
outbound.map_hashes[total_parts - 1]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_full_transfer_with_request_next() {
|
||||
// Full transfer using the request_next mechanism instead of
|
||||
|
||||
@@ -14,12 +14,31 @@ thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
zeroize = { workspace = true }
|
||||
aes = { workspace = true }
|
||||
des = { workspace = true }
|
||||
toml = "0.8"
|
||||
|
||||
# X.509 attestation-chain verification (always compiled, not behind `hardware`).
|
||||
x509-cert = { version = "0.2", features = ["pem"] }
|
||||
rsa = "0.9"
|
||||
# `oid` feature: lets RSA PKCS#1 v1.5 VerifyingKey<Sha256/Sha512> build the DigestInfo prefix.
|
||||
sha2 = { workspace = true, features = ["oid"] }
|
||||
der = "0.7"
|
||||
const-oid = "0.9"
|
||||
|
||||
# BIP-39 recoverable backup: 12-word mnemonic -> deterministic Reticulum identity.
|
||||
bip39 = "2"
|
||||
hkdf = "0.12"
|
||||
|
||||
[dev-dependencies]
|
||||
rns-crypto = { workspace = true, features = ["std"] }
|
||||
rns-identity = { workspace = true }
|
||||
rns-link = { path = "../rns-link" }
|
||||
rns-link = { workspace = true }
|
||||
# Synthetic-chain test fixtures.
|
||||
x509-cert = { version = "0.2", features = ["pem", "builder"] }
|
||||
# `sha2` feature provides RsaSignatureAssociatedOid for the cert builder's signer.
|
||||
rsa = { version = "0.9", features = ["sha2"] }
|
||||
rand = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@@ -1,21 +1,122 @@
|
||||
# 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.
|
||||
RatKey hardware identity support is **desktop only** and experimental. The full
|
||||
desktop path is validated on a real YubiKey (5.7.4): provision (recoverable /
|
||||
hardware-only / import / restore), on-card sign + ECDH, in-app load into LXMF/RNS,
|
||||
PIN-prompt unlock, auto-lock timeout, lock-on-quit, and **attestation-chain
|
||||
verification against the device's real ATTEST output**. Pre-5.7 (TDES) management
|
||||
keys are implemented and unit-tested but await validation on a pre-5.7 device.
|
||||
|
||||
Required before hardware RatKey is documented as supported:
|
||||
## Release scope: desktop only
|
||||
|
||||
- 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.
|
||||
Mobile is intentionally excluded from release. The `hardware` feature is off on
|
||||
iOS/Android (pcsc is desktop-only), the `hw_*` commands are
|
||||
`#[cfg(not(any(target_os = "android", target_os = "ios")))]`, and the frontend
|
||||
hides every hardware entry point on mobile (`isMobile()` gate in setup.js +
|
||||
identity.js).
|
||||
|
||||
## Mobile (deferred — needs a different model)
|
||||
|
||||
Desktop keeps the token plugged in and does every sign/ECDH on-card. That can't
|
||||
work over transient NFC (iOS CoreNFC is modal ~60s; Android IsoDep only while the
|
||||
tag is in-field; neither runs in the background). A messaging app used all day
|
||||
needs a **wrapped software session**: tap the key to unlock (on-card ECDH unwraps
|
||||
a software identity stored encrypted at rest, ideally in the Secure Enclave /
|
||||
StrongBox), operate in software for a configurable window (mirrors the desktop
|
||||
auto-lock setting), re-tap to refresh. This is a different security model than
|
||||
"key never leaves the token" and should be an explicit mode alongside
|
||||
hardware-only. The `PivTransport` seam is ready (`PivSession::new` takes any
|
||||
transport); a mobile loader belongs in `ratspeak-runtime`. Android NFC (IsoDep)
|
||||
is the tractable first transport.
|
||||
|
||||
### Recoverable software identities — DONE (2026-05-29, cross-platform)
|
||||
|
||||
The recoverable model generalized "hardware identity" → "recoverable identity,"
|
||||
with the YubiKey as one optional backing. All on every platform (the derivation
|
||||
+ vault are pure-Rust, gated behind a default `seed` feature in ratspeak-runtime
|
||||
that pulls `rns-ratkey` without pcsc):
|
||||
|
||||
- **Software seed-restore** (`ratspeak_runtime::derive_identity_key_from_phrase`,
|
||||
`restore_seed_identity` command): a 12-word phrase restores a software identity
|
||||
on any platform — the practical mobile recovery path. Folded into the app's
|
||||
**Import** flow (key *or* phrase), not a separate button.
|
||||
- **Mnemonic-derived-by-default** (`generate_recoverable_key`): new software
|
||||
identities are derived from a fresh BIP-39 mnemonic shown for backup at creation.
|
||||
Both `api_create_identity` (settings) and `api_setup_complete` (first-setup)
|
||||
produce them; legacy random identities keep raw-key export.
|
||||
`LxmfManager::create_identity` (random) stays for internal/tests.
|
||||
- **Recovery-phrase re-display** (`vault::store_plaintext_seed` /
|
||||
`has_stored_mnemonic` / `reveal_mnemonic`, `reveal_identity_mnemonic` command,
|
||||
software only): the phrase is persisted so it can be shown again. Its at-rest
|
||||
protection tracks the key's — a plaintext `identity.seed` sidecar when the
|
||||
identity is unprotected (crypto-equivalent to the already-plaintext `identity`
|
||||
key file), folded into the vault as a `mnemonic_token` (same KEK) once a passcode
|
||||
is set. The vault is authoritative when present, so reveal honors the passcode
|
||||
even if a stale sidecar survives the verify-before-delete window. Captured at
|
||||
create/import (both `api_create_identity`, `api_setup_complete`, and
|
||||
`restore_seed_identity`); hardware identities never store a phrase.
|
||||
- **Passcode at-rest encryption** (`vault.rs`): software identities can be sealed
|
||||
with a passcode — Argon2id(passcode,salt) → HKDF(info=params‖salt) binds the KDF
|
||||
params → 64-byte KEK → `rns_crypto::token` (AES-256-CBC + HMAC). Stored as
|
||||
`identity.enc`; param-tamper/wrong-passcode → auth failure (unit-tested). The
|
||||
launch unlock + auto-lock + lock-on-quit machinery is shared with the hardware
|
||||
PIN path (one "protected identity" state, a `kind` discriminator selects PIN vs
|
||||
passcode; the `hw_unlock`/`hardware_locked`/`hw_locked` wire names are retained).
|
||||
|
||||
Caveat documented to users: restore recovers the *identity*, not past message
|
||||
history (forward secrecy).
|
||||
|
||||
## Architecture (done)
|
||||
|
||||
- `PivTransport` is the platform seam: APDU bytes in, response bytes out.
|
||||
`PivSession<T>` builds every PIV operation on `apdu` over that seam and is
|
||||
transport-agnostic (compiles with no features).
|
||||
- `PcscTransport` (behind the `hardware` feature) is the desktop PC/SC
|
||||
implementation; `PivSession::<PcscTransport>::connect()` is the entry point.
|
||||
Mobile NFC/USB transports implement `PivTransport` from the application layer.
|
||||
- `HardwareIdentity` holds a `Box<dyn IdentityBackend>`, implemented by both
|
||||
`PivSession<T>` (real token, any transport) and `MockPivSession`.
|
||||
- `PivSession::lock()` / `HardwareIdentity::lock()` re-select the PIV applet to
|
||||
drop the on-card PIN cache (mechanism for app-side session timeout / lock-on-quit).
|
||||
|
||||
## Validated on hardware (YubiKey 5, firmware 5.7.4)
|
||||
|
||||
Full provision → verify → test loop with our own code, PIN-once + touch-never
|
||||
Ed25519 (9A) / X25519 (9D):
|
||||
|
||||
- **Management-key authentication** (witness/challenge, AES-192) — `hw provision`
|
||||
authenticates slot 9B and generates both keys on-device. Successful generate
|
||||
is proof of auth.
|
||||
- `parse_metadata_public_key` reads the correct pubkey from GET METADATA
|
||||
(confirmed against ykman-exported ground truth — the layout assumption held).
|
||||
- Ed25519 signing on slot 9A; signature verifies against the slot pubkey.
|
||||
- X25519 ECDH on slot 9D; shared secret symmetric with a software peer.
|
||||
- `HardwareIdentity` decrypt end-to-end (on-device ECDH → HKDF → AES token) — the
|
||||
same Ed25519-sign + X25519-ECDH + token-AES primitives LXMF uses, so live LXMF
|
||||
send/receive on a hardware identity routes through the card (serial 35284666).
|
||||
- The pubkey our provision records matches ykman's independent export byte-for-byte.
|
||||
- **Attestation chain verified against the device's real ATTEST output** (`hw
|
||||
attest`): both slot-9A/9D per-key certs chain through the slot-F9 device
|
||||
intermediate to a bundled, fingerprint-pinned new-PKI Yubico root. `hw provision`
|
||||
now captures + verifies the chain into the `.hwid`. The captured 5.7.4 certs are
|
||||
committed as a CI regression vector (`tests/fixtures/{9a_attest,f9_device}.der`).
|
||||
|
||||
## Still required before hardware RatKey is documented as supported
|
||||
|
||||
- **TDES management keys** are implemented (3DES EDE3 via the `des` crate, 8-byte
|
||||
block; `mgmt.rs` dispatches on the algorithm byte). A FIPS-81 known-answer test
|
||||
and a distinct-subkey round-trip cover the cipher. Pre-5.7 YubiKeys default to a
|
||||
TDES management key; the witness/challenge auth flow already drives its block
|
||||
size from `mgmt::block_len`, so it is ready — but not yet exercised against a
|
||||
physical pre-5.7 device.
|
||||
- A two-node **live LXMF message exchange** in the app on a hardware identity. The
|
||||
on-card crypto primitives are validated (above) and the runtime delegates
|
||||
sign/ECDH to the backend, but an end-to-end app round-trip between two peers is
|
||||
still a manual check.
|
||||
- Edge cases on a real device: disconnect mid-operation, wrong PIN / lockout,
|
||||
touch timeout (if touch is ever enabled), and the `from_hwid` key-mismatch guard.
|
||||
- Decide and document the ratchet policy for hardware identities. PIV cannot hold
|
||||
Reticulum ratchet private keys, so enforced-ratchet decrypt fails closed.
|
||||
- Add hardware-gated tests that are skipped by default but run when a device is
|
||||
explicitly selected by environment/config.
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDSDCCAjCgAwIBAgIUUcmMXzRIFOgGTK0Tb3gEuZYZkBIwDQYJKoZIhvcNAQEL
|
||||
BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy
|
||||
MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowLjEsMCoGA1UEAwwjWXViaWNvIEF0
|
||||
dGVzdGF0aW9uIEludGVybWVkaWF0ZSBBIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB
|
||||
DwAwggEKAoIBAQDm555bWY9WW+tOY0rIWHldh+aNanoCZCFh7Gk3YZrQmPUw0hkS
|
||||
G6qYHQtP+fZyS33VErvg+BQqnmumgNhfxFrkwEZELeidBcC8C4Ag4nqqiPWpzsvI
|
||||
17NcxYlInLNLFcZY/+gOiN6ZOTihO5/vBZMbj9riaAcqliYmNGJPgTcMGaEAyMzE
|
||||
MNy2nm6Ep+pjP5aF6gi21t/UQFsuJ1j2Rj/ynM/SdRt+ecal5OYotxHkFbL9vvv2
|
||||
A2Ov5ITZClw4bOS9npypQimOZ5QAYytmYaQpWl/pMYz6zSj8RqkVDNEJGqNfTKA2
|
||||
ivLYwX6lSttMPapg0J84l9X0voVN/FpS4VCVAgMBAAGjZjBkMB0GA1UdDgQWBBQg
|
||||
KFAhG6RaW+hTy52dxeT8bC96HzAfBgNVHSMEGDAWgBTS7u9aIo06bVwjlz3yhdUm
|
||||
8SV7kjASBgNVHRMBAf8ECDAGAQH/AgECMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG
|
||||
9w0BAQsFAAOCAQEAYMzgLrJLIr0OovQnAZrRIGuabiHSUKSmbLRWpRkWeAtsChDE
|
||||
HpXcJ/bgDNKYWoHqQ8xRUjB4CyepYevc3YlrG8o7zHxpfVcaoL5SeuJkzHxKn4bT
|
||||
aSp9+Mvwamnp64kZMiNbFLknfP9kYKoRHkMWheRJ1UsP1z4ScmkCeILfsMs6vqov
|
||||
qjWClFsJpBcsluYHWF7bBJ1n4Rwg+ATEopY4IgGv6Zvwc+A9r+AT2hqpoSkYoAl+
|
||||
ANYwgslOf9sJe0V+TA9YY/UlaBmPPTd0//r9wvcePWZkPjKoAC/zUNhfDbh4LV8G
|
||||
Hs3lyX2XomL/LNc8JYzyIaDEhGQveoPhh/tr1g==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDSDCCAjCgAwIBAgIUDqERw+4RnGSggxgUewJFEPDRZ3YwDQYJKoZIhvcNAQEL
|
||||
BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy
|
||||
MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowLjEsMCoGA1UEAwwjWXViaWNvIEF0
|
||||
dGVzdGF0aW9uIEludGVybWVkaWF0ZSBCIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB
|
||||
DwAwggEKAoIBAQDI7XnH+ZvDwMCQU8M8ZeV5qscublvVYaaRt3Ybaxn9godLx5sw
|
||||
H0lXrdgjh5h7FpVgCgYYX7E4bl1vbzULemrMWT8N3WMGUe8QAJbBeioV7W/E+hTZ
|
||||
P/0SKJVa3ewKBo6ULeMnfQZDrVORAk8wTLq2v5Llj5vMj7JtOotKa9J7nHS8kLmz
|
||||
XXSaj0SwEPh5OAZUTNV4zs1bvoTAQQWrL4/J9QuKt6WCFE5nUNiRQcEbVF8mlqK2
|
||||
bx2z6okVltyDVLCxYbpUTELvY1usR3DTGPUoIClOm4crpwnDRLVHvjYePGBB//pE
|
||||
yzxA/gcScxjwaH1ZUw9bnSbHyurKqbTa1KvjAgMBAAGjZjBkMB0GA1UdDgQWBBTq
|
||||
t0KQngx7ZHrbVHwDunxOn9ihYTAfBgNVHSMEGDAWgBTS7u9aIo06bVwjlz3yhdUm
|
||||
8SV7kjASBgNVHRMBAf8ECDAGAQH/AgECMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG
|
||||
9w0BAQsFAAOCAQEAqQaCWMxTGqVVX7Sk7kkJmUueTSYKuU6+KBBSgwIRnlw9K7He
|
||||
1IpxZ0hdwpPNikKjmcyFgFPzhImwHJgxxuT90Pw3vYOdcJJNktDg35PXOfzSn15c
|
||||
FAx1RO0mPTmIb8dXiEWOpzoXvdwXDM41ZaCDYMT7w4IQtMyvE7xUBZq2bjtAnq/N
|
||||
DUA7be4H8H3ipC+/+NKlUrcUh+j48K67WI0u1m6FeQueBA7n06j825rqDqsaLs9T
|
||||
b7KAHAw8PmrWaNPG2kjKerxPEfecivlFawp2RWZvxrVtn3TV2SBxyCJCkXsND05d
|
||||
CErVHSJIs+BdtTVNY9AwtyPmnyb0v4mSTzvWdw==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDSTCCAjGgAwIBAgIUSiefkiKiicP9B63XwO7fKqevCkQwDQYJKoZIhvcNAQEL
|
||||
BQAwLjEsMCoGA1UEAwwjWXViaWNvIEF0dGVzdGF0aW9uIEludGVybWVkaWF0ZSBB
|
||||
IDEwIBcNMjQxMjAxMDAwMDAwWhgPOTk5OTEyMzEyMzU5NTlaMCUxIzAhBgNVBAMM
|
||||
Gll1YmljbyBQSVYgQXR0ZXN0YXRpb24gQSAxMIIBIjANBgkqhkiG9w0BAQEFAAOC
|
||||
AQ8AMIIBCgKCAQEAyGCyrZjNrdPfChdDe4JWd+4TMLr8nbugcKJz12egglWi7oy5
|
||||
L9GT99/if9i1OrONdpEt0YrCa+qMb+dJJ0WUa8M5zXYnUDpn72vhFjH+Anb9P9+v
|
||||
+ZrRqaj/jnR/MYP7NpVpeLHiH2dRCe/PX/NH1XE41GvdUEncDtqUUGaXUea0DfDY
|
||||
McRDpPT2Qn5e8rn9FjzDA37SbOVuws5VlFTDzDdqR0FnqeWeIW0DFu17rzCqXcaB
|
||||
VRDnQLTc5EEPDTpiRrQE/Ag+7Wg9ieLrueos75YMQ1EIkfjL49OBVogU1A7kwRGv
|
||||
OnG8l7sYaY8LZ2b5FROe2hKqmsIy600qjn6b/QIDAQABo2YwZDAdBgNVHQ4EFgQU
|
||||
hAuLXXtpQVBkcsbqyFlj6LVAadgwHwYDVR0jBBgwFoAUIChQIRukWlvoU8udncXk
|
||||
/Gwveh8wEgYDVR0TAQH/BAgwBgEB/wIBATAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZI
|
||||
hvcNAQELBQADggEBAFxL/2oFjxkLh2KVnFKdhy7Nf7MmEfYXDDFSx1rFDn445jHO
|
||||
UP5kxQPbZc9r53jdvL5W0SQBqBjqA95PYh0r1CPMFsFJdiFXli8Hf3NQ0bTkeFSN
|
||||
G3LsQCOKMb+o2WjYU3vHkRVjKgKGLxysxxKxGfMUcXdJ0qM6ZVeRHehC2zy7XuI6
|
||||
TQn7/V0ZHXjk7So7dUV55xQde094/3cCTnh9Q3j2aqMjkGx6tDboCsz/+W+tne7W
|
||||
nMHG92ZiAAmOkP2bABjan461Qty/qBXPHomkfjqNbjUTluPXiMLYKCXHIyKwdkX6
|
||||
cphouSMU3QOTsb35Y2PeWNk54xu+Eds/3nhRMso=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDSTCCAjGgAwIBAgIUWVf2oJG+t1qP8t8TicWgJ2KYan4wDQYJKoZIhvcNAQEL
|
||||
BQAwLjEsMCoGA1UEAwwjWXViaWNvIEF0dGVzdGF0aW9uIEludGVybWVkaWF0ZSBC
|
||||
IDEwIBcNMjQxMjAxMDAwMDAwWhgPOTk5OTEyMzEyMzU5NTlaMCUxIzAhBgNVBAMM
|
||||
Gll1YmljbyBQSVYgQXR0ZXN0YXRpb24gQiAxMIIBIjANBgkqhkiG9w0BAQEFAAOC
|
||||
AQ8AMIIBCgKCAQEAv7WBL9/5AKxSpCMoL63183WqRtFrOHY7tdyuGtoidoYWQrxV
|
||||
aV9S+ZwH0aynh0IzD5A/PvCtuxdtL5w2cAI3tgsborOlEert4IZ904CZQfq3ooar
|
||||
1an/wssbtMpPOQkC3MQiqrUyHlFS2BTbuwbBXY66lSVX/tGRuUgnBdfBJtcQKS6M
|
||||
O4bU5ndPQqhGPyzcyY1LvlfzK7KJ1r/bixCRFqjhJRnPs0Czpg6rkRrFgC6cd5bK
|
||||
1UgTsJy+3wrIqkv4CeV3EhSVnhnQjZgIrdIcI5WZ8T1Oq3OhMlWmY0K0dy/oZdP/
|
||||
bpbG2qbyHLa6gprLT/qChQWLmffxn6D2DAB1zQIDAQABo2YwZDAdBgNVHQ4EFgQU
|
||||
M0Nt3QHo7eGzaKMZn2SmXT74vpcwHwYDVR0jBBgwFoAU6rdCkJ4Me2R621R8A7p8
|
||||
Tp/YoWEwEgYDVR0TAQH/BAgwBgEB/wIBATAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZI
|
||||
hvcNAQELBQADggEBAI0HwoS84fKMUyIof1LdUXvyeAMmEwW7+nVETvxNNlTMuwv7
|
||||
zPJ4XZAm9Fv95tz9CqZBj6l1PAPQn6Zht9LQA92OF7W7buuXuxuusBTgLM0C1iX2
|
||||
CGXqY/k/uSNvi3ZYfrpd44TIrfrr8bCG9ux7B5ZCRqb8adDUm92Yz3lK1aX2M6Cw
|
||||
jC9IZVTXQWhLyP8Ys3p7rb20CO2jJzV94deJ/+AsEb+bnCQImPat1GDKwrBosar+
|
||||
BxtU7k6kgkxZ0G384O59GFXqnwkbw2b5HhORvOsX7nhOUhePFufzi1vT1g8Tzbwr
|
||||
+TUfTwo2biKHHcI762KGtp8o6Bcv5y8WgExFuWY=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDRjCCAjCgAwIBAgIUM6Hs259YBTYRAMg98ZZlv/CDyO0wCwYJKoZIhvcNAQEL
|
||||
MC4xLDAqBgNVBAMMI1l1YmljbyBBdHRlc3RhdGlvbiBJbnRlcm1lZGlhdGUgQiAx
|
||||
MCAXDTI1MDgwMTAwMDAwMFoYDzk5OTkxMjMxMjM1OTU5WjAmMSQwIgYDVQQDDBtZ
|
||||
dWJpY28gUElWIEF0dGVzdGF0aW9uIEIyIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB
|
||||
DwAwggEKAoIBAQCxqNa82XHPD/QMqYffF8K4a9aoJIV7SU9NKXu3hBh+6nF0/HPP
|
||||
UtSu/ChTdPoCk1Li2Sz7gkWzijJVCCSo6uRgRT2sUoTb8xjKo80N5QxAC3TVNRpA
|
||||
lGh4Ba5KxamnXrf6s78tB73oTlTkMBUehVwvbQZGRpst00w58SxDP0nF7rO6qF+h
|
||||
8M+kV4ycd8zUssMq6yxWhDAUZ+gT4l0SwvBEvUiJ8q7phFGJPyMjrKy1bifC50GW
|
||||
xdLLJq7WRswaNxOsQ8hqJVRsoQ9pnZDCvo2WRkTzi3UrPPp5Soyy+aUOlNs0gwFu
|
||||
07H75Gnswet+wffpeDFXZM2ITH3SN0LrpairAgMBAAGjZjBkMB0GA1UdDgQWBBSe
|
||||
IRwEGD3d5SgceJxQn/ztOZHuVjAfBgNVHSMEGDAWgBTqt0KQngx7ZHrbVHwDunxO
|
||||
n9ihYTASBgNVHRMBAf8ECDAGAQH/AgEBMA4GA1UdDwEB/wQEAwIBhjALBgkqhkiG
|
||||
9w0BAQsDggEBAKK+IxeMsYsfqbLZ/Ld82tHWddLLlbXBaQojmRSDNHlBGbOvuQZg
|
||||
rnbafjIEyb+Uv1+TdJnn5cV1P/MBSfJLBPqBuhKZ3lk4460CWRmcIKsxVRe0V5+V
|
||||
bGCzLKpWtlrEBVkFTSbBQk4FQNVYw5pR4UzRIambsRyyGsyN0gppGyxyCqAR8/Od
|
||||
GI+sUWh+VxFSlSpvaDT9GBGBN6eG0WMAZlEdu9k/tphesazHeK6MvXP6tBnb4DCd
|
||||
09DUZeon7D8m1drYyw5kOjqgm1E3HPkNx4856iTdY7nAuVQ++i0hUhaJpc/5HZbw
|
||||
wdlqXnmZ+XRIGSDLn2KKoxSWziowEvlU+04=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -10,9 +10,11 @@ pub const PIV_AID: &[u8] = &[0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x0
|
||||
pub const INS_SELECT: u8 = 0xA4;
|
||||
pub const INS_VERIFY: u8 = 0x20;
|
||||
pub const INS_CHANGE_REFERENCE: u8 = 0x24;
|
||||
pub const INS_RESET_RETRY: u8 = 0x2C;
|
||||
pub const INS_GENERAL_AUTHENTICATE: u8 = 0x87;
|
||||
pub const INS_GENERATE_ASYMMETRIC: u8 = 0x47;
|
||||
pub const INS_GET_DATA: u8 = 0xCB;
|
||||
pub const INS_RESET_PIV: u8 = 0xFB;
|
||||
pub const INS_GET_METADATA: u8 = 0xF7;
|
||||
pub const INS_ATTEST: u8 = 0xF9;
|
||||
pub const INS_IMPORT_KEY: u8 = 0xFE;
|
||||
@@ -30,6 +32,13 @@ pub const SLOT_SIGNATURE: u8 = 0x9C;
|
||||
pub const SLOT_KEY_MANAGEMENT: u8 = 0x9D;
|
||||
pub const SLOT_CARD_AUTH: u8 = 0x9E;
|
||||
pub const SLOT_ATTESTATION: u8 = 0xF9;
|
||||
pub const SLOT_CARD_MANAGEMENT: u8 = 0x9B;
|
||||
|
||||
// Management-key algorithm (key reference 9B). AES-192 is the YubiKey 5.7 default.
|
||||
pub const MGMT_ALG_TDES: u8 = 0x03;
|
||||
pub const MGMT_ALG_AES128: u8 = 0x08;
|
||||
pub const MGMT_ALG_AES192: u8 = 0x0A;
|
||||
pub const MGMT_ALG_AES256: u8 = 0x0C;
|
||||
|
||||
pub const PIN_POLICY_NEVER: u8 = 0x01;
|
||||
pub const PIN_POLICY_ONCE: u8 = 0x02;
|
||||
@@ -42,26 +51,80 @@ pub const TOUCH_POLICY_CACHED: u8 = 0x03;
|
||||
const TAG_DYNAMIC_AUTH: u8 = 0x7C;
|
||||
const TAG_AUTH_RESPONSE: u8 = 0x82;
|
||||
const TAG_AUTH_CHALLENGE: u8 = 0x81;
|
||||
/// Management-key auth witness (same byte as `TAG_GEN_ALGORITHM`, different context).
|
||||
const TAG_AUTH_WITNESS: u8 = 0x80;
|
||||
const TAG_AUTH_EXPONENTIATION: u8 = 0x85;
|
||||
const TAG_GEN_ALGORITHM: u8 = 0x80;
|
||||
const TAG_PIN_POLICY: u8 = 0xAA;
|
||||
const TAG_TOUCH_POLICY: u8 = 0xAB;
|
||||
const TAG_OBJECT_ID: u8 = 0x5C;
|
||||
const TAG_ECC_POINT: u8 = 0x86;
|
||||
/// GET METADATA public-key field (Yubico).
|
||||
const TAG_METADATA_PUBLIC_KEY: u8 = 0x04;
|
||||
|
||||
/// Cert object ID for slot 9A (Authentication).
|
||||
pub const OBJ_ID_9A: &[u8] = &[0x5F, 0xC1, 0x05];
|
||||
/// Cert object ID for slot 9D (Key Management).
|
||||
pub const OBJ_ID_9D: &[u8] = &[0x5F, 0xC1, 0x0B];
|
||||
/// Object ID for the device attestation (slot F9) intermediate certificate.
|
||||
pub const OBJ_ID_F9: &[u8] = &[0x5F, 0xFF, 0x01];
|
||||
|
||||
pub fn slot_to_object_id(slot: u8) -> Option<&'static [u8]> {
|
||||
match slot {
|
||||
0x9A => Some(OBJ_ID_9A),
|
||||
0x9D => Some(OBJ_ID_9D),
|
||||
SLOT_ATTESTATION => Some(OBJ_ID_F9),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the certificate DER from a PIV GET DATA cert object response, which
|
||||
/// wraps the cert as `53 L { 70 L <certDER> 71 .. FE .. }`. Falls back to the raw
|
||||
/// buffer if it already looks like a bare certificate (`30` SEQUENCE).
|
||||
pub fn parse_certificate_object(resp: &[u8]) -> Option<Vec<u8>> {
|
||||
let content = read_ber_tlv(resp, 0x53).unwrap_or(resp);
|
||||
if let Some(cert) = read_ber_tlv(content, 0x70) {
|
||||
return Some(cert.to_vec());
|
||||
}
|
||||
match resp.first() {
|
||||
Some(0x30) => Some(resp.to_vec()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// First top-level BER-TLV with `tag` in `buf`, returning its value. Handles
|
||||
/// short-form and 1-/2-byte long-form lengths; single-byte tags only.
|
||||
fn read_ber_tlv(buf: &[u8], tag: u8) -> Option<&[u8]> {
|
||||
let mut i = 0;
|
||||
while i + 1 < buf.len() {
|
||||
let t = buf[i];
|
||||
let len_byte = buf[i + 1];
|
||||
i += 2;
|
||||
let len = if len_byte < 0x80 {
|
||||
len_byte as usize
|
||||
} else {
|
||||
let n = (len_byte & 0x7f) as usize;
|
||||
if n == 0 || n > 2 || i + n > buf.len() {
|
||||
return None;
|
||||
}
|
||||
let mut l = 0usize;
|
||||
for _ in 0..n {
|
||||
l = (l << 8) | buf[i] as usize;
|
||||
i += 1;
|
||||
}
|
||||
l
|
||||
};
|
||||
if i + len > buf.len() {
|
||||
return None;
|
||||
}
|
||||
if t == tag {
|
||||
return Some(&buf[i..i + len]);
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ISO 7816-4 APDU: CLA INS P1 P2 [Lc] [Data]. CLA=0x00 (no chaining, no secure messaging).
|
||||
fn build_apdu(ins: u8, p1: u8, p2: u8, data: &[u8]) -> Vec<u8> {
|
||||
let mut apdu = Vec::with_capacity(5 + data.len());
|
||||
@@ -110,15 +173,19 @@ pub fn select_piv() -> Vec<u8> {
|
||||
|
||||
/// PIN is ASCII, 0xFF-padded to 8 bytes (NIST SP 800-73-4 §2.4.3).
|
||||
pub fn verify_pin(pin: &str) -> Vec<u8> {
|
||||
use zeroize::Zeroize;
|
||||
let mut pin_data = [0xFFu8; 8];
|
||||
let pin_bytes = pin.as_bytes();
|
||||
let copy_len = pin_bytes.len().min(8);
|
||||
pin_data[..copy_len].copy_from_slice(&pin_bytes[..copy_len]);
|
||||
build_apdu(INS_VERIFY, 0x00, 0x80, &pin_data)
|
||||
let cmd = build_apdu(INS_VERIFY, 0x00, 0x80, &pin_data);
|
||||
pin_data.zeroize();
|
||||
cmd
|
||||
}
|
||||
|
||||
// CHANGE REFERENCE DATA.
|
||||
pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec<u8> {
|
||||
use zeroize::Zeroize;
|
||||
let mut data = [0xFFu8; 16];
|
||||
let old_bytes = old_pin.as_bytes();
|
||||
let new_bytes = new_pin.as_bytes();
|
||||
@@ -126,7 +193,31 @@ pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec<u8> {
|
||||
let new_len = new_bytes.len().min(8);
|
||||
data[..old_len].copy_from_slice(&old_bytes[..old_len]);
|
||||
data[8..8 + new_len].copy_from_slice(&new_bytes[..new_len]);
|
||||
build_apdu(INS_CHANGE_REFERENCE, 0x00, 0x80, &data)
|
||||
let cmd = build_apdu(INS_CHANGE_REFERENCE, 0x00, 0x80, &data);
|
||||
data.zeroize();
|
||||
cmd
|
||||
}
|
||||
|
||||
/// RESET RETRY COUNTER: unblock a locked PIN with the PUK and set a new PIN.
|
||||
pub fn reset_retry(puk: &str, new_pin: &str) -> Vec<u8> {
|
||||
use zeroize::Zeroize;
|
||||
let mut data = [0xFFu8; 16];
|
||||
let puk_bytes = puk.as_bytes();
|
||||
let new_bytes = new_pin.as_bytes();
|
||||
let puk_len = puk_bytes.len().min(8);
|
||||
let new_len = new_bytes.len().min(8);
|
||||
data[..puk_len].copy_from_slice(&puk_bytes[..puk_len]);
|
||||
data[8..8 + new_len].copy_from_slice(&new_bytes[..new_len]);
|
||||
let cmd = build_apdu(INS_RESET_RETRY, 0x00, 0x80, &data);
|
||||
data.zeroize();
|
||||
cmd
|
||||
}
|
||||
|
||||
/// RESET PIV: erase all PIV data and restore factory PIV secrets.
|
||||
///
|
||||
/// YubiKey only accepts this command after both the PIN and PUK are blocked.
|
||||
pub fn reset_piv() -> Vec<u8> {
|
||||
build_apdu(INS_RESET_PIV, 0x00, 0x00, &[])
|
||||
}
|
||||
|
||||
// GENERATE ASYMMETRIC KEY PAIR (Ed25519/X25519).
|
||||
@@ -147,6 +238,63 @@ pub fn generate_key(
|
||||
build_apdu(INS_GENERATE_ASYMMETRIC, 0x00, slot, &data)
|
||||
}
|
||||
|
||||
// Yubico private-key import elements: Ed25519 = 0x07, X25519 = 0x08.
|
||||
const TAG_IMPORT_ED25519: u8 = 0x07;
|
||||
const TAG_IMPORT_X25519: u8 = 0x08;
|
||||
|
||||
/// IMPORT ASYMMETRIC KEY (Ed25519, slot). Requires management-key auth. For
|
||||
/// recoverable provisioning — the key was derived off-device from a seed phrase.
|
||||
pub fn import_ed25519(
|
||||
slot: u8,
|
||||
private_key: &[u8; 32],
|
||||
pin_policy: Option<u8>,
|
||||
touch_policy: Option<u8>,
|
||||
) -> Vec<u8> {
|
||||
import_key(
|
||||
slot,
|
||||
ALG_ED25519,
|
||||
TAG_IMPORT_ED25519,
|
||||
private_key,
|
||||
pin_policy,
|
||||
touch_policy,
|
||||
)
|
||||
}
|
||||
|
||||
/// IMPORT ASYMMETRIC KEY (X25519, slot). Requires management-key auth.
|
||||
pub fn import_x25519(
|
||||
slot: u8,
|
||||
private_key: &[u8; 32],
|
||||
pin_policy: Option<u8>,
|
||||
touch_policy: Option<u8>,
|
||||
) -> Vec<u8> {
|
||||
import_key(
|
||||
slot,
|
||||
ALG_X25519,
|
||||
TAG_IMPORT_X25519,
|
||||
private_key,
|
||||
pin_policy,
|
||||
touch_policy,
|
||||
)
|
||||
}
|
||||
|
||||
fn import_key(
|
||||
slot: u8,
|
||||
alg: u8,
|
||||
key_tag: u8,
|
||||
private_key: &[u8; 32],
|
||||
pin_policy: Option<u8>,
|
||||
touch_policy: Option<u8>,
|
||||
) -> Vec<u8> {
|
||||
let mut data = tlv(key_tag, private_key);
|
||||
if let Some(pp) = pin_policy {
|
||||
data.extend_from_slice(&tlv(TAG_PIN_POLICY, &[pp]));
|
||||
}
|
||||
if let Some(tp) = touch_policy {
|
||||
data.extend_from_slice(&tlv(TAG_TOUCH_POLICY, &[tp]));
|
||||
}
|
||||
build_apdu(INS_IMPORT_KEY, alg, slot, &data)
|
||||
}
|
||||
|
||||
/// GENERAL AUTHENTICATE Ed25519 sign. Send raw message — device does SHA-512 internally; no pre-hash.
|
||||
pub fn sign_ed25519(slot: u8, message: &[u8]) -> Vec<u8> {
|
||||
let challenge = tlv(TAG_AUTH_CHALLENGE, message);
|
||||
@@ -194,6 +342,64 @@ pub fn attest_key(slot: u8) -> Vec<u8> {
|
||||
build_apdu(INS_ATTEST, slot, 0x00, &[])
|
||||
}
|
||||
|
||||
// --- Management-key authentication (slot 9B, witness/challenge mutual auth) ---
|
||||
|
||||
/// Step 1: request an encrypted witness from the card. `mgmt_alg` is the
|
||||
/// management-key algorithm (P1).
|
||||
pub fn auth_witness_request(mgmt_alg: u8) -> Vec<u8> {
|
||||
let inner = tlv(TAG_AUTH_WITNESS, &[]);
|
||||
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
|
||||
build_apdu(
|
||||
INS_GENERAL_AUTHENTICATE,
|
||||
mgmt_alg,
|
||||
SLOT_CARD_MANAGEMENT,
|
||||
&data,
|
||||
)
|
||||
}
|
||||
|
||||
/// Step 3: return the decrypted witness plus our own challenge.
|
||||
pub fn auth_witness_response(mgmt_alg: u8, decrypted_witness: &[u8], challenge: &[u8]) -> Vec<u8> {
|
||||
let mut inner = tlv(TAG_AUTH_WITNESS, decrypted_witness);
|
||||
inner.extend_from_slice(&tlv(TAG_AUTH_CHALLENGE, challenge));
|
||||
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
|
||||
build_apdu(
|
||||
INS_GENERAL_AUTHENTICATE,
|
||||
mgmt_alg,
|
||||
SLOT_CARD_MANAGEMENT,
|
||||
&data,
|
||||
)
|
||||
}
|
||||
|
||||
/// Extract the witness (tag 0x80) from a witness-request response.
|
||||
pub fn parse_auth_witness(data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
find_tlv_value(data, TAG_AUTH_WITNESS)
|
||||
.map(<[u8]>::to_vec)
|
||||
.ok_or(RatkeyError::Apdu {
|
||||
sw1: 0x6A,
|
||||
sw2: 0x80,
|
||||
})
|
||||
}
|
||||
|
||||
/// Extract the card's encrypted challenge (tag 0x82) from a witness-response reply.
|
||||
pub fn parse_auth_response(data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
find_tlv_value(data, TAG_AUTH_RESPONSE)
|
||||
.map(<[u8]>::to_vec)
|
||||
.ok_or(RatkeyError::Apdu {
|
||||
sw1: 0x6A,
|
||||
sw2: 0x80,
|
||||
})
|
||||
}
|
||||
|
||||
/// Algorithm byte (tag 0x01) from a GET METADATA response (e.g. slot 9B mgmt key).
|
||||
pub fn parse_metadata_algorithm(metadata: &[u8]) -> Result<u8, RatkeyError> {
|
||||
find_tlv_value(metadata, 0x01)
|
||||
.and_then(|v| v.first().copied())
|
||||
.ok_or(RatkeyError::Apdu {
|
||||
sw1: 0x6A,
|
||||
sw2: 0x80,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn check_response(response: &[u8]) -> Result<&[u8], RatkeyError> {
|
||||
if response.len() < 2 {
|
||||
return Err(RatkeyError::Apdu {
|
||||
@@ -293,6 +499,31 @@ pub fn parse_ecdh_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// GET METADATA public key: field tag 0x04, then EC point tag 0x86 → 32 bytes.
|
||||
/// `find_tlv_value` recurses into a `7F49` wrapper if present, so both the
|
||||
/// bare (`86 20 ..`) and wrapped (`7F49 .. 86 20 ..`) encodings resolve.
|
||||
/// Yubico 5.3+ extension; Nitrokey 3 does not implement GET METADATA.
|
||||
pub fn parse_metadata_public_key(metadata: &[u8]) -> Result<[u8; 32], RatkeyError> {
|
||||
let pubkey_field =
|
||||
find_tlv_value(metadata, TAG_METADATA_PUBLIC_KEY).ok_or(RatkeyError::Apdu {
|
||||
sw1: 0x6A,
|
||||
sw2: 0x80,
|
||||
})?;
|
||||
let point = find_tlv_value(pubkey_field, TAG_ECC_POINT).ok_or(RatkeyError::Apdu {
|
||||
sw1: 0x6A,
|
||||
sw2: 0x80,
|
||||
})?;
|
||||
if point.len() != 32 {
|
||||
return Err(RatkeyError::InvalidHwid(format!(
|
||||
"expected 32-byte public key in metadata, got {} bytes",
|
||||
point.len()
|
||||
)));
|
||||
}
|
||||
let mut out = [0u8; 32];
|
||||
out.copy_from_slice(point);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// Recurse into 7C / AC / 53 / any 2-byte tag (7F49 etc) to find a single-byte tag.
|
||||
fn find_tlv_value(data: &[u8], target_tag: u8) -> Option<&[u8]> {
|
||||
let mut pos = 0;
|
||||
@@ -507,6 +738,34 @@ mod tests {
|
||||
assert_eq!(apdu, vec![0x00, 0xF9, 0x9A, 0x00]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_data_slot_f9_attestation() {
|
||||
let apdu = get_data(SLOT_ATTESTATION).unwrap();
|
||||
assert_eq!(
|
||||
apdu,
|
||||
vec![0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, 0x03, 0x5F, 0xFF, 0x01]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_certificate_object() {
|
||||
// A 200-byte "cert" (DER SEQUENCE header) forces long-form lengths, wrapped
|
||||
// as the PIV cert object: 53 L { 70 L <cert> 71 01 00 FE 00 }.
|
||||
let mut cert = vec![0x30, 0x81, 0xC5];
|
||||
cert.extend(std::iter::repeat_n(0xAB, 197));
|
||||
let mut inner = vec![0x70, 0x81, cert.len() as u8];
|
||||
inner.extend_from_slice(&cert);
|
||||
inner.extend_from_slice(&[0x71, 0x01, 0x00, 0xFE, 0x00]);
|
||||
let mut obj = vec![0x53, 0x81, inner.len() as u8];
|
||||
obj.extend_from_slice(&inner);
|
||||
|
||||
assert_eq!(parse_certificate_object(&obj).unwrap(), cert);
|
||||
// Bare DER (no PIV wrapper) is returned as-is.
|
||||
assert_eq!(parse_certificate_object(&cert).unwrap(), cert);
|
||||
// Non-cert payload yields nothing.
|
||||
assert!(parse_certificate_object(&[0x00, 0x01, 0x02]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_metadata() {
|
||||
let apdu = get_metadata(SLOT_AUTHENTICATION);
|
||||
@@ -571,6 +830,29 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reset_retry() {
|
||||
let apdu = reset_retry("12345678", "654321");
|
||||
assert_eq!(apdu[0], 0x00); // CLA
|
||||
assert_eq!(apdu[1], 0x2C); // INS = RESET RETRY
|
||||
assert_eq!(apdu[2], 0x00); // P1
|
||||
assert_eq!(apdu[3], 0x80); // P2 = PIN
|
||||
assert_eq!(apdu[4], 0x10); // Lc = 16
|
||||
assert_eq!(
|
||||
&apdu[5..13],
|
||||
&[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38]
|
||||
);
|
||||
assert_eq!(
|
||||
&apdu[13..21],
|
||||
&[0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0xFF, 0xFF]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reset_piv() {
|
||||
assert_eq!(reset_piv(), vec![0x00, 0xFB, 0x00, 0x00]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_response_success() {
|
||||
let response = vec![0xAA, 0xBB, 0x90, 0x00];
|
||||
@@ -632,6 +914,119 @@ mod tests {
|
||||
assert_eq!(secret, [0xCC; 32]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_auth_witness_request() {
|
||||
let apdu = auth_witness_request(MGMT_ALG_AES192);
|
||||
assert_eq!(
|
||||
apdu,
|
||||
vec![0x00, 0x87, 0x0A, 0x9B, 0x04, 0x7C, 0x02, 0x80, 0x00]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_auth_witness_response_carries_witness() {
|
||||
let witness = [0xAA; 16];
|
||||
let challenge = [0xBB; 16];
|
||||
let apdu = auth_witness_response(MGMT_ALG_AES192, &witness, &challenge);
|
||||
assert_eq!(apdu[1], 0x87); // INS GENERAL AUTHENTICATE
|
||||
assert_eq!(apdu[2], 0x0A); // P1 = AES-192
|
||||
assert_eq!(apdu[3], 0x9B); // P2 = mgmt slot
|
||||
assert_eq!(apdu[5], 0x7C); // dynamic auth template
|
||||
assert_eq!(parse_auth_witness(&apdu[5..]).unwrap(), witness.to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_auth_witness() {
|
||||
let mut resp = vec![0x7C, 0x12, 0x80, 0x10];
|
||||
resp.extend_from_slice(&[0xCC; 16]);
|
||||
assert_eq!(parse_auth_witness(&resp).unwrap(), vec![0xCC; 16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_auth_response() {
|
||||
let mut resp = vec![0x7C, 0x12, 0x82, 0x10];
|
||||
resp.extend_from_slice(&[0xDD; 16]);
|
||||
assert_eq!(parse_auth_response(&resp).unwrap(), vec![0xDD; 16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_metadata_algorithm() {
|
||||
let meta = vec![0x01, 0x01, MGMT_ALG_AES192];
|
||||
assert_eq!(parse_metadata_algorithm(&meta).unwrap(), MGMT_ALG_AES192);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_import_ed25519() {
|
||||
let key = [0x11; 32];
|
||||
let apdu = import_ed25519(
|
||||
SLOT_AUTHENTICATION,
|
||||
&key,
|
||||
Some(PIN_POLICY_ONCE),
|
||||
Some(TOUCH_POLICY_NEVER),
|
||||
);
|
||||
assert_eq!(apdu[1], 0xFE); // INS IMPORT KEY
|
||||
assert_eq!(apdu[2], 0xE0); // P1 = Ed25519
|
||||
assert_eq!(apdu[3], 0x9A); // P2 = slot
|
||||
assert_eq!(apdu[5], 0x07); // Ed25519 private-key element tag
|
||||
assert_eq!(apdu[6], 0x20); // 32-byte length
|
||||
assert_eq!(&apdu[7..39], &key);
|
||||
assert_eq!(
|
||||
&apdu[39..45],
|
||||
&[0xAA, 0x01, PIN_POLICY_ONCE, 0xAB, 0x01, TOUCH_POLICY_NEVER]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_import_x25519_tag() {
|
||||
let apdu = import_x25519(SLOT_KEY_MANAGEMENT, &[0x22; 32], None, None);
|
||||
assert_eq!(apdu[1], 0xFE);
|
||||
assert_eq!(apdu[2], 0xE1); // X25519
|
||||
assert_eq!(apdu[3], 0x9D);
|
||||
assert_eq!(apdu[5], 0x08); // X25519 private-key element tag
|
||||
assert_eq!(apdu[6], 0x20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_metadata_public_key_bare() {
|
||||
// Slot metadata: 01(algo) 02(policy) 03(origin) 04(pubkey = 86 20 <32>).
|
||||
// Layout pending confirmation against a real YubiKey GET METADATA response.
|
||||
let mut meta = vec![
|
||||
0x01,
|
||||
0x01,
|
||||
ALG_ED25519,
|
||||
0x02,
|
||||
0x02,
|
||||
PIN_POLICY_ONCE,
|
||||
TOUCH_POLICY_ALWAYS,
|
||||
0x03,
|
||||
0x01,
|
||||
0x01,
|
||||
0x04,
|
||||
0x22,
|
||||
0x86,
|
||||
0x20,
|
||||
];
|
||||
meta.extend_from_slice(&[0xAB; 32]);
|
||||
assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xAB; 32]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_metadata_public_key_7f49_wrapped() {
|
||||
// Same, but the point is wrapped in a 7F49 template (04 25 7F49 22 86 20 <32>).
|
||||
let mut meta = vec![
|
||||
0x01, 0x01, ALG_X25519, 0x04, 0x25, 0x7F, 0x49, 0x22, 0x86, 0x20,
|
||||
];
|
||||
meta.extend_from_slice(&[0xCD; 32]);
|
||||
assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xCD; 32]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_metadata_public_key_missing_field() {
|
||||
// No 0x04 field present.
|
||||
let meta = vec![0x01, 0x01, ALG_ED25519, 0x03, 0x01, 0x01];
|
||||
assert!(parse_metadata_public_key(&meta).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_generate_response_wrong_size() {
|
||||
let mut response = vec![0x7F, 0x49, 0x12, 0x86, 0x10];
|
||||
|
||||
@@ -1,20 +1,51 @@
|
||||
//! YubiKey PIV attestation verification. Bundled root CAs — never fetched.
|
||||
//! YubiKey PIV attestation verification. Bundled root CAs — never fetched at runtime.
|
||||
//!
|
||||
//! Legacy chain (firmware < 5.7.4):
|
||||
//! Yubico PIV Root CA Serial 263751 → device intermediate (slot F9) → per-key attestation cert.
|
||||
//! per-key attestation cert → device intermediate (slot F9)
|
||||
//! → `Yubico PIV Root CA Serial 263751` (bundled root).
|
||||
//!
|
||||
//! New chain (firmware >= 5.7.4):
|
||||
//! Yubico Attestation Root 1 → Intermediate A/B 1 → PIV Attestation A/B 1
|
||||
//! → device intermediate (slot F9) → per-key attestation cert.
|
||||
//! per-key attestation cert → device intermediate (slot F9)
|
||||
//! → `Yubico PIV Attestation {A,B,B2} 1` (bundled intermediate)
|
||||
//! → `Yubico Attestation Intermediate {A,B} 1` (bundled intermediate)
|
||||
//! → `Yubico Attestation Root 1` (bundled root).
|
||||
//! The two tiers of intermediate CAs are not present on the device; they are
|
||||
//! bundled here from Yubico's published attestation PKI (yubico-intermediate.pem).
|
||||
//! Both A and B branches plus the 2025 B2 PIV intermediate are bundled, so any
|
||||
//! firmware-5.7.4+ YubiKey PIV attestation chains to the bundled root.
|
||||
//!
|
||||
//! Nitrokey 3 does not support PIV attestation (firmware 1.8) — verification skipped.
|
||||
//!
|
||||
//! Chain verification status: structural + OID extraction only. The
|
||||
//! `verified` flag remains false until X.509 path validation is exercised
|
||||
//! against real devices. See crates/rns-ratkey/HARDWARE_STATUS.md.
|
||||
//! ## What `chain_verified == true` means here
|
||||
//!
|
||||
//! Every link from the per-key attestation cert up to (and including) a bundled
|
||||
//! trust anchor has a valid RSA PKCS#1 v1.5 signature (issuer public key over the
|
||||
//! child's TBS bytes), the terminal issuer's DER SHA-256 matches a pinned
|
||||
//! fingerprint constant, and every certificate in the walked path is inside its
|
||||
//! notBefore/notAfter validity window at verification time.
|
||||
//!
|
||||
//! ## Explicit non-goals (NOT checked)
|
||||
//!
|
||||
//! Revocation (CRL/OCSP), name constraints, basicConstraints/keyUsage/pathlen
|
||||
//! enforcement, and the remainder of RFC 5280 path validation are intentionally
|
||||
//! out of scope. The root's own self-signature is not verified — the root is
|
||||
//! trusted by pinned fingerprint plus validity window. All required chain links
|
||||
//! are sha256WithRSAEncryption; the per-cert signature OID is still inspected so
|
||||
//! a sha512WithRSA link would be honored rather than silently mis-verified.
|
||||
|
||||
use crate::error::RatkeyError;
|
||||
|
||||
use const_oid::ObjectIdentifier;
|
||||
use der::Encode;
|
||||
use rsa::RsaPublicKey;
|
||||
use rsa::pkcs1::DecodeRsaPublicKey;
|
||||
use rsa::pkcs1v15::{Signature as RsaSignature, VerifyingKey};
|
||||
use rsa::signature::Verifier;
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use x509_cert::Certificate;
|
||||
use x509_cert::der::Decode;
|
||||
|
||||
/// Yubico PIV Root CA (legacy, firmware < 5.7.4). Subject: "Yubico PIV Root CA Serial 263751".
|
||||
pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str =
|
||||
include_str!("../certs/yubico-piv-root-ca-legacy.pem");
|
||||
@@ -23,9 +54,22 @@ pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str =
|
||||
pub const YUBICO_ATTESTATION_ROOT_1_PEM: &str =
|
||||
include_str!("../certs/yubico-attestation-root-1.pem");
|
||||
|
||||
// New-PKI intermediates (firmware >= 5.7.4). Bundled from Yubico's published
|
||||
// yubico-intermediate.pem. A, B, and the 2025 B2 PIV branches are all covered.
|
||||
const YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM: &str =
|
||||
include_str!("../certs/yubico-attestation-intermediate-a-1.pem");
|
||||
const YUBICO_ATTESTATION_INTERMEDIATE_B_1_PEM: &str =
|
||||
include_str!("../certs/yubico-attestation-intermediate-b-1.pem");
|
||||
const YUBICO_PIV_ATTESTATION_A_1_PEM: &str =
|
||||
include_str!("../certs/yubico-piv-attestation-a-1.pem");
|
||||
const YUBICO_PIV_ATTESTATION_B_1_PEM: &str =
|
||||
include_str!("../certs/yubico-piv-attestation-b-1.pem");
|
||||
const YUBICO_PIV_ATTESTATION_B2_1_PEM: &str =
|
||||
include_str!("../certs/yubico-piv-attestation-b2-1.pem");
|
||||
|
||||
/// SHA-256 fingerprint of the legacy Yubico PIV Root CA (belt-and-suspenders vs PEM swap).
|
||||
pub const YUBICO_LEGACY_ROOT_SHA256: &str =
|
||||
"63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced73833120785b546";
|
||||
"63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced738331207b546";
|
||||
|
||||
/// SHA-256 fingerprint of the new Yubico Attestation Root 1 (belt-and-suspenders vs PEM swap).
|
||||
pub const YUBICO_NEW_ROOT_SHA256: &str =
|
||||
@@ -46,6 +90,13 @@ pub const OID_USAGE_POLICY: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4,
|
||||
/// Form factor (1 byte).
|
||||
pub const OID_FORM_FACTOR: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x09];
|
||||
|
||||
// Signature algorithm OIDs (PKCS#1).
|
||||
const OID_SHA256_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
|
||||
const OID_SHA512_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13");
|
||||
|
||||
// Guard against issuer cycles in a malformed/hostile pool.
|
||||
const MAX_CHAIN_DEPTH: usize = 8;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AttestationInfo {
|
||||
pub firmware_version: Option<(u8, u8, u8)>,
|
||||
@@ -73,8 +124,12 @@ pub struct AttestationVerification {
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
/// Verify chain: attestation cert (from ATTEST) + device intermediate (slot F9).
|
||||
/// Currently structural + OID extraction only.
|
||||
/// Verify chain: attestation cert (from ATTEST F9) + device intermediate (slot F9).
|
||||
///
|
||||
/// Sets `verified`/`chain_verified == true` only when every signature from the
|
||||
/// per-key cert up to a bundled, fingerprint-pinned Yubico root validates and
|
||||
/// all walked certs are inside their validity window. See module docs for the
|
||||
/// precise meaning and the explicit non-goals.
|
||||
pub fn verify_attestation(
|
||||
attestation_cert_der: &[u8],
|
||||
device_cert_der: &[u8],
|
||||
@@ -82,9 +137,8 @@ pub fn verify_attestation(
|
||||
let info = extract_attestation_info(attestation_cert_der, device_cert_der)?;
|
||||
|
||||
let metadata_extracted = info.firmware_version.is_some();
|
||||
let chain_verified = false;
|
||||
let root_ca = if let Some((major, minor, patch)) = info.firmware_version {
|
||||
if major > 5 || (major == 5 && minor >= 7 && patch >= 4) {
|
||||
if major > 5 || (major == 5 && (minor > 7 || (minor == 7 && patch >= 4))) {
|
||||
"new".to_string()
|
||||
} else {
|
||||
"legacy".to_string()
|
||||
@@ -93,17 +147,17 @@ pub fn verify_attestation(
|
||||
"unknown".to_string()
|
||||
};
|
||||
|
||||
let description = if metadata_extracted {
|
||||
let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0));
|
||||
format!(
|
||||
"YubiKey firmware {maj}.{min}.{pat}{}; attestation chain not cryptographically verified",
|
||||
info.serial_number
|
||||
.map(|s| format!(", serial {s}"))
|
||||
.unwrap_or_default()
|
||||
)
|
||||
} else {
|
||||
"could not extract YubiKey attestation metadata".to_string()
|
||||
};
|
||||
let anchors = bundled_trust_anchors();
|
||||
let pool = bundled_intermediate_pool();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
|
||||
let chain_result = verify_chain(attestation_cert_der, device_cert_der, &anchors, &pool, now);
|
||||
|
||||
let chain_verified = chain_result.is_ok();
|
||||
|
||||
let description = build_description(metadata_extracted, &info, &chain_result);
|
||||
|
||||
Ok(AttestationVerification {
|
||||
verified: chain_verified,
|
||||
@@ -115,11 +169,268 @@ pub fn verify_attestation(
|
||||
})
|
||||
}
|
||||
|
||||
fn build_description(
|
||||
metadata_extracted: bool,
|
||||
info: &AttestationInfo,
|
||||
chain_result: &Result<(), ChainError>,
|
||||
) -> String {
|
||||
let prefix = if metadata_extracted {
|
||||
let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0));
|
||||
format!(
|
||||
"YubiKey firmware {maj}.{min}.{pat}{}",
|
||||
info.serial_number
|
||||
.map(|s| format!(", serial {s}"))
|
||||
.unwrap_or_default()
|
||||
)
|
||||
} else {
|
||||
"could not extract YubiKey attestation metadata".to_string()
|
||||
};
|
||||
|
||||
match chain_result {
|
||||
Ok(()) => {
|
||||
format!("{prefix}; attestation chain cryptographically verified to bundled Yubico root")
|
||||
}
|
||||
Err(e) => format!("{prefix}; attestation chain not verified: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// YubiKey 5 (firmware >= 4.3.0) only. Nitrokey 3 has no PIV attestation.
|
||||
pub fn supports_attestation(device_type: &str) -> bool {
|
||||
device_type == "yubikey5"
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Chain verification
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A parsed trust anchor. Only included after its DER SHA-256 matched a pinned
|
||||
/// fingerprint constant (see `bundled_trust_anchors`), so reaching one is the
|
||||
/// terminal trust condition.
|
||||
#[derive(Clone)]
|
||||
struct TrustAnchor {
|
||||
cert: Certificate,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ChainError {
|
||||
ParseLeaf,
|
||||
ParseDevice,
|
||||
IssuerNotFound,
|
||||
SignatureInvalid,
|
||||
Expired,
|
||||
UnsupportedSignatureAlg(String),
|
||||
BadPublicKey,
|
||||
DepthExceeded,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ChainError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ChainError::ParseLeaf => write!(f, "attestation certificate did not parse as X.509"),
|
||||
ChainError::ParseDevice => {
|
||||
write!(f, "device (slot F9) certificate did not parse as X.509")
|
||||
}
|
||||
ChainError::IssuerNotFound => {
|
||||
write!(
|
||||
f,
|
||||
"no bundled/known issuer found for a certificate in the chain"
|
||||
)
|
||||
}
|
||||
ChainError::SignatureInvalid => write!(f, "a certificate signature failed to verify"),
|
||||
ChainError::Expired => write!(f, "a certificate is outside its validity window"),
|
||||
ChainError::UnsupportedSignatureAlg(oid) => {
|
||||
write!(f, "unsupported certificate signature algorithm {oid}")
|
||||
}
|
||||
ChainError::BadPublicKey => write!(f, "issuer public key could not be decoded as RSA"),
|
||||
ChainError::DepthExceeded => write!(f, "chain exceeded maximum depth"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bundled, fingerprint-pinned roots. A cert is only a valid terminal if its DER
|
||||
/// SHA-256 matches one of these constants — guarding against a swapped PEM.
|
||||
fn bundled_trust_anchors() -> Vec<TrustAnchor> {
|
||||
let mut anchors = Vec::new();
|
||||
for (pem, fp) in [
|
||||
(YUBICO_PIV_ROOT_CA_LEGACY_PEM, YUBICO_LEGACY_ROOT_SHA256),
|
||||
(YUBICO_ATTESTATION_ROOT_1_PEM, YUBICO_NEW_ROOT_SHA256),
|
||||
] {
|
||||
if let Some(der) = pem_to_der(pem) {
|
||||
if hex::encode(Sha256::digest(&der)) == fp {
|
||||
if let Ok(cert) = Certificate::from_der(&der) {
|
||||
anchors.push(TrustAnchor { cert });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
anchors
|
||||
}
|
||||
|
||||
/// Bundled intermediate CAs (new-PKI A/B/B2 branches). Searchable issuers only —
|
||||
/// never terminal trust anchors.
|
||||
fn bundled_intermediate_pool() -> Vec<Certificate> {
|
||||
[
|
||||
YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM,
|
||||
YUBICO_ATTESTATION_INTERMEDIATE_B_1_PEM,
|
||||
YUBICO_PIV_ATTESTATION_A_1_PEM,
|
||||
YUBICO_PIV_ATTESTATION_B_1_PEM,
|
||||
YUBICO_PIV_ATTESTATION_B2_1_PEM,
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|pem| pem_to_der(pem).and_then(|der| Certificate::from_der(&der).ok()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Walk from the leaf up to a pinned anchor, verifying each signature and every
|
||||
/// cert's validity window. `now` is seconds since the Unix epoch.
|
||||
fn verify_chain(
|
||||
attestation_cert_der: &[u8],
|
||||
device_cert_der: &[u8],
|
||||
anchors: &[TrustAnchor],
|
||||
intermediates: &[Certificate],
|
||||
now: Duration,
|
||||
) -> Result<(), ChainError> {
|
||||
let leaf = Certificate::from_der(attestation_cert_der).map_err(|_| ChainError::ParseLeaf)?;
|
||||
let device = Certificate::from_der(device_cert_der).map_err(|_| ChainError::ParseDevice)?;
|
||||
|
||||
// Searchable issuers: the device F9 cert plus all bundled intermediates.
|
||||
let mut searchable: Vec<&Certificate> = Vec::with_capacity(intermediates.len() + 1);
|
||||
searchable.push(&device);
|
||||
for c in intermediates {
|
||||
searchable.push(c);
|
||||
}
|
||||
|
||||
check_validity(&leaf, now)?;
|
||||
|
||||
let mut current = leaf.clone();
|
||||
let mut current_der = attestation_cert_der.to_vec();
|
||||
for _ in 0..MAX_CHAIN_DEPTH {
|
||||
// Terminal: is `current` signed by a pinned anchor?
|
||||
for anchor in anchors {
|
||||
// `anchor` is trusted only because its DER SHA-256 matched a pinned
|
||||
// constant in bundled_trust_anchors(); its self-signature is not checked.
|
||||
if names_match(
|
||||
&anchor.cert.tbs_certificate.subject,
|
||||
¤t.tbs_certificate.issuer,
|
||||
) && verify_signature(¤t, &anchor.cert).is_ok()
|
||||
{
|
||||
check_validity(&anchor.cert, now)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
// A self-issued cert that is not a pinned anchor is an untrusted root:
|
||||
// the chain terminates here without reaching a trust anchor. (Anchors are
|
||||
// checked above, so reaching this point means it is not pinned.)
|
||||
if names_match(
|
||||
¤t.tbs_certificate.subject,
|
||||
¤t.tbs_certificate.issuer,
|
||||
) {
|
||||
return Err(ChainError::IssuerNotFound);
|
||||
}
|
||||
|
||||
// Otherwise advance one link via a searchable (non-anchor) issuer.
|
||||
let issuer = searchable.iter().copied().find(|cand| {
|
||||
names_match(
|
||||
&cand.tbs_certificate.subject,
|
||||
¤t.tbs_certificate.issuer,
|
||||
) && verify_signature(¤t, cand).is_ok()
|
||||
});
|
||||
|
||||
match issuer {
|
||||
Some(issuer_cert) => {
|
||||
check_validity(issuer_cert, now)?;
|
||||
let issuer_der = issuer_cert
|
||||
.to_der()
|
||||
.map_err(|_| ChainError::IssuerNotFound)?;
|
||||
// Cycle guard: a non-self-issued cert pointing back at itself.
|
||||
if issuer_der == current_der {
|
||||
return Err(ChainError::IssuerNotFound);
|
||||
}
|
||||
current = issuer_cert.clone();
|
||||
current_der = issuer_der;
|
||||
}
|
||||
None => {
|
||||
// No pinned anchor and no searchable issuer signs `current`.
|
||||
// Distinguish "issuer present but bad signature" for diagnostics.
|
||||
let issuer_present = anchors.iter().any(|a| {
|
||||
names_match(
|
||||
&a.cert.tbs_certificate.subject,
|
||||
¤t.tbs_certificate.issuer,
|
||||
)
|
||||
}) || searchable.iter().any(|c| {
|
||||
names_match(&c.tbs_certificate.subject, ¤t.tbs_certificate.issuer)
|
||||
});
|
||||
return Err(if issuer_present {
|
||||
ChainError::SignatureInvalid
|
||||
} else {
|
||||
ChainError::IssuerNotFound
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(ChainError::DepthExceeded)
|
||||
}
|
||||
|
||||
/// RFC 5280 distinguished-name match via canonical DER encoding of the Name.
|
||||
fn names_match(a: &x509_cert::name::Name, b: &x509_cert::name::Name) -> bool {
|
||||
match (a.to_der(), b.to_der()) {
|
||||
(Ok(da), Ok(db)) => da == db,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify `child`'s signature using `issuer`'s public key (RSA PKCS#1 v1.5).
|
||||
fn verify_signature(child: &Certificate, issuer: &Certificate) -> Result<(), ChainError> {
|
||||
let tbs = child
|
||||
.tbs_certificate
|
||||
.to_der()
|
||||
.map_err(|_| ChainError::SignatureInvalid)?;
|
||||
|
||||
let sig_bytes = child
|
||||
.signature
|
||||
.as_bytes()
|
||||
.ok_or(ChainError::SignatureInvalid)?;
|
||||
let sig = RsaSignature::try_from(sig_bytes).map_err(|_| ChainError::SignatureInvalid)?;
|
||||
|
||||
let spki_key = issuer
|
||||
.tbs_certificate
|
||||
.subject_public_key_info
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(ChainError::BadPublicKey)?;
|
||||
let pubkey = RsaPublicKey::from_pkcs1_der(spki_key).map_err(|_| ChainError::BadPublicKey)?;
|
||||
|
||||
let alg = child.signature_algorithm.oid;
|
||||
if alg == OID_SHA256_RSA {
|
||||
VerifyingKey::<Sha256>::new(pubkey)
|
||||
.verify(&tbs, &sig)
|
||||
.map_err(|_| ChainError::SignatureInvalid)
|
||||
} else if alg == OID_SHA512_RSA {
|
||||
VerifyingKey::<Sha512>::new(pubkey)
|
||||
.verify(&tbs, &sig)
|
||||
.map_err(|_| ChainError::SignatureInvalid)
|
||||
} else {
|
||||
Err(ChainError::UnsupportedSignatureAlg(alg.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject certs outside their notBefore/notAfter window at time `now`.
|
||||
fn check_validity(cert: &Certificate, now: Duration) -> Result<(), ChainError> {
|
||||
let nb = cert.tbs_certificate.validity.not_before.to_unix_duration();
|
||||
let na = cert.tbs_certificate.validity.not_after.to_unix_duration();
|
||||
if now < nb || now > na {
|
||||
Err(ChainError::Expired)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OID metadata extraction (byte-scan; unchanged behavior)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn extract_attestation_info(
|
||||
attestation_cert_der: &[u8],
|
||||
device_cert_der: &[u8],
|
||||
@@ -379,8 +690,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_attestation_synthetic() {
|
||||
// Build a minimal attestation cert with firmware OID
|
||||
fn test_verify_attestation_synthetic_metadata() {
|
||||
// Minimal attestation cert with firmware OID; not a real X.509 cert, so the
|
||||
// chain cannot verify — exercises metadata extraction + graceful chain failure.
|
||||
let mut attest_der = Vec::new();
|
||||
let mut inner = Vec::new();
|
||||
inner.push(0x06);
|
||||
@@ -394,7 +706,6 @@ mod tests {
|
||||
attest_der.push(inner.len() as u8);
|
||||
attest_der.extend_from_slice(&inner);
|
||||
|
||||
// Minimal device cert (just a SEQUENCE)
|
||||
let device_der = vec![0x30, 0x00];
|
||||
|
||||
let result = verify_attestation(&attest_der, &device_der).unwrap();
|
||||
@@ -403,11 +714,7 @@ mod tests {
|
||||
assert!(!result.chain_verified);
|
||||
assert_eq!(result.root_ca, "legacy"); // 5.7.1 < 5.7.4
|
||||
assert!(result.description.contains("5.7.1"));
|
||||
assert!(
|
||||
result
|
||||
.description
|
||||
.contains("not cryptographically verified")
|
||||
);
|
||||
assert!(result.description.contains("not verified"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -434,6 +741,25 @@ mod tests {
|
||||
assert_eq!(result.root_ca, "new"); // 5.7.4 → new root CA
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_attestation_future_firmware_uses_new_root_label() {
|
||||
let mut attest_der = Vec::new();
|
||||
let mut inner = Vec::new();
|
||||
inner.push(0x06);
|
||||
inner.push(OID_FIRMWARE_VERSION.len() as u8);
|
||||
inner.extend_from_slice(OID_FIRMWARE_VERSION);
|
||||
inner.push(0x04);
|
||||
inner.push(0x03);
|
||||
inner.extend_from_slice(&[0x05, 0x08, 0x00]); // 5.8.0
|
||||
|
||||
attest_der.push(0x30);
|
||||
attest_der.push(inner.len() as u8);
|
||||
attest_der.extend_from_slice(&inner);
|
||||
|
||||
let result = verify_attestation(&attest_der, &[0x30, 0x00]).unwrap();
|
||||
assert_eq!(result.root_ca, "new");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_attestation_empty_cert() {
|
||||
let result = verify_attestation(&[], &[]).unwrap();
|
||||
@@ -442,4 +768,339 @@ mod tests {
|
||||
assert!(!result.chain_verified);
|
||||
assert_eq!(result.root_ca, "unknown");
|
||||
}
|
||||
|
||||
// Real on-device vectors captured from a YubiKey 5.7.4 (serial 35284666) via
|
||||
// `rnid-rs hw attest`: the slot-9A per-key attestation cert + the slot-F9
|
||||
// device intermediate. Proves the verifier chains a real device's ATTEST
|
||||
// output to a bundled, fingerprint-pinned Yubico root — the regression guard
|
||||
// for the hardware validation, runnable in CI without a device.
|
||||
// Both certs are notAfter=9999-12-31 (Yubico attestation certs do not expire),
|
||||
// so the validity-window check in `verify_chain` will not rot this vector.
|
||||
#[test]
|
||||
fn test_real_yubikey_attestation_chain_verifies() {
|
||||
let attest = include_bytes!("../tests/fixtures/9a_attest.der");
|
||||
let device = include_bytes!("../tests/fixtures/f9_device.der");
|
||||
let v = verify_attestation(attest, device).unwrap();
|
||||
assert!(
|
||||
v.chain_verified,
|
||||
"real-device chain must verify: {}",
|
||||
v.description
|
||||
);
|
||||
assert!(v.verified);
|
||||
assert_eq!(v.root_ca, "new");
|
||||
assert_eq!(v.info.firmware_version, Some((5, 7, 4)));
|
||||
assert_eq!(v.info.serial_number, Some(35284666));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Pinned-fingerprint guards: compute the SHA-256 with our own code path
|
||||
// (pem_to_der + sha2) and assert it equals the pinned constant. Catches a
|
||||
// swapped PEM and validates the hand-rolled base64 against the same DER the
|
||||
// x509 parser consumes.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn test_legacy_root_fingerprint_matches_constant() {
|
||||
let der = pem_to_der(YUBICO_PIV_ROOT_CA_LEGACY_PEM).expect("decode legacy root");
|
||||
assert_eq!(hex::encode(Sha256::digest(&der)), YUBICO_LEGACY_ROOT_SHA256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_root_fingerprint_matches_constant() {
|
||||
let der = pem_to_der(YUBICO_ATTESTATION_ROOT_1_PEM).expect("decode new root");
|
||||
assert_eq!(hex::encode(Sha256::digest(&der)), YUBICO_NEW_ROOT_SHA256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bundled_anchors_and_pool_parse() {
|
||||
let anchors = bundled_trust_anchors();
|
||||
assert_eq!(anchors.len(), 2, "both pinned roots must parse and match");
|
||||
let pool = bundled_intermediate_pool();
|
||||
assert_eq!(pool.len(), 5, "five PIV-chain intermediates bundled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_real_intermediate_chains_to_pinned_root() {
|
||||
// The bundled PIV Attestation A 1 cert chains to the bundled Attestation
|
||||
// Root 1 via the bundled Intermediate A 1. Verify the new-PKI links work
|
||||
// against the real published certs (using PIV Attestation A 1 as the
|
||||
// synthetic "leaf"/"device" entry point).
|
||||
let anchors = bundled_trust_anchors();
|
||||
let pool = bundled_intermediate_pool();
|
||||
// Use Intermediate A 1 as the leaf; its issuer is the pinned root.
|
||||
let int_a = pem_to_der(YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM).unwrap();
|
||||
let now = Duration::from_secs(1_900_000_000); // ~2030, inside all windows
|
||||
let res = verify_chain(&int_a, &int_a, &anchors, &pool, now);
|
||||
assert!(
|
||||
res.is_ok(),
|
||||
"real intermediate must chain to pinned root: {res:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Synthetic chains. Build our own root → sub-CA → leaf with the x509
|
||||
// builder, then exercise verify_chain directly with injected anchors.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
use rsa::RsaPrivateKey;
|
||||
use rsa::pkcs1v15::SigningKey;
|
||||
use std::str::FromStr;
|
||||
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
|
||||
use x509_cert::name::Name;
|
||||
use x509_cert::serial_number::SerialNumber;
|
||||
use x509_cert::spki::SubjectPublicKeyInfoOwned;
|
||||
use x509_cert::time::{Time, Validity};
|
||||
|
||||
struct Node {
|
||||
cert: Certificate,
|
||||
der: Vec<u8>,
|
||||
}
|
||||
|
||||
fn gen_key() -> RsaPrivateKey {
|
||||
let mut rng = rand::thread_rng();
|
||||
RsaPrivateKey::new(&mut rng, 1024).expect("rsa keygen")
|
||||
}
|
||||
|
||||
fn spki_of(key: &RsaPrivateKey) -> SubjectPublicKeyInfoOwned {
|
||||
use rsa::pkcs1::EncodeRsaPublicKey;
|
||||
let pub_der = key.to_public_key().to_pkcs1_der().unwrap();
|
||||
// Wrap PKCS#1 RSAPublicKey in an rsaEncryption SubjectPublicKeyInfo.
|
||||
use x509_cert::spki::AlgorithmIdentifierOwned;
|
||||
SubjectPublicKeyInfoOwned {
|
||||
algorithm: AlgorithmIdentifierOwned {
|
||||
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
|
||||
parameters: Some(der::Any::null()),
|
||||
},
|
||||
subject_public_key: x509_cert::der::asn1::BitString::from_bytes(pub_der.as_bytes())
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn far_validity() -> Validity {
|
||||
// Wide window covering "now".
|
||||
Validity::from_now(Duration::from_secs(60 * 60 * 24 * 365 * 20)).unwrap()
|
||||
}
|
||||
|
||||
/// Build a cert with `subject`, signed by `signer_key` under `issuer` name.
|
||||
fn build_cert(
|
||||
profile: Profile,
|
||||
subject: &str,
|
||||
subject_key: &RsaPrivateKey,
|
||||
signer_key: &RsaPrivateKey,
|
||||
validity: Validity,
|
||||
serial: u32,
|
||||
) -> Node {
|
||||
let signer = SigningKey::<Sha256>::new(signer_key.clone());
|
||||
let builder = CertificateBuilder::new(
|
||||
profile,
|
||||
SerialNumber::from(serial),
|
||||
validity,
|
||||
Name::from_str(subject).unwrap(),
|
||||
spki_of(subject_key),
|
||||
&signer,
|
||||
)
|
||||
.expect("builder");
|
||||
let cert: Certificate = builder.build::<RsaSignature>().expect("build/sign");
|
||||
let der = cert.to_der().expect("encode");
|
||||
Node { cert, der }
|
||||
}
|
||||
|
||||
/// Root self-signed; sub-CA signed by root; leaf signed by sub-CA. Returns
|
||||
/// (leaf, sub_ca, root) so callers can inject the root as anchor and the
|
||||
/// sub-CA into the searchable pool.
|
||||
fn synthetic_chain() -> (Node, Node, Node) {
|
||||
let root_key = gen_key();
|
||||
let sub_key = gen_key();
|
||||
let leaf_key = gen_key();
|
||||
|
||||
let root = build_cert(
|
||||
Profile::Root,
|
||||
"CN=Test Root",
|
||||
&root_key,
|
||||
&root_key,
|
||||
far_validity(),
|
||||
1,
|
||||
);
|
||||
let sub = build_cert(
|
||||
Profile::SubCA {
|
||||
issuer: Name::from_str("CN=Test Root").unwrap(),
|
||||
path_len_constraint: Some(1),
|
||||
},
|
||||
"CN=Test SubCA",
|
||||
&sub_key,
|
||||
&root_key,
|
||||
far_validity(),
|
||||
2,
|
||||
);
|
||||
let leaf = build_cert(
|
||||
Profile::Leaf {
|
||||
issuer: Name::from_str("CN=Test SubCA").unwrap(),
|
||||
enable_key_agreement: false,
|
||||
enable_key_encipherment: false,
|
||||
},
|
||||
"CN=Test Leaf",
|
||||
&leaf_key,
|
||||
&sub_key,
|
||||
far_validity(),
|
||||
3,
|
||||
);
|
||||
(leaf, sub, root)
|
||||
}
|
||||
|
||||
fn anchor_of(node: &Node) -> TrustAnchor {
|
||||
TrustAnchor {
|
||||
cert: node.cert.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> Duration {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthetic_chain_verifies() {
|
||||
let (leaf, sub, root) = synthetic_chain();
|
||||
// Device slot = sub-CA here; intermediates = [sub].
|
||||
let res = verify_chain(
|
||||
&leaf.der,
|
||||
&sub.der,
|
||||
&[anchor_of(&root)],
|
||||
std::slice::from_ref(&sub.cert),
|
||||
now(),
|
||||
);
|
||||
assert!(res.is_ok(), "valid synthetic chain must verify: {res:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tampered_signature_fails() {
|
||||
let (leaf, sub, root) = synthetic_chain();
|
||||
// Flip one byte in the leaf signature, re-encode.
|
||||
let mut tampered = leaf.cert.clone();
|
||||
let mut sig = tampered.signature.as_bytes().unwrap().to_vec();
|
||||
sig[0] ^= 0x01;
|
||||
tampered.signature = x509_cert::der::asn1::BitString::from_bytes(&sig).unwrap();
|
||||
let tampered_der = tampered.to_der().unwrap();
|
||||
|
||||
let res = verify_chain(
|
||||
&tampered_der,
|
||||
&sub.der,
|
||||
&[anchor_of(&root)],
|
||||
std::slice::from_ref(&sub.cert),
|
||||
now(),
|
||||
);
|
||||
assert!(
|
||||
matches!(res, Err(ChainError::SignatureInvalid)),
|
||||
"got {res:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expired_cert_fails() {
|
||||
let root_key = gen_key();
|
||||
let sub_key = gen_key();
|
||||
let leaf_key = gen_key();
|
||||
|
||||
let root = build_cert(
|
||||
Profile::Root,
|
||||
"CN=Test Root",
|
||||
&root_key,
|
||||
&root_key,
|
||||
far_validity(),
|
||||
1,
|
||||
);
|
||||
let sub = build_cert(
|
||||
Profile::SubCA {
|
||||
issuer: Name::from_str("CN=Test Root").unwrap(),
|
||||
path_len_constraint: Some(1),
|
||||
},
|
||||
"CN=Test SubCA",
|
||||
&sub_key,
|
||||
&root_key,
|
||||
far_validity(),
|
||||
2,
|
||||
);
|
||||
// Leaf already expired: notBefore..notAfter both in the past.
|
||||
let expired = Validity {
|
||||
not_before: Time::UtcTime(
|
||||
x509_cert::der::asn1::UtcTime::from_unix_duration(Duration::from_secs(
|
||||
1_000_000_000,
|
||||
))
|
||||
.unwrap(),
|
||||
),
|
||||
not_after: Time::UtcTime(
|
||||
x509_cert::der::asn1::UtcTime::from_unix_duration(Duration::from_secs(
|
||||
1_100_000_000,
|
||||
))
|
||||
.unwrap(),
|
||||
),
|
||||
};
|
||||
let leaf = build_cert(
|
||||
Profile::Leaf {
|
||||
issuer: Name::from_str("CN=Test SubCA").unwrap(),
|
||||
enable_key_agreement: false,
|
||||
enable_key_encipherment: false,
|
||||
},
|
||||
"CN=Test Leaf",
|
||||
&leaf_key,
|
||||
&sub_key,
|
||||
expired,
|
||||
3,
|
||||
);
|
||||
|
||||
let res = verify_chain(
|
||||
&leaf.der,
|
||||
&sub.der,
|
||||
&[anchor_of(&root)],
|
||||
std::slice::from_ref(&sub.cert),
|
||||
now(),
|
||||
);
|
||||
assert!(matches!(res, Err(ChainError::Expired)), "got {res:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrong_root_fails_on_pin() {
|
||||
// Build a fully valid chain, but the actual signing root is NOT pinned.
|
||||
// Put the bogus root in the SEARCHABLE pool (so issuer-by-name succeeds and
|
||||
// its signature verifies) but NOT in the anchor set. Verification must fail
|
||||
// because no walked cert reaches a pinned terminal — exercises pin rejection,
|
||||
// not a mere "issuer not found".
|
||||
let (leaf, sub, bogus_root) = synthetic_chain();
|
||||
|
||||
// A second, unrelated key serves as the only *pinned* anchor — it signs
|
||||
// nothing in this chain.
|
||||
let other_root_key = gen_key();
|
||||
let other_root = build_cert(
|
||||
Profile::Root,
|
||||
"CN=Unrelated Pinned Root",
|
||||
&other_root_key,
|
||||
&other_root_key,
|
||||
far_validity(),
|
||||
9,
|
||||
);
|
||||
|
||||
let res = verify_chain(
|
||||
&leaf.der,
|
||||
&sub.der,
|
||||
&[anchor_of(&other_root)], // pinned set: unrelated root only
|
||||
&[sub.cert.clone(), bogus_root.cert.clone()], // searchable: real signer present
|
||||
now(),
|
||||
);
|
||||
// The real signing root is reachable by name+signature but is not pinned,
|
||||
// so the walk terminates without a pinned anchor.
|
||||
assert!(
|
||||
matches!(res, Err(ChainError::IssuerNotFound)),
|
||||
"wrong-root chain must be rejected at the pin, got {res:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_issuer_fails() {
|
||||
let (leaf, _sub, root) = synthetic_chain();
|
||||
// No sub-CA in the pool: leaf's issuer is unfindable.
|
||||
let res = verify_chain(&leaf.der, &leaf.der, &[anchor_of(&root)], &[], now());
|
||||
assert!(
|
||||
matches!(res, Err(ChainError::IssuerNotFound)),
|
||||
"got {res:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Bridges a PIV token to an `rns_identity::Identity` via the `LocalKeyBackend`
|
||||
//! seam. The PIV session runs on a dedicated thread — pcsc handles want serial
|
||||
//! APDU access and are not `Sync` — so the backend handle holds only channel
|
||||
//! senders and is therefore `Send + Sync`, usable directly from the async runtime.
|
||||
|
||||
use std::sync::mpsc::{self, Sender};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
|
||||
use rns_identity::identity::{Identity, LocalKeyBackend};
|
||||
|
||||
use crate::apdu::{SLOT_AUTHENTICATION, SLOT_KEY_MANAGEMENT};
|
||||
use crate::error::RatkeyError;
|
||||
use crate::hwid::HwidConfig;
|
||||
use crate::session::PivSession;
|
||||
use crate::transport::PcscTransport;
|
||||
|
||||
enum Cmd {
|
||||
Sign {
|
||||
message: Vec<u8>,
|
||||
reply: Sender<Option<[u8; 64]>>,
|
||||
},
|
||||
Ecdh {
|
||||
peer_pub: [u8; 32],
|
||||
reply: Sender<Option<[u8; 32]>>,
|
||||
},
|
||||
/// Re-select the PIV applet to drop the on-card PIN cache. Acknowledged so
|
||||
/// callers (lock-on-quit / timeout) can block until the card is re-locked.
|
||||
Lock { reply: Sender<()> },
|
||||
}
|
||||
|
||||
/// `LocalKeyBackend` over a PIV token. Each call round-trips a request to the
|
||||
/// card-service thread and blocks for the device's reply (PIV ops are ~10-50ms).
|
||||
pub struct HardwareBackend {
|
||||
cmd_tx: Mutex<Sender<Cmd>>,
|
||||
}
|
||||
|
||||
impl LocalKeyBackend for HardwareBackend {
|
||||
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
|
||||
let (reply, rx) = mpsc::channel();
|
||||
self.cmd_tx
|
||||
.lock()
|
||||
.ok()?
|
||||
.send(Cmd::Sign {
|
||||
message: message.to_vec(),
|
||||
reply,
|
||||
})
|
||||
.ok()?;
|
||||
rx.recv().ok().flatten()
|
||||
}
|
||||
|
||||
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
|
||||
let (reply, rx) = mpsc::channel();
|
||||
self.cmd_tx
|
||||
.lock()
|
||||
.ok()?
|
||||
.send(Cmd::Ecdh {
|
||||
peer_pub: *peer_pub,
|
||||
reply,
|
||||
})
|
||||
.ok()?;
|
||||
rx.recv().ok().flatten()
|
||||
}
|
||||
|
||||
fn lock(&self) {
|
||||
let (reply, rx) = mpsc::channel();
|
||||
if let Ok(tx) = self.cmd_tx.lock()
|
||||
&& tx.send(Cmd::Lock { reply }).is_ok()
|
||||
{
|
||||
let _ = rx.recv();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to the token described by `hwid`, verify the on-device keys match it
|
||||
/// (fail-closed), unlock with `pin`, and return an `Identity` whose private
|
||||
/// operations run on the device. The PIV session lives on a worker thread that
|
||||
/// exits when the returned identity (and its backend) is dropped.
|
||||
pub fn load_hardware_identity(hwid: &HwidConfig, pin: &str) -> Result<Identity, RatkeyError> {
|
||||
let ed_pub = hwid.ed25519_pub_bytes()?;
|
||||
let x_pub = hwid.x25519_pub_bytes()?;
|
||||
let pin = pin.to_string();
|
||||
|
||||
let (cmd_tx, cmd_rx) = mpsc::channel::<Cmd>();
|
||||
let (ready_tx, ready_rx) = mpsc::channel::<Result<(), RatkeyError>>();
|
||||
|
||||
thread::Builder::new()
|
||||
.name("ratkey-piv".to_string())
|
||||
.spawn(move || {
|
||||
let mut session = match PivSession::<PcscTransport>::connect() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
let _ = ready_tx.send(Err(e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Fail closed: the device's slot keys must match the .hwid.
|
||||
match (
|
||||
session.read_public_key(SLOT_AUTHENTICATION),
|
||||
session.read_public_key(SLOT_KEY_MANAGEMENT),
|
||||
) {
|
||||
(Ok(de), Ok(dx)) if de == ed_pub && dx == x_pub => {}
|
||||
(Ok(_), Ok(_)) => {
|
||||
let _ = ready_tx.send(Err(RatkeyError::KeyMismatch));
|
||||
return;
|
||||
}
|
||||
(Err(e), _) | (_, Err(e)) => {
|
||||
let _ = ready_tx.send(Err(e));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Err(e) = session.verify_pin(&pin) {
|
||||
let _ = ready_tx.send(Err(e));
|
||||
return;
|
||||
}
|
||||
let _ = ready_tx.send(Ok(()));
|
||||
|
||||
// Serve sign/ECDH until the backend is dropped (sender closed).
|
||||
while let Ok(cmd) = cmd_rx.recv() {
|
||||
match cmd {
|
||||
Cmd::Sign { message, reply } => {
|
||||
let _ =
|
||||
reply.send(session.sign_ed25519(SLOT_AUTHENTICATION, &message).ok());
|
||||
}
|
||||
Cmd::Ecdh { peer_pub, reply } => {
|
||||
let _ =
|
||||
reply.send(session.ecdh_x25519(SLOT_KEY_MANAGEMENT, &peer_pub).ok());
|
||||
}
|
||||
Cmd::Lock { reply } => {
|
||||
let locked = session.lock().is_ok();
|
||||
tracing::debug!(locked, "PIV applet re-selected (PIN cache dropped)");
|
||||
let _ = reply.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|e| RatkeyError::Io(std::io::Error::other(e.to_string())))?;
|
||||
|
||||
// Wait for the worker to connect, match, and unlock before handing back.
|
||||
ready_rx.recv().map_err(|_| RatkeyError::NoDevice)??;
|
||||
|
||||
let mut pub64 = [0u8; 64];
|
||||
pub64[..32].copy_from_slice(&x_pub);
|
||||
pub64[32..].copy_from_slice(&ed_pub);
|
||||
Identity::from_backend(
|
||||
&pub64,
|
||||
Arc::new(HardwareBackend {
|
||||
cmd_tx: Mutex::new(cmd_tx),
|
||||
}),
|
||||
)
|
||||
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot build identity: {e}")))
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
//! PC/SC reader enumeration; filters to YubiKey 5 / Nitrokey 3 by reader name.
|
||||
|
||||
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::error::RatkeyError;
|
||||
//! Device classification (always available) + PC/SC reader enumeration (behind `hardware`).
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DeviceInfo {
|
||||
@@ -47,6 +42,14 @@ pub fn detect_device_type(reader_name: &str) -> DeviceType {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
use crate::error::RatkeyError;
|
||||
#[cfg(feature = "hardware")]
|
||||
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
|
||||
#[cfg(feature = "hardware")]
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
pub fn list_readers() -> Result<Vec<String>, RatkeyError> {
|
||||
let ctx = Context::establish(Scope::User)?;
|
||||
|
||||
@@ -64,6 +67,7 @@ pub fn list_readers() -> Result<Vec<String>, RatkeyError> {
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
pub fn detect_devices() -> Result<Vec<DeviceInfo>, RatkeyError> {
|
||||
let readers = list_readers()?;
|
||||
let mut devices = Vec::new();
|
||||
@@ -101,6 +105,7 @@ pub fn detect_devices() -> Result<Vec<DeviceInfo>, RatkeyError> {
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
fn try_connect_piv(reader_name: &str) -> Result<DeviceInfo, RatkeyError> {
|
||||
use crate::apdu;
|
||||
|
||||
@@ -150,6 +155,7 @@ fn try_connect_piv(reader_name: &str) -> Result<DeviceInfo, RatkeyError> {
|
||||
|
||||
/// Best-effort serial/firmware read. Yubico proprietary INS — Nitrokey 3 returns (None, None).
|
||||
/// APDU errors are tolerated; never fails a connection.
|
||||
#[cfg(feature = "hardware")]
|
||||
pub(crate) fn read_identity(card: &Card, device_type: DeviceType) -> (Option<u32>, Option<String>) {
|
||||
use crate::apdu;
|
||||
|
||||
|
||||
@@ -11,10 +11,20 @@ pub enum RatkeyError {
|
||||
#[error("PIN verification failed ({remaining} attempts remaining)")]
|
||||
PinFailed { remaining: u8 },
|
||||
|
||||
/// PIN locked (retry counter exhausted); PUK required to unlock.
|
||||
#[error("PIN locked — device requires PUK to unlock")]
|
||||
/// PIN locked (retry counter exhausted); PIV reset or recovery-code unlock required.
|
||||
#[error("PIN locked — reset the PIV application to recover")]
|
||||
PinLocked,
|
||||
|
||||
#[error("PIV recovery code failed ({remaining} attempts remaining)")]
|
||||
PukFailed { remaining: u8 },
|
||||
|
||||
/// Recovery counter exhausted; PIV reset is required.
|
||||
#[error("PIV recovery counter locked — reset the PIV application to recover")]
|
||||
PukLocked,
|
||||
|
||||
#[error("PIV reset requires both retry counters to be blocked")]
|
||||
ResetRequiresBlockedPinAndPuk,
|
||||
|
||||
#[error("PIN required — call verify_pin() first")]
|
||||
PinRequired,
|
||||
|
||||
@@ -36,6 +46,9 @@ pub enum RatkeyError {
|
||||
#[error("key mismatch: hardware public key does not match .hwid file")]
|
||||
KeyMismatch,
|
||||
|
||||
#[error("management key authentication failed")]
|
||||
ManagementAuthFailed,
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
#[error("PC/SC error: {0}")]
|
||||
Pcsc(#[from] pcsc::Error),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! `HardwareIdentity`: public-key-only `Identity` + PIV session for private ops.
|
||||
//! Wire-compatible with software identities.
|
||||
//! `HardwareIdentity`: a public-key-only `Identity` whose private ops are served
|
||||
//! by an `IdentityBackend` (real PIV session or mock). Wire-compatible with
|
||||
//! software identities.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
@@ -7,71 +8,128 @@ use rns_crypto::hkdf::derive_key_64;
|
||||
use rns_crypto::token;
|
||||
use rns_identity::identity::Identity;
|
||||
|
||||
use crate::apdu::{SLOT_AUTHENTICATION as SLOT_9A, SLOT_KEY_MANAGEMENT as SLOT_9D};
|
||||
use crate::error::RatkeyError;
|
||||
use crate::hwid::HwidConfig;
|
||||
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D};
|
||||
use crate::mock::MockPivSession;
|
||||
use crate::session::PivSession;
|
||||
use crate::transport::PivTransport;
|
||||
|
||||
/// The private-key operations `HardwareIdentity` needs from a token. Implemented
|
||||
/// by `PivSession<T>` (any transport) and `MockPivSession`, so the runtime
|
||||
/// identity is backend-agnostic.
|
||||
pub trait IdentityBackend {
|
||||
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError>;
|
||||
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError>;
|
||||
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>;
|
||||
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>;
|
||||
fn is_connected(&self) -> bool;
|
||||
/// Re-lock the session (require PIN again on the next op).
|
||||
fn lock(&mut self) -> Result<(), RatkeyError>;
|
||||
}
|
||||
|
||||
// Inherent methods take precedence over trait methods, so these delegate without recursing.
|
||||
impl<T: PivTransport> IdentityBackend for PivSession<T> {
|
||||
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
|
||||
self.sign_ed25519(slot, message)
|
||||
}
|
||||
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
|
||||
self.ecdh_x25519(slot, peer_pub)
|
||||
}
|
||||
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
|
||||
self.read_public_key(slot)
|
||||
}
|
||||
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
|
||||
self.read_public_key(slot)
|
||||
}
|
||||
fn is_connected(&self) -> bool {
|
||||
self.is_connected()
|
||||
}
|
||||
fn lock(&mut self) -> Result<(), RatkeyError> {
|
||||
self.lock()
|
||||
}
|
||||
}
|
||||
|
||||
impl IdentityBackend for MockPivSession {
|
||||
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
|
||||
self.sign_ed25519(slot, message)
|
||||
}
|
||||
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
|
||||
self.ecdh_x25519(slot, peer_pub)
|
||||
}
|
||||
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
|
||||
MockPivSession::read_ed25519_public(self, slot)
|
||||
}
|
||||
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
|
||||
MockPivSession::read_x25519_public(self, slot)
|
||||
}
|
||||
fn is_connected(&self) -> bool {
|
||||
self.is_connected()
|
||||
}
|
||||
fn lock(&mut self) -> Result<(), RatkeyError> {
|
||||
self.lock();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HardwareIdentity {
|
||||
pub identity: Identity,
|
||||
pub config: HwidConfig,
|
||||
ed25519_pub: [u8; 32],
|
||||
x25519_pub: [u8; 32],
|
||||
// Mock session storage keeps the current API testable until the real PIV
|
||||
// backend is wired. See crates/rns-ratkey/HARDWARE_STATUS.md.
|
||||
mock_session: Option<MockPivSession>,
|
||||
backend: Box<dyn IdentityBackend>,
|
||||
}
|
||||
|
||||
impl HardwareIdentity {
|
||||
pub fn from_hwid_mock(
|
||||
/// Build from a `.hwid` config + a backend. Fail-closed: the device's slot
|
||||
/// public keys must match the published identity.
|
||||
pub fn from_hwid(
|
||||
config: HwidConfig,
|
||||
session: MockPivSession,
|
||||
mut backend: Box<dyn IdentityBackend>,
|
||||
) -> Result<Self, RatkeyError> {
|
||||
let ed25519_pub = config.ed25519_pub_bytes()?;
|
||||
let x25519_pub = config.x25519_pub_bytes()?;
|
||||
|
||||
// Fail closed: published identity hash must map to keys actually on the device.
|
||||
let session_ed = session.read_ed25519_public(SLOT_9A)?;
|
||||
let session_x = session.read_x25519_public(SLOT_9D)?;
|
||||
let session_ed = backend.read_ed25519_public(SLOT_9A)?;
|
||||
let session_x = backend.read_x25519_public(SLOT_9D)?;
|
||||
if session_ed != ed25519_pub || session_x != x25519_pub {
|
||||
return Err(RatkeyError::KeyMismatch);
|
||||
}
|
||||
|
||||
let mut pub_key_bytes = [0u8; 64];
|
||||
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
|
||||
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
|
||||
let identity = Identity::from_public_key(&pub_key_bytes)
|
||||
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
|
||||
|
||||
let identity = build_identity(&ed25519_pub, &x25519_pub)?;
|
||||
Ok(Self {
|
||||
identity,
|
||||
config,
|
||||
ed25519_pub,
|
||||
x25519_pub,
|
||||
mock_session: Some(session),
|
||||
backend,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn from_file_mock(path: &Path, session: MockPivSession) -> Result<Self, RatkeyError> {
|
||||
pub fn from_file(path: &Path, backend: Box<dyn IdentityBackend>) -> Result<Self, RatkeyError> {
|
||||
let config = HwidConfig::from_file(path)?;
|
||||
Self::from_hwid_mock(config, session)
|
||||
Self::from_hwid(config, backend)
|
||||
}
|
||||
|
||||
/// Test-only: build without `.hwid`; skips key-mismatch guard.
|
||||
pub fn from_keys_mock(
|
||||
/// Test / first-bring-up: build without a `.hwid` and skip the key-mismatch
|
||||
/// guard, so sign/ECDH can be validated independently of metadata pubkey
|
||||
/// readback.
|
||||
pub fn from_keys(
|
||||
ed25519_pub: [u8; 32],
|
||||
x25519_pub: [u8; 32],
|
||||
session: MockPivSession,
|
||||
backend: Box<dyn IdentityBackend>,
|
||||
) -> Result<Self, RatkeyError> {
|
||||
let identity = build_identity(&ed25519_pub, &x25519_pub)?;
|
||||
let config = HwidConfig {
|
||||
identity: crate::hwid::HwidIdentity {
|
||||
hash: String::new(),
|
||||
hash: hex::encode(identity.hash),
|
||||
nickname: "test".to_string(),
|
||||
created_at: 0,
|
||||
},
|
||||
device: crate::hwid::HwidDevice {
|
||||
device_type: session.device_type.clone(),
|
||||
serial: session.serial,
|
||||
firmware: session.firmware.clone(),
|
||||
device_type: "unknown".to_string(),
|
||||
serial: 0,
|
||||
firmware: "unknown".to_string(),
|
||||
},
|
||||
keys: crate::hwid::HwidKeys {
|
||||
ed25519_pub: hex::encode(ed25519_pub),
|
||||
@@ -91,22 +149,12 @@ impl HardwareIdentity {
|
||||
backup: Default::default(),
|
||||
};
|
||||
|
||||
let mut pub_key_bytes = [0u8; 64];
|
||||
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
|
||||
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
|
||||
let identity = Identity::from_public_key(&pub_key_bytes)
|
||||
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
|
||||
|
||||
let mut config = config;
|
||||
// Hash is derived from the Identity so the .hwid stays consistent.
|
||||
config.identity.hash = hex::encode(identity.hash);
|
||||
|
||||
Ok(Self {
|
||||
identity,
|
||||
config,
|
||||
ed25519_pub,
|
||||
x25519_pub,
|
||||
mock_session: Some(session),
|
||||
backend,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -136,13 +184,11 @@ impl HardwareIdentity {
|
||||
}
|
||||
|
||||
pub fn sign(&mut self, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
|
||||
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
|
||||
session.sign_ed25519(SLOT_9A, message)
|
||||
self.backend.sign_ed25519(SLOT_9A, message)
|
||||
}
|
||||
|
||||
pub fn ecdh(&mut self, peer_pub_bytes: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
|
||||
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
|
||||
session.ecdh_x25519(SLOT_9D, peer_pub_bytes)
|
||||
self.backend.ecdh_x25519(SLOT_9D, peer_pub_bytes)
|
||||
}
|
||||
|
||||
/// Ciphertext = ephemeral_pub(32) || AES-256-CBC token. Mirrors `Identity::decrypt`
|
||||
@@ -190,23 +236,38 @@ impl HardwareIdentity {
|
||||
}
|
||||
|
||||
pub fn is_connected(&self) -> bool {
|
||||
self.mock_session.as_ref().is_some_and(|s| s.is_connected())
|
||||
self.backend.is_connected()
|
||||
}
|
||||
|
||||
/// Re-lock the session; the next sign/ECDH will require the PIN again.
|
||||
/// The app calls this on its session timeout and on quit.
|
||||
pub fn lock(&mut self) -> Result<(), RatkeyError> {
|
||||
self.backend.lock()
|
||||
}
|
||||
}
|
||||
|
||||
fn build_identity(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> Result<Identity, RatkeyError> {
|
||||
let mut pub_key_bytes = [0u8; 64];
|
||||
pub_key_bytes[..32].copy_from_slice(x25519_pub);
|
||||
pub_key_bytes[32..].copy_from_slice(ed25519_pub);
|
||||
Identity::from_public_key(&pub_key_bytes)
|
||||
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::mock::{SLOT_9A as MOCK_9A, SLOT_9D as MOCK_9D};
|
||||
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
|
||||
use rns_identity::identity::Identity;
|
||||
|
||||
#[test]
|
||||
fn test_from_keys_mock() {
|
||||
fn test_from_keys() {
|
||||
let session = MockPivSession::with_keys();
|
||||
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
|
||||
let hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
|
||||
let hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
assert_eq!(hw.ed25519_public(), &ed_pub);
|
||||
assert_eq!(hw.x25519_public(), &x_pub);
|
||||
assert!(!hw.hash_hex().is_empty());
|
||||
@@ -215,9 +276,9 @@ mod tests {
|
||||
#[test]
|
||||
fn test_sign_and_verify() {
|
||||
let session = MockPivSession::with_keys();
|
||||
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
|
||||
let message = b"ratkey hardware identity test";
|
||||
let sig = hw.sign(message).unwrap();
|
||||
@@ -231,9 +292,9 @@ mod tests {
|
||||
let ed_seed = [0x42u8; 32];
|
||||
let x_secret = [0x43u8; 32];
|
||||
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
|
||||
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
|
||||
let mut prv_bytes = [0u8; 64];
|
||||
prv_bytes[..32].copy_from_slice(&x_secret);
|
||||
@@ -256,9 +317,9 @@ mod tests {
|
||||
#[test]
|
||||
fn test_ecdh_with_software_peer() {
|
||||
let session = MockPivSession::with_keys();
|
||||
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
|
||||
let peer_prv = X25519PrivateKey::generate();
|
||||
let peer_pub = peer_prv.public_key();
|
||||
@@ -277,9 +338,9 @@ mod tests {
|
||||
let ed_seed = [0x42u8; 32];
|
||||
let x_secret = [0x43u8; 32];
|
||||
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
|
||||
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
|
||||
let mut prv_bytes = [0u8; 64];
|
||||
prv_bytes[..32].copy_from_slice(&x_secret);
|
||||
@@ -296,9 +357,9 @@ mod tests {
|
||||
#[test]
|
||||
fn test_encrypt_from_other_identity() {
|
||||
let session = MockPivSession::with_keys();
|
||||
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
|
||||
let _sender = Identity::new();
|
||||
|
||||
@@ -310,27 +371,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_disconnect_fails_operations() {
|
||||
let session = MockPivSession::with_keys();
|
||||
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
|
||||
let mut session = MockPivSession::with_keys();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
session.disconnect();
|
||||
|
||||
assert!(hw.is_connected());
|
||||
hw.mock_session.as_mut().unwrap().disconnect();
|
||||
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
assert!(!hw.is_connected());
|
||||
|
||||
assert!(matches!(hw.sign(b"test"), Err(RatkeyError::Disconnected)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_key_mismatch_rejected() {
|
||||
// from_keys_mock does not cross-check; the .hwid path does (test_hwid_key_mismatch).
|
||||
let session = MockPivSession::with_keys();
|
||||
let wrong_ed = [0xFFu8; 32];
|
||||
let wrong_x = [0xFFu8; 32];
|
||||
let _result = HardwareIdentity::from_keys_mock(wrong_ed, wrong_x, session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hwid_key_mismatch() {
|
||||
let session = MockPivSession::with_keys();
|
||||
@@ -363,7 +413,245 @@ mod tests {
|
||||
backup: Default::default(),
|
||||
};
|
||||
|
||||
let result = HardwareIdentity::from_hwid_mock(config, session);
|
||||
let result = HardwareIdentity::from_hwid(config, Box::new(session));
|
||||
assert!(matches!(result, Err(RatkeyError::KeyMismatch)));
|
||||
}
|
||||
|
||||
// --- Real backend path over a canned-APDU transport ---------------------
|
||||
// MockPivSession implements IdentityBackend directly and never touches
|
||||
// PivSession. These exercise the production path (PivSession ops + its
|
||||
// IdentityBackend impl + read_public_key→parse + slot routing) without a
|
||||
// device. Caveat: the fake uses the *assumed* metadata layout, so it
|
||||
// validates glue, not the real byte layout — that stays hardware-only.
|
||||
|
||||
use crate::detect::DeviceType;
|
||||
use crate::session::DeviceMeta;
|
||||
use crate::transport::PivTransport;
|
||||
|
||||
struct FakeTransport {
|
||||
ed_pub: [u8; 32],
|
||||
x_pub: [u8; 32],
|
||||
sig: [u8; 64],
|
||||
secret: [u8; 32],
|
||||
}
|
||||
|
||||
impl FakeTransport {
|
||||
fn metadata(key: &[u8; 32]) -> Vec<u8> {
|
||||
// 01(algo) 04(pubkey = 86 20 <32>) + SW 90 00
|
||||
let mut v = vec![0x01, 0x01, 0xE0, 0x04, 0x22, 0x86, 0x20];
|
||||
v.extend_from_slice(key);
|
||||
v.extend_from_slice(&[0x90, 0x00]);
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl PivTransport for FakeTransport {
|
||||
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
let (ins, p1, p2) = (apdu[1], apdu[2], apdu[3]);
|
||||
match ins {
|
||||
0xA4 => Ok(vec![0x90, 0x00]), // SELECT (applet / re-lock)
|
||||
0x20 => Ok(vec![0x90, 0x00]), // VERIFY PIN
|
||||
0x87 if p1 == 0xE0 => {
|
||||
assert_eq!(p2, 0x9A, "sign must target slot 9A");
|
||||
let mut v = vec![0x7C, 0x42, 0x82, 0x40];
|
||||
v.extend_from_slice(&self.sig);
|
||||
v.extend_from_slice(&[0x90, 0x00]);
|
||||
Ok(v)
|
||||
}
|
||||
0x87 if p1 == 0xE1 => {
|
||||
assert_eq!(p2, 0x9D, "ECDH must target slot 9D");
|
||||
let mut v = vec![0x7C, 0x22, 0x82, 0x20];
|
||||
v.extend_from_slice(&self.secret);
|
||||
v.extend_from_slice(&[0x90, 0x00]);
|
||||
Ok(v)
|
||||
}
|
||||
0xF7 => {
|
||||
// GET METADATA: key keyed by requested slot, so a wrong-slot
|
||||
// read returns the wrong key.
|
||||
let key = match p2 {
|
||||
0x9A => &self.ed_pub,
|
||||
0x9D => &self.x_pub,
|
||||
other => panic!("unexpected metadata slot 0x{other:02X}"),
|
||||
};
|
||||
Ok(Self::metadata(key))
|
||||
}
|
||||
other => panic!("unexpected INS 0x{other:02X}"),
|
||||
}
|
||||
}
|
||||
fn is_connected(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_meta() -> DeviceMeta {
|
||||
DeviceMeta {
|
||||
device_type: DeviceType::YubiKey5,
|
||||
serial: Some(1),
|
||||
firmware: Some("5.7.4".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pivsession_ops_over_fake_transport() {
|
||||
let ed_pub = [0x11u8; 32];
|
||||
let x_pub = [0x22u8; 32];
|
||||
let sig = [0x33u8; 64];
|
||||
let secret = [0x44u8; 32];
|
||||
let fake = FakeTransport {
|
||||
ed_pub,
|
||||
x_pub,
|
||||
sig,
|
||||
secret,
|
||||
};
|
||||
let mut session = PivSession::new(fake, fake_meta());
|
||||
|
||||
assert_eq!(session.sign_ed25519(SLOT_9A, b"msg").unwrap(), sig);
|
||||
assert_eq!(session.ecdh_x25519(SLOT_9D, &[0u8; 32]).unwrap(), secret);
|
||||
// read_public_key routes the slot and runs the metadata parser.
|
||||
assert_eq!(session.read_public_key(SLOT_9A).unwrap(), ed_pub);
|
||||
assert_eq!(session.read_public_key(SLOT_9D).unwrap(), x_pub);
|
||||
// lock() re-selects the applet (SELECT APDU) without error.
|
||||
session.lock().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lock_requires_pin_again() {
|
||||
// End-to-end session lock on the mock path: sign works, lock, then the
|
||||
// next op needs the PIN again.
|
||||
let session = MockPivSession::with_keys();
|
||||
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
|
||||
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
|
||||
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
|
||||
|
||||
assert!(hw.sign(b"m").is_ok());
|
||||
hw.lock().unwrap();
|
||||
assert!(matches!(hw.sign(b"m"), Err(RatkeyError::PinRequired)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hardware_identity_from_hwid_over_real_backend() {
|
||||
// Closest mock-free representation of the runtime path: HardwareIdentity
|
||||
// over a real PivSession backend — guard reads pubkeys via metadata, then
|
||||
// sign dispatches to slot 9A.
|
||||
let ed_prv = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[0x42u8; 32]);
|
||||
let ed_pub = ed_prv.public_key().to_bytes();
|
||||
let x_prv = X25519PrivateKey::from_bytes(&[0x43u8; 32]);
|
||||
let x_pub = x_prv.public_key().to_bytes();
|
||||
let sig = [0x33u8; 64];
|
||||
|
||||
let fake = FakeTransport {
|
||||
ed_pub,
|
||||
x_pub,
|
||||
sig,
|
||||
secret: [0x44u8; 32],
|
||||
};
|
||||
let session = PivSession::new(fake, fake_meta());
|
||||
|
||||
let config = HwidConfig {
|
||||
identity: crate::hwid::HwidIdentity {
|
||||
hash: "test".to_string(),
|
||||
nickname: "fake".to_string(),
|
||||
created_at: 0,
|
||||
},
|
||||
device: crate::hwid::HwidDevice {
|
||||
device_type: "yubikey5".to_string(),
|
||||
serial: 1,
|
||||
firmware: "5.7.4".to_string(),
|
||||
},
|
||||
keys: crate::hwid::HwidKeys {
|
||||
ed25519_pub: hex::encode(ed_pub),
|
||||
x25519_pub: hex::encode(x_pub),
|
||||
},
|
||||
slots: crate::hwid::HwidSlots {
|
||||
signing: "9A".to_string(),
|
||||
encryption: "9D".to_string(),
|
||||
},
|
||||
policy: crate::hwid::HwidPolicy {
|
||||
pin_cache_timeout: 300,
|
||||
touch_signing: "always".to_string(),
|
||||
touch_encryption: "cached".to_string(),
|
||||
},
|
||||
attestation: Default::default(),
|
||||
app: Default::default(),
|
||||
backup: Default::default(),
|
||||
};
|
||||
|
||||
let mut hw = HardwareIdentity::from_hwid(config, Box::new(session)).unwrap();
|
||||
assert_eq!(hw.sign(b"announce").unwrap(), sig);
|
||||
}
|
||||
|
||||
// --- Management-key auth over a card-simulating transport ----------------
|
||||
// Plays the card side of witness/challenge so the protocol direction (host
|
||||
// must DECRYPT the witness, not encrypt it) is exercised without hardware.
|
||||
struct MgmtFakeTransport {
|
||||
alg: u8,
|
||||
key: Vec<u8>,
|
||||
witness: [u8; 16],
|
||||
}
|
||||
|
||||
fn wrap_7c(tag: u8, payload: &[u8]) -> Vec<u8> {
|
||||
let mut v = vec![0x7C, (payload.len() + 2) as u8, tag, payload.len() as u8];
|
||||
v.extend_from_slice(payload);
|
||||
v.extend_from_slice(&[0x90, 0x00]); // SW OK
|
||||
v
|
||||
}
|
||||
|
||||
impl PivTransport for MgmtFakeTransport {
|
||||
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
let (ins, p2) = (apdu[1], apdu[3]);
|
||||
match (ins, p2) {
|
||||
(0xF7, 0x9B) => Ok(vec![0x01, 0x01, self.alg, 0x90, 0x00]), // metadata: alg
|
||||
(0x87, 0x9B) => {
|
||||
let data = &apdu[5..];
|
||||
let witness_field = crate::apdu::parse_auth_witness(data).unwrap();
|
||||
if witness_field.is_empty() {
|
||||
// witness request → return the witness encrypted with the key
|
||||
let enc =
|
||||
crate::mgmt::ecb_encrypt(self.alg, &self.key, &self.witness).unwrap();
|
||||
Ok(wrap_7c(0x80, &enc))
|
||||
} else if witness_field.as_slice() == self.witness {
|
||||
// correct decrypted witness → encrypt the host's challenge
|
||||
let challenge = &data[data.len() - 16..];
|
||||
let enc = crate::mgmt::ecb_encrypt(self.alg, &self.key, challenge).unwrap();
|
||||
Ok(wrap_7c(0x82, &enc))
|
||||
} else {
|
||||
// wrong witness → card rejects (security status not satisfied)
|
||||
Ok(vec![0x69, 0x82])
|
||||
}
|
||||
}
|
||||
_ => panic!("unexpected mgmt apdu ins=0x{ins:02X} p2=0x{p2:02X}"),
|
||||
}
|
||||
}
|
||||
fn is_connected(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_authenticate_management_key_success() {
|
||||
let key = vec![0x5Au8; 24]; // AES-192
|
||||
let fake = MgmtFakeTransport {
|
||||
alg: crate::apdu::MGMT_ALG_AES192,
|
||||
key: key.clone(),
|
||||
witness: [0x77; 16],
|
||||
};
|
||||
let mut session = PivSession::new(fake, fake_meta());
|
||||
session.authenticate_management_key(&key).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_authenticate_management_key_wrong_key() {
|
||||
// Host's wrong key → decrypted witness mismatches → card rejects → mapped error.
|
||||
let fake = MgmtFakeTransport {
|
||||
alg: crate::apdu::MGMT_ALG_AES192,
|
||||
key: vec![0x5Au8; 24],
|
||||
witness: [0x77; 16],
|
||||
};
|
||||
let mut session = PivSession::new(fake, fake_meta());
|
||||
let wrong = vec![0x00u8; 24];
|
||||
assert!(matches!(
|
||||
session.authenticate_management_key(&wrong),
|
||||
Err(RatkeyError::ManagementAuthFailed)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,40 @@
|
||||
//! Hardware-backed identity (YubiKey 5, Nitrokey 3) via PIV. Ed25519 sign + X25519
|
||||
//! ECDH keys live on-device; only public keys and results leave the token.
|
||||
//! Wire-compatible with software identities. `hardware` feature enables real PIV via `pcsc`.
|
||||
//! Wire-compatible with software identities.
|
||||
//!
|
||||
//! The PIV protocol logic (`PivSession`, `apdu`) is transport-agnostic; the
|
||||
//! `PivTransport` seam isolates platform access. The `hardware` feature adds the
|
||||
//! PC/SC transport (`PcscTransport`) and its `connect()` entry points. Mobile
|
||||
//! NFC/USB transports implement `PivTransport` from the application layer.
|
||||
|
||||
pub mod apdu;
|
||||
pub mod attestation;
|
||||
#[cfg(feature = "hardware")]
|
||||
pub mod backend;
|
||||
pub mod detect;
|
||||
pub mod error;
|
||||
pub mod hardware;
|
||||
pub mod hwid;
|
||||
pub mod mgmt;
|
||||
pub mod mock;
|
||||
pub mod pin;
|
||||
pub mod provision;
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
pub mod detect;
|
||||
#[cfg(feature = "hardware")]
|
||||
pub mod seed;
|
||||
pub mod session;
|
||||
pub mod transport;
|
||||
|
||||
pub use error::RatkeyError;
|
||||
pub use hardware::HardwareIdentity;
|
||||
pub use hardware::{HardwareIdentity, IdentityBackend};
|
||||
pub use hwid::HwidConfig;
|
||||
pub use mock::MockPivSession;
|
||||
pub use pin::PinCache;
|
||||
pub use provision::{ProvisionConfig, ProvisionResult};
|
||||
pub use session::{DeviceMeta, PivSession};
|
||||
pub use transport::PivTransport;
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
pub use backend::{HardwareBackend, load_hardware_identity};
|
||||
#[cfg(feature = "hardware")]
|
||||
pub use session::PcscPivSession;
|
||||
#[cfg(feature = "hardware")]
|
||||
pub use transport::PcscTransport;
|
||||
@@ -0,0 +1,203 @@
|
||||
//! PIV management-key crypto: ECB single/multi-block for the witness/challenge
|
||||
//! mutual authentication. Dispatch is on the management-key *algorithm* byte, not
|
||||
//! the key length — AES-192 and TDES both use 24-byte keys, but differ in block
|
||||
//! size (AES 16, TDES 8). TDES (3DES EDE3) is the pre-5.7 YubiKey factory default.
|
||||
|
||||
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
|
||||
use aes::{Aes128, Aes192, Aes256};
|
||||
use des::TdesEde3;
|
||||
|
||||
use crate::apdu;
|
||||
use crate::error::RatkeyError;
|
||||
|
||||
const AES_BLOCK: usize = 16;
|
||||
const DES_BLOCK: usize = 8;
|
||||
|
||||
/// Required key length for a management-key algorithm, or `None` if unsupported.
|
||||
pub fn key_len(alg: u8) -> Option<usize> {
|
||||
match alg {
|
||||
apdu::MGMT_ALG_TDES => Some(24), // 3DES EDE3: three 8-byte DES subkeys
|
||||
apdu::MGMT_ALG_AES128 => Some(16),
|
||||
apdu::MGMT_ALG_AES192 => Some(24),
|
||||
apdu::MGMT_ALG_AES256 => Some(32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// ECB block size (challenge length) for a supported algorithm.
|
||||
pub fn block_len(alg: u8) -> Option<usize> {
|
||||
match alg {
|
||||
apdu::MGMT_ALG_TDES => Some(DES_BLOCK),
|
||||
apdu::MGMT_ALG_AES128 | apdu::MGMT_ALG_AES192 | apdu::MGMT_ALG_AES256 => Some(AES_BLOCK),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn check(alg: u8, key: &[u8], data: &[u8]) -> Result<(), RatkeyError> {
|
||||
let n = key_len(alg).ok_or_else(|| {
|
||||
RatkeyError::UnsupportedDevice(format!("unsupported management-key algorithm 0x{alg:02X}"))
|
||||
})?;
|
||||
if key.len() != n {
|
||||
return Err(RatkeyError::InvalidHwid(format!(
|
||||
"management key length {} does not match algorithm 0x{alg:02X} (expected {n})",
|
||||
key.len()
|
||||
)));
|
||||
}
|
||||
let block = block_len(alg).expect("supported alg has a block size");
|
||||
if data.is_empty() || data.len() % block != 0 {
|
||||
return Err(RatkeyError::InvalidHwid(format!(
|
||||
"management-key ECB input not block-aligned: {} bytes (block {block})",
|
||||
data.len()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn ecb_encrypt(alg: u8, key: &[u8], data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
check(alg, key, data)?;
|
||||
let mut out = data.to_vec();
|
||||
process(alg, key, &mut out, false)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn ecb_decrypt(alg: u8, key: &[u8], data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
check(alg, key, data)?;
|
||||
let mut out = data.to_vec();
|
||||
process(alg, key, &mut out, true)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn process(alg: u8, key: &[u8], buf: &mut [u8], decrypt: bool) -> Result<(), RatkeyError> {
|
||||
macro_rules! run {
|
||||
($cipher:ty, $block:expr) => {{
|
||||
let cipher = <$cipher>::new_from_slice(key)
|
||||
.map_err(|_| RatkeyError::InvalidHwid("invalid management key".to_string()))?;
|
||||
for chunk in buf.chunks_mut($block) {
|
||||
let block = GenericArray::from_mut_slice(chunk);
|
||||
if decrypt {
|
||||
cipher.decrypt_block(block);
|
||||
} else {
|
||||
cipher.encrypt_block(block);
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
match alg {
|
||||
apdu::MGMT_ALG_TDES => run!(TdesEde3, DES_BLOCK),
|
||||
apdu::MGMT_ALG_AES128 => run!(Aes128, AES_BLOCK),
|
||||
apdu::MGMT_ALG_AES192 => run!(Aes192, AES_BLOCK),
|
||||
apdu::MGMT_ALG_AES256 => run!(Aes256, AES_BLOCK),
|
||||
_ => {
|
||||
return Err(RatkeyError::UnsupportedDevice(format!(
|
||||
"unsupported management-key algorithm 0x{alg:02X}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// FIPS-197 Appendix C.2 AES-192 known-answer vector.
|
||||
const KAT_KEY: [u8; 24] = [
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
|
||||
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
|
||||
];
|
||||
const KAT_PT: [u8; 16] = [
|
||||
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
|
||||
0xff,
|
||||
];
|
||||
const KAT_CT: [u8; 16] = [
|
||||
0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71,
|
||||
0x91,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn test_aes192_kat_encrypt() {
|
||||
assert_eq!(
|
||||
ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &KAT_PT).unwrap(),
|
||||
KAT_CT.to_vec()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_aes192_kat_decrypt() {
|
||||
assert_eq!(
|
||||
ecb_decrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &KAT_CT).unwrap(),
|
||||
KAT_PT.to_vec()
|
||||
);
|
||||
}
|
||||
|
||||
// 3DES EDE3 with three identical 8-byte subkeys reduces to single-DES, so the
|
||||
// canonical FIPS-81 single-DES ECB vector is a known-answer for our EDE3 path:
|
||||
// DES(0x0123456789ABCDEF, "Now is t") = 0x3FA40E8A984D4815.
|
||||
const TDES_KAT_KEY: [u8; 24] = [
|
||||
0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD,
|
||||
0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
|
||||
];
|
||||
const TDES_KAT_PT: [u8; 8] = [0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74];
|
||||
const TDES_KAT_CT: [u8; 8] = [0x3F, 0xA4, 0x0E, 0x8A, 0x98, 0x4D, 0x48, 0x15];
|
||||
|
||||
#[test]
|
||||
fn test_round_trip_all_aes() {
|
||||
for (alg, klen) in [
|
||||
(apdu::MGMT_ALG_AES128, 16usize),
|
||||
(apdu::MGMT_ALG_AES192, 24),
|
||||
(apdu::MGMT_ALG_AES256, 32),
|
||||
] {
|
||||
let key = vec![0x5Au8; klen];
|
||||
let pt = [0x42u8; 16];
|
||||
let ct = ecb_encrypt(alg, &key, &pt).unwrap();
|
||||
assert_ne!(ct, pt.to_vec());
|
||||
assert_eq!(ecb_decrypt(alg, &key, &ct).unwrap(), pt.to_vec());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrong_key_length_rejected() {
|
||||
// AES-192 with a 16-byte key (would silently be AES-128 if not checked).
|
||||
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &[0u8; 16], &[0u8; 16]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tdes_kat() {
|
||||
assert_eq!(key_len(apdu::MGMT_ALG_TDES), Some(24));
|
||||
assert_eq!(block_len(apdu::MGMT_ALG_TDES), Some(8));
|
||||
assert_eq!(
|
||||
ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &TDES_KAT_PT).unwrap(),
|
||||
TDES_KAT_CT.to_vec()
|
||||
);
|
||||
assert_eq!(
|
||||
ecb_decrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &TDES_KAT_CT).unwrap(),
|
||||
TDES_KAT_PT.to_vec()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tdes_round_trip_distinct_keys() {
|
||||
// Three distinct subkeys exercise the real EDE3 / DED3 inverse, not the
|
||||
// degenerate single-DES reduction.
|
||||
let mut key = [0u8; 24];
|
||||
for (i, b) in key.iter_mut().enumerate() {
|
||||
*b = (i as u8).wrapping_mul(7).wrapping_add(1);
|
||||
}
|
||||
let pt = [0x42u8; 8];
|
||||
let ct = ecb_encrypt(apdu::MGMT_ALG_TDES, &key, &pt).unwrap();
|
||||
assert_ne!(ct, pt.to_vec());
|
||||
assert_eq!(
|
||||
ecb_decrypt(apdu::MGMT_ALG_TDES, &key, &ct).unwrap(),
|
||||
pt.to_vec()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_block_aligned_rejected() {
|
||||
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &[0u8; 15]).is_err());
|
||||
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &[]).is_err());
|
||||
// TDES uses an 8-byte block: 8 is valid, 7 is not.
|
||||
assert!(ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &[0u8; 8]).is_ok());
|
||||
assert!(ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &[0u8; 7]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,8 @@ impl SlotState {
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum MockOperation {
|
||||
PinVerify { success: bool },
|
||||
PinUnblock { success: bool },
|
||||
ResetPiv { success: bool },
|
||||
GenerateEd25519 { slot: u8 },
|
||||
GenerateX25519 { slot: u8 },
|
||||
SignEd25519 { slot: u8, data_len: usize },
|
||||
@@ -56,8 +58,10 @@ pub enum MockOperation {
|
||||
pub struct MockPivSession {
|
||||
slots: HashMap<u8, SlotState>,
|
||||
pin: String,
|
||||
puk: String,
|
||||
pin_verified: bool,
|
||||
pin_retries: u8,
|
||||
puk_retries: u8,
|
||||
max_retries: u8,
|
||||
connected: bool,
|
||||
/// True: `TouchPolicy::Always` slots reject ops. `simulate_touch()` clears.
|
||||
@@ -77,8 +81,10 @@ impl MockPivSession {
|
||||
Self {
|
||||
slots,
|
||||
pin: "123456".to_string(),
|
||||
puk: "12345678".to_string(),
|
||||
pin_verified: false,
|
||||
pin_retries: 3,
|
||||
puk_retries: 3,
|
||||
max_retries: 3,
|
||||
connected: true,
|
||||
touch_required: true,
|
||||
@@ -136,6 +142,10 @@ impl MockPivSession {
|
||||
self.pin_verified = false;
|
||||
}
|
||||
|
||||
pub fn set_puk(&mut self, puk: &str) {
|
||||
self.puk = puk.to_string();
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self) {
|
||||
self.connected = false;
|
||||
}
|
||||
@@ -145,6 +155,12 @@ impl MockPivSession {
|
||||
self.pin_verified = false;
|
||||
}
|
||||
|
||||
/// Re-lock: clears PIN verification so the next op needs `verify_pin` again.
|
||||
/// Mirrors `PivSession::lock` (which re-selects the applet on real hardware).
|
||||
pub fn lock(&mut self) {
|
||||
self.pin_verified = false;
|
||||
}
|
||||
|
||||
pub fn simulate_touch(&mut self) {
|
||||
self.touch_required = false;
|
||||
}
|
||||
@@ -211,6 +227,58 @@ impl MockPivSession {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unblock_pin(&mut self, puk: &str, new_pin: &str) -> Result<(), RatkeyError> {
|
||||
self.check_connected()?;
|
||||
|
||||
if self.puk_retries == 0 {
|
||||
self.operations
|
||||
.push(MockOperation::PinUnblock { success: false });
|
||||
return Err(RatkeyError::PukLocked);
|
||||
}
|
||||
|
||||
if puk == self.puk {
|
||||
self.pin = new_pin.to_string();
|
||||
self.pin_verified = true;
|
||||
self.pin_retries = self.max_retries;
|
||||
self.puk_retries = self.max_retries;
|
||||
self.operations
|
||||
.push(MockOperation::PinUnblock { success: true });
|
||||
Ok(())
|
||||
} else {
|
||||
self.puk_retries -= 1;
|
||||
self.operations
|
||||
.push(MockOperation::PinUnblock { success: false });
|
||||
if self.puk_retries == 0 {
|
||||
Err(RatkeyError::PukLocked)
|
||||
} else {
|
||||
Err(RatkeyError::PukFailed {
|
||||
remaining: self.puk_retries,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset_piv(&mut self) -> Result<(), RatkeyError> {
|
||||
self.check_connected()?;
|
||||
if self.pin_retries != 0 || self.puk_retries != 0 {
|
||||
self.operations
|
||||
.push(MockOperation::ResetPiv { success: false });
|
||||
return Err(RatkeyError::ResetRequiresBlockedPinAndPuk);
|
||||
}
|
||||
|
||||
self.slots.insert(SLOT_9A, SlotState::empty());
|
||||
self.slots.insert(SLOT_9D, SlotState::empty());
|
||||
self.pin = "123456".to_string();
|
||||
self.puk = "12345678".to_string();
|
||||
self.pin_verified = false;
|
||||
self.pin_retries = self.max_retries;
|
||||
self.puk_retries = self.max_retries;
|
||||
self.touch_required = true;
|
||||
self.operations
|
||||
.push(MockOperation::ResetPiv { success: true });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn generate_ed25519(
|
||||
&mut self,
|
||||
slot: u8,
|
||||
@@ -374,6 +442,7 @@ impl Default for MockPivSession {
|
||||
impl Drop for MockPivSession {
|
||||
fn drop(&mut self) {
|
||||
self.pin.zeroize();
|
||||
self.puk.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,6 +481,70 @@ mod tests {
|
||||
assert!(matches!(err, RatkeyError::PinLocked));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pin_unblock_with_puk() {
|
||||
let mut session = MockPivSession::new();
|
||||
let _ = session.verify_pin("wrong");
|
||||
let _ = session.verify_pin("wrong");
|
||||
let _ = session.verify_pin("wrong");
|
||||
assert!(matches!(
|
||||
session.verify_pin("123456"),
|
||||
Err(RatkeyError::PinLocked)
|
||||
));
|
||||
|
||||
session.unblock_pin("12345678", "654321").unwrap();
|
||||
assert!(session.verify_pin("654321").is_ok());
|
||||
assert!(matches!(
|
||||
session.verify_pin("123456"),
|
||||
Err(RatkeyError::PinFailed { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pin_unblock_wrong_puk_locks_puk() {
|
||||
let mut session = MockPivSession::new();
|
||||
let _ = session.verify_pin("wrong");
|
||||
let _ = session.verify_pin("wrong");
|
||||
let _ = session.verify_pin("wrong");
|
||||
|
||||
let err = session.unblock_pin("bad", "654321").unwrap_err();
|
||||
assert!(matches!(err, RatkeyError::PukFailed { remaining: 2 }));
|
||||
let _ = session.unblock_pin("bad", "654321");
|
||||
let err = session.unblock_pin("bad", "654321").unwrap_err();
|
||||
assert!(matches!(err, RatkeyError::PukLocked));
|
||||
assert!(matches!(
|
||||
session.unblock_pin("12345678", "654321"),
|
||||
Err(RatkeyError::PukLocked)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reset_piv_requires_blocked_pin_and_puk() {
|
||||
let mut session = MockPivSession::with_keys();
|
||||
assert!(matches!(
|
||||
session.reset_piv(),
|
||||
Err(RatkeyError::ResetRequiresBlockedPinAndPuk)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reset_piv_clears_keys_and_restores_defaults() {
|
||||
let mut session = MockPivSession::with_keys();
|
||||
let _ = session.verify_pin("badpin");
|
||||
let _ = session.verify_pin("badpin");
|
||||
let _ = session.verify_pin("badpin");
|
||||
let _ = session.unblock_pin("badpuk", "654321");
|
||||
let _ = session.unblock_pin("badpuk", "654321");
|
||||
let _ = session.unblock_pin("badpuk", "654321");
|
||||
|
||||
session.reset_piv().unwrap();
|
||||
session.verify_pin("123456").unwrap();
|
||||
assert!(matches!(
|
||||
session.sign_ed25519(SLOT_9A, b"test"),
|
||||
Err(RatkeyError::EmptySlot { slot: SLOT_9A })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pin_retry_reset() {
|
||||
let mut session = MockPivSession::new();
|
||||
|
||||
@@ -5,9 +5,13 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rns_crypto::sha::truncated_hash;
|
||||
|
||||
use crate::apdu;
|
||||
use crate::error::RatkeyError;
|
||||
use crate::hwid::*;
|
||||
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D, TouchPolicy};
|
||||
use crate::seed;
|
||||
use crate::session::PivSession;
|
||||
use crate::transport::PivTransport;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProvisionResult {
|
||||
@@ -132,6 +136,167 @@ pub fn compute_identity_hash(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> [
|
||||
truncated_hash(&pub_key_bytes)
|
||||
}
|
||||
|
||||
fn touch_byte(tp: TouchPolicy) -> u8 {
|
||||
match tp {
|
||||
TouchPolicy::Never => apdu::TOUCH_POLICY_NEVER,
|
||||
TouchPolicy::Always => apdu::TOUCH_POLICY_ALWAYS,
|
||||
TouchPolicy::Cached => apdu::TOUCH_POLICY_CACHED,
|
||||
}
|
||||
}
|
||||
|
||||
fn touch_str(tp: TouchPolicy) -> &'static str {
|
||||
match tp {
|
||||
TouchPolicy::Never => "never",
|
||||
TouchPolicy::Always => "always",
|
||||
TouchPolicy::Cached => "cached",
|
||||
}
|
||||
}
|
||||
|
||||
/// Recoverable provision / restore: derive the identity from `mnemonic`, import
|
||||
/// both keys into the token (PIN-once + configured touch policy), and write the
|
||||
/// `.hwid`. Requires the management key. The session must already be connected.
|
||||
pub fn import_recoverable_identity<T: PivTransport>(
|
||||
session: &mut PivSession<T>,
|
||||
mgmt_key: &[u8],
|
||||
config: &ProvisionConfig,
|
||||
mnemonic: &str,
|
||||
) -> Result<ProvisionResult, RatkeyError> {
|
||||
let derived = seed::derive_identity(mnemonic)?;
|
||||
session.authenticate_management_key(mgmt_key)?;
|
||||
session.import_ed25519(
|
||||
SLOT_9A,
|
||||
&derived.ed25519_seed,
|
||||
Some(apdu::PIN_POLICY_ONCE),
|
||||
Some(touch_byte(config.touch_signing)),
|
||||
)?;
|
||||
session.import_x25519(
|
||||
SLOT_9D,
|
||||
&derived.x25519_secret,
|
||||
Some(apdu::PIN_POLICY_ONCE),
|
||||
Some(touch_byte(config.touch_encryption)),
|
||||
)?;
|
||||
|
||||
finalize_provision(session, config, derived.ed25519_pub, derived.x25519_pub)
|
||||
}
|
||||
|
||||
/// On-device provisioning (no seed backup): authenticate, generate both keys on
|
||||
/// the token, and write the `.hwid`. Requires the management key.
|
||||
pub fn provision_hardware_only<T: PivTransport>(
|
||||
session: &mut PivSession<T>,
|
||||
mgmt_key: &[u8],
|
||||
config: &ProvisionConfig,
|
||||
) -> Result<ProvisionResult, RatkeyError> {
|
||||
session.authenticate_management_key(mgmt_key)?;
|
||||
let ed_pub = session.generate_ed25519(
|
||||
SLOT_9A,
|
||||
Some(apdu::PIN_POLICY_ONCE),
|
||||
Some(touch_byte(config.touch_signing)),
|
||||
)?;
|
||||
let x_pub = session.generate_x25519(
|
||||
SLOT_9D,
|
||||
Some(apdu::PIN_POLICY_ONCE),
|
||||
Some(touch_byte(config.touch_encryption)),
|
||||
)?;
|
||||
finalize_provision(session, config, ed_pub, x_pub)
|
||||
}
|
||||
|
||||
/// Register an already-provisioned token: read its slot public keys and write a
|
||||
/// `.hwid` for it (import-existing). No key material is created; no mgmt key needed.
|
||||
pub fn read_existing<T: PivTransport>(
|
||||
session: &mut PivSession<T>,
|
||||
config: &ProvisionConfig,
|
||||
) -> Result<ProvisionResult, RatkeyError> {
|
||||
let ed_pub = session.read_public_key(SLOT_9A)?;
|
||||
let x_pub = session.read_public_key(SLOT_9D)?;
|
||||
finalize_provision(session, config, ed_pub, x_pub)
|
||||
}
|
||||
|
||||
/// Build the `.hwid` from the provisioned public keys + device metadata, writing
|
||||
/// it under `config.identities_dir` if set. Shared by all real-hardware flows.
|
||||
fn finalize_provision<T: PivTransport>(
|
||||
session: &PivSession<T>,
|
||||
config: &ProvisionConfig,
|
||||
ed25519_pub: [u8; 32],
|
||||
x25519_pub: [u8; 32],
|
||||
) -> Result<ProvisionResult, RatkeyError> {
|
||||
let identity_hash = compute_identity_hash(&ed25519_pub, &x25519_pub);
|
||||
let identity_hash_hex = hex::encode(identity_hash);
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
|
||||
let hwid = HwidConfig {
|
||||
identity: HwidIdentity {
|
||||
hash: identity_hash_hex.clone(),
|
||||
nickname: config.nickname.clone(),
|
||||
created_at: now,
|
||||
},
|
||||
device: HwidDevice {
|
||||
device_type: session.device_type().as_str().to_string(),
|
||||
serial: session.serial().unwrap_or(0),
|
||||
firmware: session.firmware().unwrap_or("unknown").to_string(),
|
||||
},
|
||||
keys: HwidKeys {
|
||||
ed25519_pub: hex::encode(ed25519_pub),
|
||||
x25519_pub: hex::encode(x25519_pub),
|
||||
},
|
||||
slots: HwidSlots {
|
||||
signing: "9A".to_string(),
|
||||
encryption: "9D".to_string(),
|
||||
},
|
||||
policy: HwidPolicy {
|
||||
pin_cache_timeout: 300,
|
||||
touch_signing: touch_str(config.touch_signing).to_string(),
|
||||
touch_encryption: touch_str(config.touch_encryption).to_string(),
|
||||
},
|
||||
attestation: HwidAttestation::default(),
|
||||
app: HwidApp::default(),
|
||||
backup: HwidBackup::default(),
|
||||
};
|
||||
|
||||
let hwid_path = if let Some(ref dir) = config.identities_dir {
|
||||
let identity_dir = dir.join(&identity_hash_hex);
|
||||
std::fs::create_dir_all(&identity_dir)?;
|
||||
let path = identity_dir.join("identity.hwid");
|
||||
hwid.to_file(&path)?;
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(ProvisionResult {
|
||||
config: hwid,
|
||||
ed25519_pub,
|
||||
x25519_pub,
|
||||
identity_hash,
|
||||
identity_hash_hex,
|
||||
hwid_path,
|
||||
})
|
||||
}
|
||||
|
||||
/// Recoverable provisioning: generate a fresh 12-word mnemonic, import the
|
||||
/// derived identity, and return both the result and the mnemonic to show once.
|
||||
pub fn provision_recoverable<T: PivTransport>(
|
||||
session: &mut PivSession<T>,
|
||||
mgmt_key: &[u8],
|
||||
config: &ProvisionConfig,
|
||||
) -> Result<(ProvisionResult, String), RatkeyError> {
|
||||
let mnemonic = seed::generate_mnemonic()?;
|
||||
let result = import_recoverable_identity(session, mgmt_key, config, &mnemonic)?;
|
||||
Ok((result, mnemonic))
|
||||
}
|
||||
|
||||
/// Restore a recoverable identity from an existing 12-word mnemonic onto a token.
|
||||
pub fn restore<T: PivTransport>(
|
||||
session: &mut PivSession<T>,
|
||||
mgmt_key: &[u8],
|
||||
config: &ProvisionConfig,
|
||||
mnemonic: &str,
|
||||
) -> Result<ProvisionResult, RatkeyError> {
|
||||
import_recoverable_identity(session, mgmt_key, config, mnemonic)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -218,7 +383,7 @@ mod tests {
|
||||
let result = provision_mock(&mut session, &config).unwrap();
|
||||
|
||||
let path = result.hwid_path.as_ref().unwrap();
|
||||
let mut hw = crate::HardwareIdentity::from_file_mock(path, session).unwrap();
|
||||
let mut hw = crate::HardwareIdentity::from_file(path, Box::new(session)).unwrap();
|
||||
|
||||
let message = b"provisioned and loaded";
|
||||
let sig = hw.sign(message).unwrap();
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! BIP-39 recoverable backup: a deterministic Reticulum identity derived from a
|
||||
//! 12-word mnemonic. Interop-compatible with ratkey-py (derivation scheme v1):
|
||||
//!
|
||||
//! ```text
|
||||
//! mnemonic (12 words)
|
||||
//! -> PBKDF2-SHA512 (BIP-39, passphrase="") -> 64-byte seed
|
||||
//! -> HKDF-SHA256(seed, salt="ratkey-ed25519-v1", info) -> 32-byte Ed25519 seed
|
||||
//! -> HKDF-SHA256(seed, salt="ratkey-x25519-v1", info) -> 32-byte X25519 secret
|
||||
//! ```
|
||||
//!
|
||||
//! The seed phrase is a second attack surface (it reconstructs the private keys
|
||||
//! and is not protected by the device PIN). Callers must surface that tradeoff.
|
||||
|
||||
use bip39::{Language, Mnemonic};
|
||||
use hkdf::Hkdf;
|
||||
use sha2::Sha256;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use rns_crypto::ed25519::Ed25519PrivateKey;
|
||||
use rns_crypto::x25519::X25519PrivateKey;
|
||||
|
||||
use crate::error::RatkeyError;
|
||||
|
||||
const ED25519_SALT: &[u8] = b"ratkey-ed25519-v1";
|
||||
const X25519_SALT: &[u8] = b"ratkey-x25519-v1";
|
||||
const HKDF_INFO: &[u8] = b"ratkey identity key derivation";
|
||||
const MNEMONIC_WORDS: usize = 12;
|
||||
const MNEMONIC_ENTROPY_BYTES: usize = 16;
|
||||
|
||||
/// Key material derived from a mnemonic. The two secret fields are zeroized on drop.
|
||||
pub struct DerivedIdentity {
|
||||
pub ed25519_seed: [u8; 32],
|
||||
pub x25519_secret: [u8; 32],
|
||||
pub ed25519_pub: [u8; 32],
|
||||
pub x25519_pub: [u8; 32],
|
||||
}
|
||||
|
||||
impl Drop for DerivedIdentity {
|
||||
fn drop(&mut self) {
|
||||
self.ed25519_seed.zeroize();
|
||||
self.x25519_secret.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a fresh 12-word (128-bit) BIP-39 English mnemonic.
|
||||
pub fn generate_mnemonic() -> Result<String, RatkeyError> {
|
||||
let mut entropy = [0u8; MNEMONIC_ENTROPY_BYTES];
|
||||
entropy.copy_from_slice(&rns_crypto::random::random_bytes(MNEMONIC_ENTROPY_BYTES));
|
||||
let result = Mnemonic::from_entropy_in(Language::English, &entropy)
|
||||
.map(|m| m.to_string())
|
||||
.map_err(|e| RatkeyError::InvalidHwid(format!("mnemonic generation failed: {e}")));
|
||||
entropy.zeroize();
|
||||
result
|
||||
}
|
||||
|
||||
/// True for a valid 12-word BIP-39 English mnemonic (wordlist + checksum).
|
||||
pub fn validate_mnemonic(words: &str) -> bool {
|
||||
let w = words.trim();
|
||||
w.split_whitespace().count() == MNEMONIC_WORDS
|
||||
&& Mnemonic::parse_in_normalized(Language::English, w).is_ok()
|
||||
}
|
||||
|
||||
/// Derive the Reticulum identity keys from a 12-word mnemonic (scheme v1).
|
||||
pub fn derive_identity(words: &str) -> Result<DerivedIdentity, RatkeyError> {
|
||||
if !validate_mnemonic(words) {
|
||||
return Err(RatkeyError::InvalidHwid(
|
||||
"invalid seed phrase: expected 12 valid BIP-39 English words".to_string(),
|
||||
));
|
||||
}
|
||||
let mnemonic = Mnemonic::parse_in_normalized(Language::English, words.trim())
|
||||
.map_err(|e| RatkeyError::InvalidHwid(format!("invalid seed phrase: {e}")))?;
|
||||
|
||||
let mut seed = mnemonic.to_seed("");
|
||||
let ed25519_seed = hkdf32(&seed, ED25519_SALT)?;
|
||||
let x25519_secret = hkdf32(&seed, X25519_SALT)?;
|
||||
seed.zeroize();
|
||||
|
||||
let ed25519_pub = Ed25519PrivateKey::from_bytes(&ed25519_seed)
|
||||
.public_key()
|
||||
.to_bytes();
|
||||
let x25519_pub = X25519PrivateKey::from_bytes(&x25519_secret)
|
||||
.public_key()
|
||||
.to_bytes();
|
||||
|
||||
Ok(DerivedIdentity {
|
||||
ed25519_seed,
|
||||
x25519_secret,
|
||||
ed25519_pub,
|
||||
x25519_pub,
|
||||
})
|
||||
}
|
||||
|
||||
fn hkdf32(ikm: &[u8], salt: &[u8]) -> Result<[u8; 32], RatkeyError> {
|
||||
let hk = Hkdf::<Sha256>::new(Some(salt), ikm);
|
||||
let mut okm = [0u8; 32];
|
||||
hk.expand(HKDF_INFO, &mut okm)
|
||||
.map_err(|_| RatkeyError::InvalidHwid("HKDF expand failed".to_string()))?;
|
||||
Ok(okm)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_mnemonic() -> String {
|
||||
// Standard BIP-39 all-zero-entropy vector (checksum word "about").
|
||||
"abandon ".repeat(11) + "about"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_matches_python_vector() {
|
||||
// Cross-checked against ratkey-py's derivation (scheme v1).
|
||||
let d = derive_identity(&test_mnemonic()).unwrap();
|
||||
assert_eq!(
|
||||
hex::encode(d.ed25519_seed),
|
||||
"dfbf047515deef875db5884b7d1ec625f57641adb7265153a2c3b775ed04386f"
|
||||
);
|
||||
assert_eq!(
|
||||
hex::encode(d.x25519_secret),
|
||||
"20c92deea11650882a353b4e9928602d247b4ee689c1e0e10dc77637dbe3b33f"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_is_deterministic() {
|
||||
let a = derive_identity(&test_mnemonic()).unwrap();
|
||||
let b = derive_identity(&test_mnemonic()).unwrap();
|
||||
assert_eq!(a.ed25519_pub, b.ed25519_pub);
|
||||
assert_eq!(a.x25519_pub, b.x25519_pub);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_bad_input() {
|
||||
assert!(!validate_mnemonic("not a real phrase"));
|
||||
assert!(!validate_mnemonic(&"abandon ".repeat(12))); // 12 abandon = bad checksum
|
||||
assert!(validate_mnemonic(&test_mnemonic()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_roundtrips() {
|
||||
let m = generate_mnemonic().unwrap();
|
||||
assert_eq!(m.split_whitespace().count(), MNEMONIC_WORDS);
|
||||
assert!(validate_mnemonic(&m));
|
||||
// A generated phrase derives a stable identity.
|
||||
let d = derive_identity(&m).unwrap();
|
||||
assert_ne!(d.ed25519_pub, [0u8; 32]);
|
||||
}
|
||||
}
|
||||
@@ -1,70 +1,43 @@
|
||||
//! Real PIV session over PC/SC (YubiKey 5, Nitrokey 3).
|
||||
//! Requires `hardware` feature + PC/SC daemon (macOS CryptoTokenKit / Linux pcscd / Windows WinSCard).
|
||||
|
||||
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
|
||||
use tracing::{debug, warn};
|
||||
use zeroize::Zeroize;
|
||||
//! Transport-agnostic PIV session. Every PIV operation is built on `apdu` plus a
|
||||
//! `PivTransport`; the transport is the only platform-specific part (see `transport`).
|
||||
//! `hardware` feature adds the PC/SC `connect()` entry points.
|
||||
|
||||
use crate::apdu;
|
||||
use crate::detect::DeviceType;
|
||||
use crate::error::RatkeyError;
|
||||
use crate::pin::PinCache;
|
||||
use crate::transport::PivTransport;
|
||||
|
||||
const MAX_RESPONSE: usize = 4096;
|
||||
/// Device identity captured once at connect time; no per-operation cost.
|
||||
pub struct DeviceMeta {
|
||||
pub device_type: DeviceType,
|
||||
pub serial: Option<u32>,
|
||||
pub firmware: Option<String>,
|
||||
}
|
||||
|
||||
pub struct PivSession {
|
||||
card: Card,
|
||||
pub struct PivSession<T: PivTransport> {
|
||||
transport: T,
|
||||
device_type: DeviceType,
|
||||
reader_name: String,
|
||||
serial: Option<u32>,
|
||||
firmware: Option<String>,
|
||||
pin_cache: PinCache,
|
||||
}
|
||||
|
||||
impl PivSession {
|
||||
pub fn connect() -> Result<Self, RatkeyError> {
|
||||
let devices = crate::detect::detect_devices()?;
|
||||
let device = devices.first().ok_or(RatkeyError::NoDevice)?;
|
||||
Self::connect_reader(&device.reader_name)
|
||||
}
|
||||
|
||||
pub fn connect_reader(reader_name: &str) -> Result<Self, RatkeyError> {
|
||||
let ctx = Context::establish(Scope::User)?;
|
||||
let reader = std::ffi::CString::new(reader_name)
|
||||
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
|
||||
|
||||
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
|
||||
|
||||
let resp = transmit(&card, &apdu::select_piv())?;
|
||||
apdu::check_response(&resp)?;
|
||||
|
||||
let device_type = crate::detect::detect_device_type(reader_name);
|
||||
debug!(
|
||||
"PIV session established with {} ({})",
|
||||
reader_name,
|
||||
device_type.as_str()
|
||||
);
|
||||
|
||||
let (serial, firmware) = crate::detect::read_identity(&card, device_type);
|
||||
|
||||
Ok(Self {
|
||||
card,
|
||||
device_type,
|
||||
reader_name: reader_name.to_string(),
|
||||
serial,
|
||||
firmware,
|
||||
impl<T: PivTransport> PivSession<T> {
|
||||
pub fn new(transport: T, meta: DeviceMeta) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
device_type: meta.device_type,
|
||||
serial: meta.serial,
|
||||
firmware: meta.firmware,
|
||||
pin_cache: PinCache::default_timeout(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn device_type(&self) -> DeviceType {
|
||||
self.device_type
|
||||
}
|
||||
|
||||
pub fn reader_name(&self) -> &str {
|
||||
&self.reader_name
|
||||
}
|
||||
|
||||
pub fn serial(&self) -> Option<u32> {
|
||||
self.serial
|
||||
}
|
||||
@@ -73,102 +46,374 @@ impl PivSession {
|
||||
self.firmware.as_deref()
|
||||
}
|
||||
|
||||
/// Probes the attestation slot (F9) — always present on provisioned tokens.
|
||||
pub fn is_connected(&self) -> bool {
|
||||
let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION);
|
||||
let mut buf = vec![0u8; 256];
|
||||
self.card.transmit(&cmd, &mut buf).is_ok()
|
||||
self.transport.is_connected()
|
||||
}
|
||||
|
||||
/// Re-locks the card: re-selects the PIV applet (resetting the on-card PIN
|
||||
/// verification) and clears the cached PIN, so the next private-key op needs
|
||||
/// a fresh `verify_pin`. This is the mechanism behind the app-side session
|
||||
/// timeout / lock-on-quit.
|
||||
pub fn lock(&mut self) -> Result<(), RatkeyError> {
|
||||
let resp = self.transport.transmit(&apdu::select_piv())?;
|
||||
apdu::check_response(&resp)?;
|
||||
self.pin_cache.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> {
|
||||
let cmd = apdu::verify_pin(pin);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
// PIN-bearing APDU buffers are wiped once transmitted.
|
||||
let cmd = zeroize::Zeroizing::new(apdu::verify_pin(pin));
|
||||
let resp = self.transport.transmit(&cmd)?;
|
||||
apdu::check_response(&resp)?;
|
||||
self.pin_cache.cache(pin);
|
||||
debug!("PIN verified");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn change_pin(&mut self, old_pin: &str, new_pin: &str) -> Result<(), RatkeyError> {
|
||||
let cmd = apdu::change_pin(old_pin, new_pin);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
let cmd = zeroize::Zeroizing::new(apdu::change_pin(old_pin, new_pin));
|
||||
let resp = self.transport.transmit(&cmd)?;
|
||||
apdu::check_response(&resp)?;
|
||||
self.pin_cache.cache(new_pin);
|
||||
debug!("PIN changed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unblock_pin(&mut self, puk: &str, new_pin: &str) -> Result<(), RatkeyError> {
|
||||
let cmd = zeroize::Zeroizing::new(apdu::reset_retry(puk, new_pin));
|
||||
let resp = self.transport.transmit(&cmd)?;
|
||||
match apdu::check_response(&resp) {
|
||||
Ok(_) => {
|
||||
self.pin_cache.cache(new_pin);
|
||||
Ok(())
|
||||
}
|
||||
Err(RatkeyError::PinFailed { remaining }) => Err(RatkeyError::PukFailed { remaining }),
|
||||
Err(RatkeyError::PinLocked) => Err(RatkeyError::PukLocked),
|
||||
Err(other) => Err(other),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset_piv(&mut self) -> Result<(), RatkeyError> {
|
||||
let resp = self.transport.transmit(&apdu::reset_piv())?;
|
||||
match apdu::check_response(&resp) {
|
||||
Ok(_) => {
|
||||
self.pin_cache.clear();
|
||||
Ok(())
|
||||
}
|
||||
Err(RatkeyError::Apdu {
|
||||
sw1: 0x69,
|
||||
sw2: 0x85,
|
||||
}) => Err(RatkeyError::ResetRequiresBlockedPinAndPuk),
|
||||
Err(other) => Err(other),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_ed25519(
|
||||
&self,
|
||||
&mut self,
|
||||
slot: u8,
|
||||
pin_policy: Option<u8>,
|
||||
touch_policy: Option<u8>,
|
||||
) -> Result<[u8; 32], RatkeyError> {
|
||||
let cmd = apdu::generate_key(slot, apdu::ALG_ED25519, pin_policy, touch_policy);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
let resp = self.transport.transmit(&apdu::generate_key(
|
||||
slot,
|
||||
apdu::ALG_ED25519,
|
||||
pin_policy,
|
||||
touch_policy,
|
||||
))?;
|
||||
let data = apdu::check_response(&resp)?;
|
||||
apdu::parse_generate_response(data)
|
||||
}
|
||||
|
||||
pub fn generate_x25519(
|
||||
&self,
|
||||
&mut self,
|
||||
slot: u8,
|
||||
pin_policy: Option<u8>,
|
||||
touch_policy: Option<u8>,
|
||||
) -> Result<[u8; 32], RatkeyError> {
|
||||
let cmd = apdu::generate_key(slot, apdu::ALG_X25519, pin_policy, touch_policy);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
let resp = self.transport.transmit(&apdu::generate_key(
|
||||
slot,
|
||||
apdu::ALG_X25519,
|
||||
pin_policy,
|
||||
touch_policy,
|
||||
))?;
|
||||
let data = apdu::check_response(&resp)?;
|
||||
apdu::parse_generate_response(data)
|
||||
}
|
||||
|
||||
pub fn sign_ed25519(&self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
|
||||
let cmd = apdu::sign_ed25519(slot, message);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
let data = apdu::check_response(&resp)?;
|
||||
apdu::parse_sign_response(data)
|
||||
/// Import an off-device Ed25519 key (recoverable provisioning / restore).
|
||||
/// Requires prior `authenticate_management_key`.
|
||||
pub fn import_ed25519(
|
||||
&mut self,
|
||||
slot: u8,
|
||||
private_key: &[u8; 32],
|
||||
pin_policy: Option<u8>,
|
||||
touch_policy: Option<u8>,
|
||||
) -> Result<(), RatkeyError> {
|
||||
let resp = self.transport.transmit(&apdu::import_ed25519(
|
||||
slot,
|
||||
private_key,
|
||||
pin_policy,
|
||||
touch_policy,
|
||||
))?;
|
||||
apdu::check_response(&resp)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn ecdh_x25519(&self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
|
||||
let cmd = apdu::ecdh_x25519(slot, peer_pub);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
let data = apdu::check_response(&resp)?;
|
||||
let mut secret = apdu::parse_ecdh_response(data)?;
|
||||
// Wipes local stack copy only. Caller must zeroize the returned bytes.
|
||||
let result = secret;
|
||||
secret.zeroize();
|
||||
Ok(result)
|
||||
/// Import an off-device X25519 key. Requires prior `authenticate_management_key`.
|
||||
pub fn import_x25519(
|
||||
&mut self,
|
||||
slot: u8,
|
||||
private_key: &[u8; 32],
|
||||
pin_policy: Option<u8>,
|
||||
touch_policy: Option<u8>,
|
||||
) -> Result<(), RatkeyError> {
|
||||
let resp = self.transport.transmit(&apdu::import_x25519(
|
||||
slot,
|
||||
private_key,
|
||||
pin_policy,
|
||||
touch_policy,
|
||||
))?;
|
||||
apdu::check_response(&resp)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transmit a PIN-gated command, retrying once through the cached PIN
|
||||
/// when the card answers 0x6982 (security status not satisfied) — e.g.
|
||||
/// pin_policy=ALWAYS slots, or the applet was re-selected since the last
|
||||
/// VERIFY. The cache expires on its own timeout and is cleared by `lock`.
|
||||
fn transmit_pin_gated(&mut self, cmd: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
let resp = self.transport.transmit(cmd)?;
|
||||
match apdu::check_response(&resp) {
|
||||
Err(RatkeyError::Apdu {
|
||||
sw1: 0x69,
|
||||
sw2: 0x82,
|
||||
}) => {
|
||||
let pin = match self.pin_cache.get() {
|
||||
Some(pin) => zeroize::Zeroizing::new(pin.to_string()),
|
||||
None => {
|
||||
return Err(RatkeyError::Apdu {
|
||||
sw1: 0x69,
|
||||
sw2: 0x82,
|
||||
});
|
||||
}
|
||||
};
|
||||
self.verify_pin(&pin)?;
|
||||
let resp = self.transport.transmit(cmd)?;
|
||||
Ok(apdu::check_response(&resp)?.to_vec())
|
||||
}
|
||||
other => Ok(other?.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
|
||||
let data = self.transmit_pin_gated(&apdu::sign_ed25519(slot, message))?;
|
||||
apdu::parse_sign_response(&data)
|
||||
}
|
||||
|
||||
pub fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
|
||||
let data = self.transmit_pin_gated(&apdu::ecdh_x25519(slot, peer_pub))?;
|
||||
apdu::parse_ecdh_response(&data)
|
||||
}
|
||||
|
||||
/// Returns DER-encoded X.509 attestation certificate.
|
||||
pub fn attest_key(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
|
||||
let cmd = apdu::attest_key(slot);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
let data = apdu::check_response(&resp)?;
|
||||
Ok(data.to_vec())
|
||||
pub fn attest_key(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
|
||||
let resp = self.transport.transmit(&apdu::attest_key(slot))?;
|
||||
Ok(apdu::check_response(&resp)?.to_vec())
|
||||
}
|
||||
|
||||
pub fn read_certificate(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
|
||||
pub fn read_certificate(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
|
||||
let cmd = apdu::get_data(slot).ok_or(RatkeyError::EmptySlot { slot })?;
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
let data = apdu::check_response(&resp)?;
|
||||
Ok(data.to_vec())
|
||||
let resp = self.transport.transmit(&cmd)?;
|
||||
Ok(apdu::check_response(&resp)?.to_vec())
|
||||
}
|
||||
|
||||
/// Returns raw metadata TLV bytes.
|
||||
pub fn read_metadata(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
|
||||
let cmd = apdu::get_metadata(slot);
|
||||
let resp = transmit(&self.card, &cmd)?;
|
||||
/// Device attestation (slot F9) intermediate certificate, unwrapped to raw DER.
|
||||
/// This is the issuer of the per-slot certs returned by [`Self::attest_key`].
|
||||
pub fn read_attestation_cert(&mut self) -> Result<Vec<u8>, RatkeyError> {
|
||||
let cmd = apdu::get_data(apdu::SLOT_ATTESTATION).ok_or(RatkeyError::EmptySlot {
|
||||
slot: apdu::SLOT_ATTESTATION,
|
||||
})?;
|
||||
let resp = self.transport.transmit(&cmd)?;
|
||||
let data = apdu::check_response(&resp)?;
|
||||
Ok(data.to_vec())
|
||||
apdu::parse_certificate_object(data).ok_or_else(|| {
|
||||
RatkeyError::InvalidHwid("device attestation cert (F9) not found in response".into())
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns raw GET METADATA TLV bytes.
|
||||
pub fn read_metadata(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
|
||||
let resp = self.transport.transmit(&apdu::get_metadata(slot))?;
|
||||
Ok(apdu::check_response(&resp)?.to_vec())
|
||||
}
|
||||
|
||||
/// Reads the slot's 32-byte public key from GET METADATA. The metadata byte
|
||||
/// layout is pending confirmation against a real device — see
|
||||
/// `apdu::parse_metadata_public_key`. Yubico 5.3+ only (Nitrokey 3 has no
|
||||
/// GET METADATA).
|
||||
pub fn read_public_key(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
|
||||
let metadata = self.read_metadata(slot)?;
|
||||
apdu::parse_metadata_public_key(&metadata)
|
||||
}
|
||||
|
||||
/// Authenticate the PIV management key (slot 9B) via witness/challenge mutual
|
||||
/// auth — required before on-device key generation. The algorithm is read
|
||||
/// from the card (YubiKey 5.7 default: AES-192).
|
||||
pub fn authenticate_management_key(&mut self, key: &[u8]) -> Result<(), RatkeyError> {
|
||||
let meta = self.read_metadata(apdu::SLOT_CARD_MANAGEMENT)?;
|
||||
let alg = apdu::parse_metadata_algorithm(&meta)?;
|
||||
let block = crate::mgmt::block_len(alg).ok_or_else(|| {
|
||||
RatkeyError::UnsupportedDevice(format!(
|
||||
"unsupported management-key algorithm 0x{alg:02X}"
|
||||
))
|
||||
})?;
|
||||
|
||||
// Step 1: get the card's encrypted witness, decrypt it with the key.
|
||||
let resp = self.transport.transmit(&apdu::auth_witness_request(alg))?;
|
||||
let witness = apdu::parse_auth_witness(apdu::check_response(&resp)?)?;
|
||||
let decrypted = crate::mgmt::ecb_decrypt(alg, key, &witness)?;
|
||||
|
||||
// Step 2: prove the witness + send our own challenge. A wrong key is
|
||||
// rejected here with an APDU status (not the mutual check below).
|
||||
let challenge = rns_crypto::random::random_bytes(block);
|
||||
let resp = self
|
||||
.transport
|
||||
.transmit(&apdu::auth_witness_response(alg, &decrypted, &challenge))?;
|
||||
let data = apdu::check_response(&resp).map_err(|_| RatkeyError::ManagementAuthFailed)?;
|
||||
let encrypted = apdu::parse_auth_response(data)?;
|
||||
|
||||
// Step 3: mutual check — the card must have encrypted our challenge.
|
||||
if crate::mgmt::ecb_encrypt(alg, key, &challenge)? != encrypted {
|
||||
return Err(RatkeyError::ManagementAuthFailed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn transmit(card: &Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
let mut response_buf = vec![0u8; MAX_RESPONSE];
|
||||
let response = card.transmit(command, &mut response_buf).map_err(|e| {
|
||||
warn!("PC/SC transmit failed: {}", e);
|
||||
RatkeyError::Disconnected
|
||||
})?;
|
||||
Ok(response.to_vec())
|
||||
/// PC/SC convenience alias; `connect()` lives on this monomorphization.
|
||||
#[cfg(feature = "hardware")]
|
||||
pub type PcscPivSession = PivSession<crate::transport::PcscTransport>;
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
impl PivSession<crate::transport::PcscTransport> {
|
||||
/// Connect to the first detected token over PC/SC.
|
||||
pub fn connect() -> Result<Self, RatkeyError> {
|
||||
let (transport, meta) = crate::transport::PcscTransport::connect()?;
|
||||
Ok(Self::new(transport, meta))
|
||||
}
|
||||
|
||||
/// Connect to a specific PC/SC reader by name.
|
||||
pub fn connect_reader(reader_name: &str) -> Result<Self, RatkeyError> {
|
||||
let (transport, meta) = crate::transport::PcscTransport::connect_reader(reader_name)?;
|
||||
Ok(Self::new(transport, meta))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
|
||||
/// Card that loses PIN verification whenever `verified` is flipped off
|
||||
/// (pin_policy=ALWAYS / applet reselect shape): SIGN answers 0x6982
|
||||
/// until a VERIFY lands.
|
||||
struct PinGatedTransport {
|
||||
verified: Arc<AtomicBool>,
|
||||
verify_calls: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
impl PivTransport for PinGatedTransport {
|
||||
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
match apdu[1] {
|
||||
0xA4 => {
|
||||
self.verified.store(false, Ordering::SeqCst);
|
||||
Ok(vec![0x90, 0x00])
|
||||
}
|
||||
0x20 => {
|
||||
self.verify_calls.fetch_add(1, Ordering::SeqCst);
|
||||
self.verified.store(true, Ordering::SeqCst);
|
||||
Ok(vec![0x90, 0x00])
|
||||
}
|
||||
0x87 => {
|
||||
if !self.verified.load(Ordering::SeqCst) {
|
||||
return Ok(vec![0x69, 0x82]);
|
||||
}
|
||||
let mut v = vec![0x7C, 0x42, 0x82, 0x40];
|
||||
v.extend_from_slice(&[0xAB; 64]);
|
||||
v.extend_from_slice(&[0x90, 0x00]);
|
||||
Ok(v)
|
||||
}
|
||||
_ => Ok(vec![0x90, 0x00]),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_connected(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn session_with_flags() -> (
|
||||
PivSession<PinGatedTransport>,
|
||||
Arc<AtomicBool>,
|
||||
Arc<AtomicU32>,
|
||||
) {
|
||||
let verified = Arc::new(AtomicBool::new(false));
|
||||
let verify_calls = Arc::new(AtomicU32::new(0));
|
||||
let transport = PinGatedTransport {
|
||||
verified: verified.clone(),
|
||||
verify_calls: verify_calls.clone(),
|
||||
};
|
||||
let session = PivSession::new(
|
||||
transport,
|
||||
DeviceMeta {
|
||||
device_type: DeviceType::Unknown,
|
||||
serial: None,
|
||||
firmware: None,
|
||||
},
|
||||
);
|
||||
(session, verified, verify_calls)
|
||||
}
|
||||
|
||||
/// T2-6a: the PIN cache is no longer write-only — a 0x6982 on a key op
|
||||
/// re-verifies through the cached PIN and retries once.
|
||||
#[test]
|
||||
fn sign_retries_through_cached_pin() {
|
||||
let (mut session, verified, verify_calls) = session_with_flags();
|
||||
|
||||
session.verify_pin("123456").unwrap();
|
||||
assert_eq!(verify_calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
// Card drops auth state (pin_policy=ALWAYS consumes the VERIFY).
|
||||
verified.store(false, Ordering::SeqCst);
|
||||
|
||||
let sig = session.sign_ed25519(0x9A, b"message").unwrap();
|
||||
assert_eq!(sig, [0xAB; 64]);
|
||||
assert_eq!(
|
||||
verify_calls.load(Ordering::SeqCst),
|
||||
2,
|
||||
"sign must have re-verified via the cached PIN"
|
||||
);
|
||||
}
|
||||
|
||||
/// After `lock()` the cache is cleared: no silent re-verify is possible.
|
||||
#[test]
|
||||
fn sign_after_lock_fails_without_fresh_pin() {
|
||||
let (mut session, _verified, verify_calls) = session_with_flags();
|
||||
|
||||
session.verify_pin("123456").unwrap();
|
||||
session.lock().unwrap();
|
||||
|
||||
let err = session.sign_ed25519(0x9A, b"message").unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
RatkeyError::Apdu {
|
||||
sw1: 0x69,
|
||||
sw2: 0x82
|
||||
}
|
||||
));
|
||||
assert_eq!(
|
||||
verify_calls.load(Ordering::SeqCst),
|
||||
1,
|
||||
"locked session must not re-verify on its own"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Transport seam for PIV. The PIV protocol logic lives in `PivSession`; this
|
||||
//! trait is the only platform-specific part: APDU bytes in, response bytes out.
|
||||
//! Desktop PC/SC ships here behind the `hardware` feature. Mobile NFC/USB
|
||||
//! transports live in the application layer and implement the same trait.
|
||||
|
||||
use crate::error::RatkeyError;
|
||||
|
||||
pub trait PivTransport {
|
||||
/// Send one ISO 7816-4 APDU; return the full response including SW1/SW2.
|
||||
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError>;
|
||||
|
||||
/// Cheap liveness probe — token still present and responding.
|
||||
fn is_connected(&self) -> bool;
|
||||
}
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
pub use pcsc_transport::PcscTransport;
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
mod pcsc_transport {
|
||||
use pcsc::{Context, Protocols, Scope, ShareMode};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::PivTransport;
|
||||
use crate::apdu;
|
||||
use crate::detect::{self, detect_device_type};
|
||||
use crate::error::RatkeyError;
|
||||
use crate::session::DeviceMeta;
|
||||
|
||||
const MAX_RESPONSE: usize = 4096;
|
||||
|
||||
/// Real PIV transport over PC/SC (YubiKey 5, Nitrokey 3). Requires a PC/SC
|
||||
/// daemon: macOS CryptoTokenKit / Linux pcscd / Windows WinSCard.
|
||||
pub struct PcscTransport {
|
||||
card: pcsc::Card,
|
||||
}
|
||||
|
||||
impl PcscTransport {
|
||||
/// Connect to the first detected RATKEY token.
|
||||
pub fn connect() -> Result<(Self, DeviceMeta), RatkeyError> {
|
||||
let devices = detect::detect_devices()?;
|
||||
let device = devices.first().ok_or(RatkeyError::NoDevice)?;
|
||||
Self::connect_reader(&device.reader_name)
|
||||
}
|
||||
|
||||
/// Connect to a specific PC/SC reader by name.
|
||||
pub fn connect_reader(reader_name: &str) -> Result<(Self, DeviceMeta), RatkeyError> {
|
||||
let ctx = Context::establish(Scope::User)?;
|
||||
let reader = std::ffi::CString::new(reader_name)
|
||||
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
|
||||
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
|
||||
|
||||
let resp = transmit_card(&card, &apdu::select_piv())?;
|
||||
apdu::check_response(&resp)?;
|
||||
|
||||
let device_type = detect_device_type(reader_name);
|
||||
debug!(
|
||||
"PIV session established with {} ({})",
|
||||
reader_name,
|
||||
device_type.as_str()
|
||||
);
|
||||
|
||||
let (serial, firmware) = detect::read_identity(&card, device_type);
|
||||
|
||||
Ok((
|
||||
Self { card },
|
||||
DeviceMeta {
|
||||
device_type,
|
||||
serial,
|
||||
firmware,
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl PivTransport for PcscTransport {
|
||||
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
transmit_card(&self.card, apdu)
|
||||
}
|
||||
|
||||
fn is_connected(&self) -> bool {
|
||||
// Attestation slot (F9) is present on any provisioned token.
|
||||
let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION);
|
||||
let mut buf = vec![0u8; 256];
|
||||
self.card.transmit(&cmd, &mut buf).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn transmit_card(card: &pcsc::Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
let initial = transmit_once(card, command)?;
|
||||
super::chain_response(command, initial, |apdu| transmit_once(card, apdu))
|
||||
}
|
||||
|
||||
fn transmit_once(card: &pcsc::Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
|
||||
let mut response_buf = vec![0u8; MAX_RESPONSE];
|
||||
let response = card.transmit(command, &mut response_buf).map_err(|e| {
|
||||
warn!("PC/SC transmit failed: {}", e);
|
||||
RatkeyError::Disconnected
|
||||
})?;
|
||||
Ok(response.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO 7816-4 response chaining, factored out of the PC/SC transport so it is
|
||||
/// testable without a card. `initial` is the first response (data‖SW1‖SW2);
|
||||
/// `transmit` sends a follow-up APDU and returns its raw response.
|
||||
/// - `61 xx`: more data available — fetch it with GET RESPONSE and append.
|
||||
/// - `6C xx`: wrong Le — resend `command` with the card's expected Le. Assumes
|
||||
/// `command` carries no Le of its own (true for our case-3 reads); a command
|
||||
/// that already has an Le would be malformed here.
|
||||
///
|
||||
/// Large reads (e.g. GET DATA on a ~1 KB attestation cert) arrive as `61 xx`;
|
||||
/// without this every such read would be truncated to the first ≤256 bytes.
|
||||
// Only the `hardware` transport calls this; the unit tests exercise it always.
|
||||
#[cfg_attr(not(feature = "hardware"), allow(dead_code))]
|
||||
pub(crate) fn chain_response(
|
||||
command: &[u8],
|
||||
initial: Vec<u8>,
|
||||
mut transmit: impl FnMut(&[u8]) -> Result<Vec<u8>, RatkeyError>,
|
||||
) -> Result<Vec<u8>, RatkeyError> {
|
||||
let mut data = initial;
|
||||
// Bounded against a misbehaving card that never returns a terminal SW.
|
||||
for _ in 0..64 {
|
||||
if data.len() < 2 {
|
||||
break;
|
||||
}
|
||||
let (sw1, sw2) = (data[data.len() - 2], data[data.len() - 1]);
|
||||
if sw1 == 0x61 {
|
||||
data.truncate(data.len() - 2); // drop interim SW; keep the data
|
||||
let get_response = [0x00, 0xC0, 0x00, 0x00, sw2]; // sw2 = bytes left (0 = 256)
|
||||
data.extend_from_slice(&transmit(&get_response)?);
|
||||
} else if sw1 == 0x6C {
|
||||
let mut retry = command.to_vec();
|
||||
retry.push(sw2);
|
||||
data = transmit(&retry)?;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn passthrough_on_terminal_sw() {
|
||||
let out = chain_response(&[], vec![0x01, 0x02, 0x90, 0x00], |_| {
|
||||
panic!("no follow-up expected")
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(out, vec![0x01, 0x02, 0x90, 0x00]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appends_get_response_on_61() {
|
||||
let mut calls = 0;
|
||||
let out = chain_response(
|
||||
&[0x00, 0xCB, 0x3F, 0xFF],
|
||||
vec![0xAA, 0xBB, 0x61, 0x02],
|
||||
|apdu| {
|
||||
calls += 1;
|
||||
assert_eq!(apdu, &[0x00, 0xC0, 0x00, 0x00, 0x02]); // GET RESPONSE, Le=2
|
||||
Ok(vec![0xCC, 0xDD, 0x90, 0x00])
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(calls, 1);
|
||||
assert_eq!(out, vec![0xAA, 0xBB, 0xCC, 0xDD, 0x90, 0x00]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chains_multiple_61() {
|
||||
let mut step = 0;
|
||||
let out = chain_response(&[0x00], vec![0x01, 0x61, 0x00], |_| {
|
||||
step += 1;
|
||||
if step == 1 {
|
||||
Ok(vec![0x02, 0x61, 0x00]) // still more
|
||||
} else {
|
||||
Ok(vec![0x03, 0x90, 0x00]) // done
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(step, 2);
|
||||
assert_eq!(out, vec![0x01, 0x02, 0x03, 0x90, 0x00]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resends_with_le_on_6c() {
|
||||
let out = chain_response(&[0x00, 0xCB, 0x3F, 0xFF], vec![0x6C, 0x05], |apdu| {
|
||||
assert_eq!(apdu, &[0x00, 0xCB, 0x3F, 0xFF, 0x05]); // original + Le=5
|
||||
Ok(vec![0xDE, 0xAD, 0x90, 0x00])
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(out, vec![0xDE, 0xAD, 0x90, 0x00]);
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
[features]
|
||||
default = []
|
||||
serial = ["rns-interface/serial"]
|
||||
rnode-tcp = ["rns-interface/rnode-tcp"]
|
||||
ble = ["rns-interface/ble"]
|
||||
|
||||
[dependencies]
|
||||
@@ -23,6 +24,7 @@ tokio = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
hmac = { workspace = true }
|
||||
md-5 = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
rmpv = { workspace = true, features = ["with-serde"] }
|
||||
|
||||
@@ -12,9 +12,12 @@ pub const RESOURCE_CACHE: u64 = 86400;
|
||||
pub const MAX_QUEUED_ANNOUNCES: usize = 16384;
|
||||
pub const QUEUED_ANNOUNCE_LIFE: u64 = 86400;
|
||||
|
||||
/// Percentage matching Python `Reticulum.ANNOUNCE_CAP = 2`; transport actor
|
||||
/// divides by 100 before applying to bitrate math.
|
||||
pub const ANNOUNCE_CAP: f64 = 2.0;
|
||||
/// Announce bandwidth cap as a fraction of interface bitrate (2%).
|
||||
///
|
||||
/// Python exposes/configures this as `2` percent, then stores `0.02` on live
|
||||
/// interfaces. Runtime registration must hand the transport actor the stored
|
||||
/// fraction, because queue spacing is calculated as `tx_time / announce_cap`.
|
||||
pub const ANNOUNCE_CAP: f64 = 0.02;
|
||||
|
||||
pub const MINIMUM_BITRATE: u64 = 5;
|
||||
pub const IFAC_MIN_SIZE: usize = 1;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -75,23 +75,50 @@ impl Default for ExitHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Install Ctrl-C / SIGTERM handlers that trip `shutdown`. Returned receiver
|
||||
/// Install a Ctrl-C (SIGINT) handler that trips `shutdown`. Returned receiver
|
||||
/// yields once on signal for await-based callers.
|
||||
///
|
||||
/// On unix the OS-level registration happens synchronously in this call — a
|
||||
/// handler registered inside a spawned task only takes effect once that task
|
||||
/// is first polled, leaving a window where SIGINT kills the process via the
|
||||
/// default disposition.
|
||||
pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> {
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
|
||||
let shutdown_clone = shutdown.clone();
|
||||
tokio::spawn(async move {
|
||||
let ctrl_c = tokio::signal::ctrl_c();
|
||||
ctrl_c.await.ok();
|
||||
tracing::info!("received shutdown signal");
|
||||
shutdown_clone.trigger();
|
||||
let _ = tx.send(()).await;
|
||||
});
|
||||
|
||||
#[cfg(unix)]
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) {
|
||||
Ok(mut sigint) => {
|
||||
tokio::spawn(async move {
|
||||
sigint.recv().await;
|
||||
signal_shutdown(shutdown_clone, tx).await;
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c");
|
||||
spawn_ctrl_c_handler(shutdown_clone, tx);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
spawn_ctrl_c_handler(shutdown_clone, tx);
|
||||
|
||||
rx
|
||||
}
|
||||
|
||||
fn spawn_ctrl_c_handler(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
|
||||
tokio::spawn(async move {
|
||||
tokio::signal::ctrl_c().await.ok();
|
||||
signal_shutdown(shutdown, tx).await;
|
||||
});
|
||||
}
|
||||
|
||||
async fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
|
||||
tracing::info!("received shutdown signal");
|
||||
shutdown.trigger();
|
||||
let _ = tx.send(()).await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -64,6 +64,36 @@ pub struct ChannelSendReceipt {
|
||||
pub packet_hash: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinkPacketSendReceipt {
|
||||
pub link_id: [u8; 16],
|
||||
pub packet_hash: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinkResourceSendReceipt {
|
||||
pub link_id: [u8; 16],
|
||||
pub resource_hash: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinkPacketProof {
|
||||
pub link_id: [u8; 16],
|
||||
pub packet_hash: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinkResourceProof {
|
||||
pub link_id: [u8; 16],
|
||||
pub resource_hash: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LinkPayloadSendReceipt {
|
||||
Packet(LinkPacketSendReceipt),
|
||||
Resource(LinkResourceSendReceipt),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ChannelSendError {
|
||||
#[error("link not found")]
|
||||
@@ -78,12 +108,43 @@ pub enum ChannelSendError {
|
||||
TransportUnavailable,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LinkSendError {
|
||||
#[error("link not found")]
|
||||
LinkNotFound,
|
||||
#[error("link is not active")]
|
||||
LinkNotActive,
|
||||
#[error("link session keys are unavailable")]
|
||||
NoSessionKeys,
|
||||
#[error("transport channel is full or closed")]
|
||||
TransportUnavailable,
|
||||
#[error("resource transfer could not be started")]
|
||||
ResourceStartFailed,
|
||||
}
|
||||
|
||||
pub enum LinkManagerCommand {
|
||||
SendChannelMessage {
|
||||
link_id: [u8; 16],
|
||||
message: Box<dyn MessageBase>,
|
||||
result_tx: Option<oneshot::Sender<Result<ChannelSendReceipt, ChannelSendError>>>,
|
||||
},
|
||||
SendLinkPacket {
|
||||
link_id: [u8; 16],
|
||||
payload: Vec<u8>,
|
||||
result_tx: Option<oneshot::Sender<Result<LinkPacketSendReceipt, LinkSendError>>>,
|
||||
},
|
||||
SendLinkResource {
|
||||
link_id: [u8; 16],
|
||||
payload: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
result_tx: Option<oneshot::Sender<Result<LinkResourceSendReceipt, LinkSendError>>>,
|
||||
},
|
||||
SendLinkPayload {
|
||||
link_id: [u8; 16],
|
||||
payload: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
result_tx: Option<oneshot::Sender<Result<LinkPayloadSendReceipt, LinkSendError>>>,
|
||||
},
|
||||
CloseLink {
|
||||
link_id: [u8; 16],
|
||||
reason: CloseReason,
|
||||
@@ -137,7 +198,8 @@ pub struct LinkManager {
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
event_rx: mpsc::Receiver<DestinationEvent>,
|
||||
active_links: HashMap<[u8; 16], ActiveLink>,
|
||||
/// `None` rejects all links.
|
||||
/// Raw software signing key, when available. Hardware-backed identities sign
|
||||
/// through `identity` instead.
|
||||
identity_key: Option<Ed25519PrivateKey>,
|
||||
pub destination_hash: [u8; 16],
|
||||
destination: Option<Destination>,
|
||||
@@ -162,6 +224,10 @@ pub struct LinkManager {
|
||||
link_identity_gate: Option<LinkIdentityGate>,
|
||||
/// Decrypted link-packet stream (LXMF DIRECT).
|
||||
link_packet_tx: Option<mpsc::Sender<(Vec<u8>, [u8; 16])>>,
|
||||
/// Valid proof for an application link packet sent through this manager.
|
||||
link_packet_proof_tx: Option<mpsc::Sender<LinkPacketProof>>,
|
||||
/// Valid proof for an application resource sent through this manager.
|
||||
outbound_resource_proof_tx: Option<mpsc::Sender<LinkResourceProof>>,
|
||||
/// Decrypted channel envelopes as `(link_id, msg_type, payload)`.
|
||||
channel_message_tx: Option<mpsc::Sender<LinkChannelMessage>>,
|
||||
/// Fires when an active link is closed or torn down.
|
||||
@@ -199,6 +265,8 @@ impl LinkManager {
|
||||
link_identified_tx: None,
|
||||
link_identity_gate: None,
|
||||
link_packet_tx: None,
|
||||
link_packet_proof_tx: None,
|
||||
outbound_resource_proof_tx: None,
|
||||
channel_message_tx: None,
|
||||
link_closed_tx: None,
|
||||
inbound_raw_tx: None,
|
||||
@@ -213,7 +281,9 @@ impl LinkManager {
|
||||
event_rx: mpsc::Receiver<DestinationEvent>,
|
||||
identity: &Identity,
|
||||
app_name: &str,
|
||||
identity_key: Ed25519PrivateKey,
|
||||
// `None` for hardware-backed identities (no extractable signing key);
|
||||
// link proofs are routed through the backend-aware `Identity`.
|
||||
identity_key: Option<Ed25519PrivateKey>,
|
||||
) -> Self {
|
||||
let dest = match Destination::new(Some(identity), Direction::In, DestType::Single, app_name)
|
||||
{
|
||||
@@ -231,7 +301,7 @@ impl LinkManager {
|
||||
transport_tx,
|
||||
event_rx,
|
||||
active_links: HashMap::new(),
|
||||
identity_key: Some(identity_key),
|
||||
identity_key,
|
||||
destination_hash,
|
||||
destination: dest,
|
||||
identity: manager_identity,
|
||||
@@ -245,6 +315,8 @@ impl LinkManager {
|
||||
link_identified_tx: None,
|
||||
link_identity_gate: None,
|
||||
link_packet_tx: None,
|
||||
link_packet_proof_tx: None,
|
||||
outbound_resource_proof_tx: None,
|
||||
channel_message_tx: None,
|
||||
link_closed_tx: None,
|
||||
inbound_raw_tx: None,
|
||||
@@ -342,6 +414,41 @@ impl LinkManager {
|
||||
}
|
||||
true
|
||||
}
|
||||
LinkManagerCommand::SendLinkPacket {
|
||||
link_id,
|
||||
payload,
|
||||
result_tx,
|
||||
} => {
|
||||
let result = self.send_link_packet(&link_id, &payload);
|
||||
if let Some(tx) = result_tx {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
true
|
||||
}
|
||||
LinkManagerCommand::SendLinkResource {
|
||||
link_id,
|
||||
payload,
|
||||
auto_compress,
|
||||
result_tx,
|
||||
} => {
|
||||
let result = self.send_link_resource(&link_id, payload, auto_compress);
|
||||
if let Some(tx) = result_tx {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
true
|
||||
}
|
||||
LinkManagerCommand::SendLinkPayload {
|
||||
link_id,
|
||||
payload,
|
||||
auto_compress,
|
||||
result_tx,
|
||||
} => {
|
||||
let result = self.send_link_payload(&link_id, payload, auto_compress);
|
||||
if let Some(tx) = result_tx {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
true
|
||||
}
|
||||
LinkManagerCommand::CloseLink {
|
||||
link_id,
|
||||
reason,
|
||||
@@ -455,14 +562,6 @@ impl LinkManager {
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -483,14 +582,32 @@ impl LinkManager {
|
||||
}
|
||||
}
|
||||
|
||||
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 responder = match (&self.identity_key, &self.identity) {
|
||||
(Some(identity_key), _) => {
|
||||
Link::new_responder(request_data, identity_key, self.destination_hash, hops)
|
||||
}
|
||||
(None, Some(identity)) => {
|
||||
let identity_ed25519_pub = identity_ed25519_public_key(identity);
|
||||
Link::new_responder_with(
|
||||
request_data,
|
||||
&identity_ed25519_pub,
|
||||
self.destination_hash,
|
||||
hops,
|
||||
|signed_data| identity.sign(signed_data),
|
||||
)
|
||||
}
|
||||
(None, None) => {
|
||||
tracing::warn!("link request received but no identity signer configured");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (link, proof_data) = match responder {
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "link handshake failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let link_id = link.link_id;
|
||||
|
||||
@@ -1418,6 +1535,8 @@ impl LinkManager {
|
||||
.is_some_and(|transfer| transfer.handle_proof(data));
|
||||
if complete {
|
||||
active.outbound_resources.remove(&rh);
|
||||
let mut started_next_segment = false;
|
||||
let completed_resource_hash = queue_key.unwrap_or(rh);
|
||||
if let Some(key) = queue_key {
|
||||
let (next, empty) = if let Some(queue) =
|
||||
active.outbound_split_queues.get_mut(&key)
|
||||
@@ -1437,8 +1556,17 @@ impl LinkManager {
|
||||
&link_id,
|
||||
next,
|
||||
);
|
||||
started_next_segment = true;
|
||||
}
|
||||
}
|
||||
if !started_next_segment
|
||||
&& let Some(ref tx) = self.outbound_resource_proof_tx
|
||||
{
|
||||
let _ = tx.try_send(LinkResourceProof {
|
||||
link_id,
|
||||
resource_hash: completed_resource_hash,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1588,6 +1716,12 @@ impl LinkManager {
|
||||
}
|
||||
_ => {
|
||||
// Application data on a link (LXMF DIRECT).
|
||||
let identity_key_bytes = self.identity_key.as_ref().map(|key| key.to_bytes());
|
||||
let identity_for_signing = if identity_key_bytes.is_none() {
|
||||
self.identity.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(active) = self.active_links.get_mut(&link_id) {
|
||||
active.link.record_inbound();
|
||||
active.link.record_rx(data.len());
|
||||
@@ -1604,11 +1738,19 @@ impl LinkManager {
|
||||
);
|
||||
|
||||
// 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 pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
let proof = if let Some(key_bytes) = identity_key_bytes {
|
||||
let signing_key = Ed25519PrivateKey::from_bytes(&key_bytes);
|
||||
active.link.prove_packet(&pkt_hash, &signing_key)
|
||||
} else if let Some(identity) = identity_for_signing.as_ref() {
|
||||
active
|
||||
.link
|
||||
.prove_packet_with_fallible(&pkt_hash, |hash| identity.sign(hash))
|
||||
} else {
|
||||
Err(rns_link::encryption::LinkCryptoError::EncryptionFailed)
|
||||
};
|
||||
match proof {
|
||||
Ok(proof_data) => {
|
||||
let proof_header = rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
@@ -1636,6 +1778,12 @@ impl LinkManager {
|
||||
"delivery proof sent for link data packet (unencrypted)"
|
||||
);
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
link_id = hex::encode(link_id),
|
||||
"could not sign delivery proof for link data packet"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1933,8 +2081,10 @@ impl LinkManager {
|
||||
}
|
||||
|
||||
let rtt = active.link.rtt_secs();
|
||||
let mut matched_channel_sequence = false;
|
||||
if let Some(channel) = active.channel.as_mut() {
|
||||
if let Some(sequence) = channel.delivered_by_packet_hash(&packet_hash, rtt) {
|
||||
matched_channel_sequence = true;
|
||||
active.link.keepalive.record_proof();
|
||||
tracing::debug!(
|
||||
link_id = hex::encode(link_id),
|
||||
@@ -1944,6 +2094,12 @@ impl LinkManager {
|
||||
);
|
||||
}
|
||||
}
|
||||
if !matched_channel_sequence && let Some(ref tx) = self.link_packet_proof_tx {
|
||||
let _ = tx.try_send(LinkPacketProof {
|
||||
link_id,
|
||||
packet_hash,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_request_handler<F>(&mut self, handler: F)
|
||||
@@ -2002,6 +2158,14 @@ impl LinkManager {
|
||||
self.link_packet_tx = Some(tx);
|
||||
}
|
||||
|
||||
pub fn set_link_packet_proof_channel(&mut self, tx: mpsc::Sender<LinkPacketProof>) {
|
||||
self.link_packet_proof_tx = Some(tx);
|
||||
}
|
||||
|
||||
pub fn set_outbound_resource_proof_channel(&mut self, tx: mpsc::Sender<LinkResourceProof>) {
|
||||
self.outbound_resource_proof_tx = Some(tx);
|
||||
}
|
||||
|
||||
pub fn set_channel_message_channel(&mut self, tx: mpsc::Sender<LinkChannelMessage>) {
|
||||
self.channel_message_tx = Some(tx);
|
||||
}
|
||||
@@ -2092,6 +2256,111 @@ impl LinkManager {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn send_link_packet(
|
||||
&mut self,
|
||||
link_id: &[u8; 16],
|
||||
payload: &[u8],
|
||||
) -> Result<LinkPacketSendReceipt, LinkSendError> {
|
||||
let active = self
|
||||
.active_links
|
||||
.get(link_id)
|
||||
.ok_or(LinkSendError::LinkNotFound)?;
|
||||
if active.link.state != LinkState::Active {
|
||||
return Err(LinkSendError::LinkNotActive);
|
||||
}
|
||||
|
||||
let encrypted = active
|
||||
.link
|
||||
.encrypt(payload)
|
||||
.map_err(|_| LinkSendError::NoSessionKeys)?;
|
||||
let transport_tx = self.transport_tx.clone();
|
||||
let permit = transport_tx
|
||||
.try_reserve()
|
||||
.map_err(|_| LinkSendError::TransportUnavailable)?;
|
||||
|
||||
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::None,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(&encrypted);
|
||||
let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type);
|
||||
|
||||
let active = self
|
||||
.active_links
|
||||
.get_mut(link_id)
|
||||
.ok_or(LinkSendError::LinkNotFound)?;
|
||||
active.link.record_tx(raw.len());
|
||||
permit.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: Bytes::from(raw),
|
||||
destination_hash: *link_id,
|
||||
}));
|
||||
|
||||
Ok(LinkPacketSendReceipt {
|
||||
link_id: *link_id,
|
||||
packet_hash,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn send_link_resource(
|
||||
&mut self,
|
||||
link_id: &[u8; 16],
|
||||
payload: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
) -> Result<LinkResourceSendReceipt, LinkSendError> {
|
||||
let active = self
|
||||
.active_links
|
||||
.get(link_id)
|
||||
.ok_or(LinkSendError::LinkNotFound)?;
|
||||
if active.link.state != LinkState::Active {
|
||||
return Err(LinkSendError::LinkNotActive);
|
||||
}
|
||||
if active.link.session_keys().is_none() {
|
||||
return Err(LinkSendError::NoSessionKeys);
|
||||
}
|
||||
|
||||
let resource_hash = self
|
||||
.start_resource_transfer(link_id, payload, auto_compress)
|
||||
.ok_or(LinkSendError::ResourceStartFailed)?;
|
||||
|
||||
Ok(LinkResourceSendReceipt {
|
||||
link_id: *link_id,
|
||||
resource_hash,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn send_link_payload(
|
||||
&mut self,
|
||||
link_id: &[u8; 16],
|
||||
payload: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
) -> Result<LinkPayloadSendReceipt, LinkSendError> {
|
||||
let active = self
|
||||
.active_links
|
||||
.get(link_id)
|
||||
.ok_or(LinkSendError::LinkNotFound)?;
|
||||
if active.link.state != LinkState::Active {
|
||||
return Err(LinkSendError::LinkNotActive);
|
||||
}
|
||||
|
||||
if payload.len() <= active.link.mdu {
|
||||
self.send_link_packet(link_id, &payload)
|
||||
.map(LinkPayloadSendReceipt::Packet)
|
||||
} else {
|
||||
self.send_link_resource(link_id, payload, auto_compress)
|
||||
.map(LinkPayloadSendReceipt::Resource)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn process_destination_packet(&self, raw: &[u8], identity: &Identity) -> Option<Vec<u8>> {
|
||||
let dest = self.destination.as_ref()?;
|
||||
let (header, data_offset) = rns_wire::header::PacketHeader::unpack(raw).ok()?;
|
||||
@@ -2301,8 +2570,20 @@ impl LinkManager {
|
||||
}
|
||||
|
||||
fn clone_identity(identity: &Identity) -> Option<Identity> {
|
||||
let private_key = identity.get_private_key()?;
|
||||
Identity::from_private_key(&*private_key).ok()
|
||||
// Clone preserves a hardware backend (shared Arc) — there is no extractable
|
||||
// private key to copy; software identities clone their key material.
|
||||
if identity.has_private_key() || identity.has_backend() {
|
||||
Some(identity.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn identity_ed25519_public_key(identity: &Identity) -> [u8; 32] {
|
||||
let public_key = identity.get_public_key();
|
||||
let mut ed25519_pub = [0u8; 32];
|
||||
ed25519_pub.copy_from_slice(&public_key[32..64]);
|
||||
ed25519_pub
|
||||
}
|
||||
|
||||
fn unix_now() -> f64 {
|
||||
@@ -2332,9 +2613,31 @@ pub fn register_destination(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rns_identity::identity::LocalKeyBackend;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
const TEST_CHANNEL_MSG_TYPE: u16 = 0x1234;
|
||||
|
||||
struct TestSigningBackend {
|
||||
signing_key: Ed25519PrivateKey,
|
||||
available: AtomicBool,
|
||||
}
|
||||
|
||||
impl LocalKeyBackend for TestSigningBackend {
|
||||
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
|
||||
self.available
|
||||
.load(Ordering::SeqCst)
|
||||
.then(|| self.signing_key.sign(message))
|
||||
}
|
||||
|
||||
fn ecdh(&self, _peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
struct TestChannelNoop;
|
||||
|
||||
impl rns_protocol::channel_message::MessageBase for TestChannelNoop {
|
||||
@@ -2354,6 +2657,39 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn link_request_raw(dest_hash: [u8; 16], request_data: &[u8]) -> Vec<u8> {
|
||||
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);
|
||||
raw
|
||||
}
|
||||
|
||||
fn backend_identity(available: bool) -> (Identity, [u8; 32], [u8; 32]) {
|
||||
let software = Identity::new();
|
||||
let public_key = software.get_public_key();
|
||||
let identity_ed25519_pub = identity_ed25519_public_key(&software);
|
||||
let signing_seed = software.get_signing_key().unwrap().to_bytes();
|
||||
let backend: Arc<dyn LocalKeyBackend> = Arc::new(TestSigningBackend {
|
||||
signing_key: Ed25519PrivateKey::from_bytes(&signing_seed),
|
||||
available: AtomicBool::new(available),
|
||||
});
|
||||
let backend_identity = Identity::from_backend(&public_key, backend).unwrap();
|
||||
(backend_identity, identity_ed25519_pub, signing_seed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_manager_creation() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
@@ -2560,6 +2896,59 @@ mod tests {
|
||||
assert_eq!(lm.active_link_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_identity_accepts_link_request_without_raw_signing_key() {
|
||||
let (tx, mut rx) = mpsc::channel(16);
|
||||
let (_event_tx, event_rx) = mpsc::channel(16);
|
||||
let (identity, identity_ed25519_pub, _signing_seed) = backend_identity(true);
|
||||
let mut lm = LinkManager::with_destination(tx, event_rx, &identity, "test.hw", None);
|
||||
|
||||
let dest_hash = lm.destination_hash;
|
||||
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
|
||||
let raw = link_request_raw(dest_hash, &request_data);
|
||||
|
||||
lm.handle_link_request(&raw, 1);
|
||||
|
||||
assert_eq!(lm.active_link_count(), 1);
|
||||
let outbound = rx.try_recv().expect("link proof should be queued");
|
||||
let TransportMessage::Outbound(request) = outbound else {
|
||||
panic!("expected outbound link proof");
|
||||
};
|
||||
let (proof_header, proof_offset) =
|
||||
rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
|
||||
assert_eq!(
|
||||
proof_header.context,
|
||||
rns_wire::context::PacketContext::Lrproof
|
||||
);
|
||||
let identity_pub =
|
||||
rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&identity_ed25519_pub).unwrap();
|
||||
let rtt = initiator
|
||||
.validate_proof(
|
||||
&request.raw[proof_offset..],
|
||||
&identity_pub,
|
||||
&identity_ed25519_pub,
|
||||
)
|
||||
.expect("backend-signed proof validates");
|
||||
assert!(!rtt.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_identity_link_request_fails_closed_when_signer_unavailable() {
|
||||
let (tx, mut rx) = mpsc::channel(16);
|
||||
let (_event_tx, event_rx) = mpsc::channel(16);
|
||||
let (identity, _identity_ed25519_pub, _signing_seed) = backend_identity(false);
|
||||
let mut lm = LinkManager::with_destination(tx, event_rx, &identity, "test.hw", None);
|
||||
|
||||
let dest_hash = lm.destination_hash;
|
||||
let (_initiator, request_data) = Link::new_initiator(dest_hash, 1);
|
||||
let raw = link_request_raw(dest_hash, &request_data);
|
||||
|
||||
lm.handle_link_request(&raw, 1);
|
||||
|
||||
assert_eq!(lm.active_link_count(), 0);
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_destination_constructor() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
@@ -2568,7 +2957,8 @@ mod tests {
|
||||
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);
|
||||
let lm =
|
||||
LinkManager::with_destination(tx, event_rx, &identity, "test.app", Some(signing_key));
|
||||
|
||||
assert!(lm.destination.is_some());
|
||||
assert_eq!(lm.active_link_count(), 0);
|
||||
@@ -2582,7 +2972,7 @@ mod tests {
|
||||
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);
|
||||
LinkManager::with_destination(tx, event_rx, &identity, "test.app", Some(signing_key));
|
||||
|
||||
let tag = vec![0xA5; 16];
|
||||
lm.handle_event(DestinationEvent::AnnounceRequested(AnnounceRequest {
|
||||
@@ -2770,7 +3160,7 @@ mod tests {
|
||||
let signing_key = identity.get_signing_key().unwrap();
|
||||
|
||||
let mut lm =
|
||||
LinkManager::with_destination(tx, event_rx, &identity, "test.gate", signing_key);
|
||||
LinkManager::with_destination(tx, event_rx, &identity, "test.gate", Some(signing_key));
|
||||
|
||||
if let Some(ref mut dest) = lm.destination {
|
||||
dest.set_accepts_links(false);
|
||||
@@ -2904,6 +3294,83 @@ mod tests {
|
||||
assert!(sender_link.validate_packet_proof(&packet_hash, proof_data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_identity_signs_link_packet_delivery_proof() {
|
||||
let (identity, identity_ed25519_pub, signing_seed) = backend_identity(true);
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
let (_event_tx, event_rx) = mpsc::channel(16);
|
||||
let mut lm =
|
||||
LinkManager::with_destination(transport_tx, event_rx, &identity, "test.hw", None);
|
||||
|
||||
let dest_hash = lm.destination_hash;
|
||||
let identity_pub =
|
||||
rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&identity_ed25519_pub).unwrap();
|
||||
let signing_key = Ed25519PrivateKey::from_bytes(&signing_seed);
|
||||
let (mut sender_link, request_data) = Link::new_initiator(dest_hash, 1);
|
||||
let (mut receiver_link, proof_data) =
|
||||
Link::new_responder(&request_data, &signing_key, dest_hash, 1).unwrap();
|
||||
let rtt_data = sender_link
|
||||
.validate_proof(&proof_data, &identity_pub, &identity_ed25519_pub)
|
||||
.unwrap();
|
||||
receiver_link.receive_rtt_packet(&rtt_data).unwrap();
|
||||
let link_id = receiver_link.link_id;
|
||||
|
||||
let encrypted = sender_link.encrypt(b"link payload").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::None,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(&encrypted);
|
||||
let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type);
|
||||
|
||||
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 outbound = transport_rx
|
||||
.try_recv()
|
||||
.expect("backend-signed delivery 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::LinkProof
|
||||
);
|
||||
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();
|
||||
@@ -3105,6 +3572,145 @@ mod tests {
|
||||
assert!(lm.get_channel(&link_id).unwrap().is_ready_to_send());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_link_packet_emits_plain_link_data_and_proof_event() {
|
||||
let (initiator_link, responder_link, _identity_key) = handshaken_link_pair_with_identity();
|
||||
let link_id = responder_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, [0xC1; 16], None);
|
||||
let (proof_tx, mut proof_rx) = mpsc::channel(4);
|
||||
lm.set_link_packet_proof_channel(proof_tx);
|
||||
lm.active_links.insert(
|
||||
link_id,
|
||||
ActiveLink {
|
||||
link: responder_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_link_packet(&link_id, b"backchannel payload")
|
||||
.expect("link packet queued");
|
||||
let outbound = transport_rx.try_recv().expect("link packet outbound");
|
||||
let TransportMessage::Outbound(request) = outbound else {
|
||||
panic!("expected outbound link packet");
|
||||
};
|
||||
let (sent_header, sent_offset) =
|
||||
rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
|
||||
assert_eq!(sent_header.context, rns_wire::context::PacketContext::None);
|
||||
assert_eq!(sent_header.destination_hash, link_id);
|
||||
assert_eq!(
|
||||
receipt.packet_hash,
|
||||
rns_wire::hash::packet_hash(&request.raw, sent_header.flags.header_type)
|
||||
);
|
||||
assert_eq!(
|
||||
initiator_link.decrypt(&request.raw[sent_offset..]).unwrap(),
|
||||
b"backchannel payload"
|
||||
);
|
||||
|
||||
let proof_data = initiator_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);
|
||||
|
||||
let proof = proof_rx.try_recv().expect("link packet proof event");
|
||||
assert_eq!(proof.link_id, link_id);
|
||||
assert_eq!(proof.packet_hash, receipt.packet_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_link_resource_emits_resource_proof_event() {
|
||||
let (_initiator_link, responder_link, _identity_key) = handshaken_link_pair_with_identity();
|
||||
let link_id = responder_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, [0xC2; 16], None);
|
||||
let (proof_tx, mut proof_rx) = mpsc::channel(4);
|
||||
lm.set_outbound_resource_proof_channel(proof_tx);
|
||||
lm.active_links.insert(
|
||||
link_id,
|
||||
ActiveLink {
|
||||
link: responder_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_link_resource(&link_id, b"resource payload".to_vec(), false)
|
||||
.expect("resource started");
|
||||
let outbound = transport_rx.try_recv().expect("resource ADV outbound");
|
||||
let TransportMessage::Outbound(request) = outbound else {
|
||||
panic!("expected outbound resource ADV");
|
||||
};
|
||||
let (adv_header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
|
||||
assert_eq!(
|
||||
adv_header.context,
|
||||
rns_wire::context::PacketContext::ResourceAdv
|
||||
);
|
||||
|
||||
let proof_data = {
|
||||
let active = lm.active_links.get(&link_id).unwrap();
|
||||
let transfer = active
|
||||
.outbound_resources
|
||||
.get(&receipt.resource_hash)
|
||||
.expect("outbound resource tracked");
|
||||
let mut proof = Vec::new();
|
||||
proof.extend_from_slice(&transfer.resource.resource_hash);
|
||||
proof.extend_from_slice(&transfer.resource.expected_proof);
|
||||
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::ResourcePrf,
|
||||
};
|
||||
let mut proof_raw = proof_header.pack();
|
||||
proof_raw.extend_from_slice(&proof_data);
|
||||
lm.handle_inbound_packet(&proof_raw, 1);
|
||||
|
||||
let proof = proof_rx.try_recv().expect("resource proof event");
|
||||
assert_eq!(proof.link_id, link_id);
|
||||
assert_eq!(proof.resource_hash, receipt.resource_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmatched_valid_link_packet_proof_does_not_record_keepalive_proof() {
|
||||
let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity();
|
||||
|
||||
+121
-10
@@ -75,13 +75,52 @@ pub async fn spawn_probe_responder(
|
||||
.map_err(|_| ProbeError::TransportClosed)?;
|
||||
|
||||
let identity = Arc::new(identity);
|
||||
let mut destination = dest;
|
||||
// Implicit proof is Python's default (`use_implicit_proof = Yes`).
|
||||
let implicit = true;
|
||||
|
||||
tokio::spawn(async move {
|
||||
while let Some(event) = event_rx.recv().await {
|
||||
let DestinationEvent::InboundPacket { raw, .. } = event else {
|
||||
continue;
|
||||
let (raw, interface_id) = match event {
|
||||
DestinationEvent::InboundPacket { raw, interface_id } => (raw, interface_id),
|
||||
DestinationEvent::AnnounceRequested(request) => {
|
||||
let raw = match destination.announce_packet(
|
||||
identity.as_ref(),
|
||||
None,
|
||||
None,
|
||||
request.path_response,
|
||||
request.tag.as_deref(),
|
||||
unix_now(),
|
||||
) {
|
||||
Ok(raw) => raw,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
error = %e,
|
||||
path_response = request.path_response,
|
||||
"probe responder: failed to build requested announce"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let outbound = OutboundRequest {
|
||||
raw: Bytes::from(raw),
|
||||
destination_hash: dest_hash,
|
||||
};
|
||||
let message = if let Some(interface_id) = request.attached_interface {
|
||||
TransportMessage::OutboundAttached {
|
||||
request: outbound,
|
||||
interface_id,
|
||||
}
|
||||
} else {
|
||||
TransportMessage::Outbound(outbound)
|
||||
};
|
||||
if transport_tx.send(message).await.is_err() {
|
||||
tracing::debug!("probe responder: transport closed, exiting");
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let (header, _) = match PacketHeader::unpack(&raw) {
|
||||
Ok(h) => h,
|
||||
@@ -122,10 +161,13 @@ pub async fn spawn_probe_responder(
|
||||
proof_raw.extend_from_slice(&proof_payload);
|
||||
|
||||
if transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: Bytes::from(proof_raw),
|
||||
destination_hash: trunc_hash,
|
||||
}))
|
||||
.send(TransportMessage::OutboundAttached {
|
||||
request: OutboundRequest {
|
||||
raw: Bytes::from(proof_raw),
|
||||
destination_hash: trunc_hash,
|
||||
},
|
||||
interface_id,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
@@ -413,6 +455,13 @@ fn find_public_key(announces: &[AnnounceRpcEntry], dest_hash: &[u8; 16]) -> Opti
|
||||
.and_then(|a| a.public_key)
|
||||
}
|
||||
|
||||
fn unix_now() -> f64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -455,6 +504,8 @@ mod tests {
|
||||
timestamp: 0.0,
|
||||
public_key: Some([0x11; 64]),
|
||||
ratchet: None,
|
||||
name_hash: [0; 10],
|
||||
is_path_response: false,
|
||||
retained: false,
|
||||
},
|
||||
AnnounceRpcEntry {
|
||||
@@ -464,6 +515,8 @@ mod tests {
|
||||
timestamp: 0.0,
|
||||
public_key: Some([0x22; 64]),
|
||||
ratchet: None,
|
||||
name_hash: [0; 10],
|
||||
is_path_response: false,
|
||||
retained: false,
|
||||
},
|
||||
];
|
||||
@@ -524,15 +577,20 @@ mod tests {
|
||||
.await
|
||||
.expect("timed out waiting for proof")
|
||||
.expect("channel closed");
|
||||
let (request, interface_id) = match outbound {
|
||||
TransportMessage::OutboundAttached {
|
||||
request,
|
||||
interface_id,
|
||||
} => (request, interface_id),
|
||||
other => panic!("expected OutboundAttached, got {other:?}"),
|
||||
};
|
||||
let OutboundRequest {
|
||||
raw: proof_raw,
|
||||
destination_hash,
|
||||
} = match outbound {
|
||||
TransportMessage::Outbound(r) => r,
|
||||
other => panic!("expected Outbound, got {other:?}"),
|
||||
};
|
||||
} = request;
|
||||
|
||||
assert_eq!(destination_hash, expected_trunc);
|
||||
assert_eq!(interface_id, 0);
|
||||
|
||||
let (proof_header, data_offset) = PacketHeader::unpack(&proof_raw).unwrap();
|
||||
assert_eq!(proof_header.flags.packet_type, PacketType::Proof);
|
||||
@@ -552,6 +610,59 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn responder_sends_attached_path_response_announce() {
|
||||
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
|
||||
|
||||
let identity = Identity::new();
|
||||
let spawn_tx = tx.clone();
|
||||
let spawn_handle = tokio::spawn(async move {
|
||||
spawn_probe_responder(spawn_tx, identity, default_probe_app_name()).await
|
||||
});
|
||||
|
||||
let first = rx.recv().await.expect("RegisterDestination");
|
||||
let delivery_tx = match first {
|
||||
TransportMessage::RegisterDestination {
|
||||
delivery_tx: Some(dt),
|
||||
..
|
||||
} => dt,
|
||||
other => panic!("expected RegisterDestination, got {other:?}"),
|
||||
};
|
||||
let dest_hash = spawn_handle.await.unwrap().unwrap();
|
||||
|
||||
delivery_tx
|
||||
.send(DestinationEvent::AnnounceRequested(
|
||||
rns_transport::link_messages::AnnounceRequest {
|
||||
app_name: default_probe_app_name().to_string(),
|
||||
path_response: true,
|
||||
tag: Some(vec![0xA5; 16]),
|
||||
attached_interface: Some(7),
|
||||
},
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let outbound = tokio::time::timeout(Duration::from_secs(2), rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for path response")
|
||||
.expect("channel closed");
|
||||
let (request, interface_id) = match outbound {
|
||||
TransportMessage::OutboundAttached {
|
||||
request,
|
||||
interface_id,
|
||||
} => (request, interface_id),
|
||||
other => panic!("expected OutboundAttached, got {other:?}"),
|
||||
};
|
||||
|
||||
assert_eq!(interface_id, 7);
|
||||
assert_eq!(request.destination_hash, dest_hash);
|
||||
let (header, _offset) = PacketHeader::unpack(&request.raw).unwrap();
|
||||
assert_eq!(header.flags.packet_type, PacketType::Announce);
|
||||
assert_eq!(header.flags.destination_type, DestinationType::Single);
|
||||
assert_eq!(header.destination_hash, dest_hash);
|
||||
assert_eq!(header.context, PacketContext::PathResponse);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn responder_ignores_non_data_packets() {
|
||||
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
|
||||
|
||||
@@ -45,7 +45,7 @@ pub async fn start_remote_management(
|
||||
event_rx,
|
||||
identity,
|
||||
app_name,
|
||||
signing_key,
|
||||
Some(signing_key),
|
||||
);
|
||||
|
||||
let status_hash: [u8; 16] = truncated_hash(STATUS_PATH.as_bytes());
|
||||
@@ -252,7 +252,13 @@ fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats
|
||||
txb: e.tx_bytes,
|
||||
incoming_announce_frequency: e.incoming_announce_frequency,
|
||||
outgoing_announce_frequency: e.outgoing_announce_frequency,
|
||||
incoming_pr_frequency: e.incoming_pr_frequency,
|
||||
outgoing_pr_frequency: e.outgoing_pr_frequency,
|
||||
held_announces: e.held_announces,
|
||||
burst_active: e.burst_active,
|
||||
burst_activated: e.burst_activated,
|
||||
pr_burst_active: e.pr_burst_active,
|
||||
pr_burst_activated: e.pr_burst_activated,
|
||||
status: e.online,
|
||||
mode,
|
||||
bitrate: Some(e.bitrate),
|
||||
@@ -330,7 +336,13 @@ mod tests {
|
||||
txb: 7,
|
||||
incoming_announce_frequency: 0.0,
|
||||
outgoing_announce_frequency: 0.0,
|
||||
incoming_pr_frequency: 0.0,
|
||||
outgoing_pr_frequency: 0.0,
|
||||
held_announces: 0,
|
||||
burst_active: false,
|
||||
burst_activated: 0.0,
|
||||
pr_burst_active: false,
|
||||
pr_burst_activated: 0.0,
|
||||
status: true,
|
||||
mode: 0x01,
|
||||
bitrate: Some(1_000_000),
|
||||
@@ -465,11 +477,17 @@ mod tests {
|
||||
held_announces: 1,
|
||||
incoming_announce_frequency: 0.5,
|
||||
outgoing_announce_frequency: 0.25,
|
||||
incoming_pr_frequency: 3.0,
|
||||
outgoing_pr_frequency: 1.5,
|
||||
burst_active: true,
|
||||
burst_activated: 1_700_000_001.0,
|
||||
pr_burst_active: true,
|
||||
pr_burst_activated: 1_700_000_002.0,
|
||||
clients: None,
|
||||
announce_rate_target: None,
|
||||
announce_rate_grace: None,
|
||||
announce_rate_penalty: None,
|
||||
announce_cap: 2.0,
|
||||
announce_cap: 0.02,
|
||||
ifac_size: 0,
|
||||
tx_drops: 0,
|
||||
}];
|
||||
@@ -484,6 +502,9 @@ mod tests {
|
||||
hops: 2,
|
||||
expires: 1_700_100_000.0,
|
||||
interface: "MockIf".to_string(),
|
||||
interface_id: 1,
|
||||
interface_mode: rns_transport::constants::InterfaceMode::Full,
|
||||
interface_role: rns_transport::messages::InterfaceRole::Normal,
|
||||
}];
|
||||
TransportQueryResponse::PathTable(entries)
|
||||
}
|
||||
@@ -562,6 +583,34 @@ mod tests {
|
||||
Some(0x06),
|
||||
"Gateway mode maps to Python MODE_GATEWAY=0x06"
|
||||
);
|
||||
let incoming_pr = iface_map
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some("incoming_pr_frequency"))
|
||||
.unwrap()
|
||||
.1
|
||||
.as_f64();
|
||||
assert_eq!(incoming_pr, Some(3.0));
|
||||
let outgoing_pr = iface_map
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some("outgoing_pr_frequency"))
|
||||
.unwrap()
|
||||
.1
|
||||
.as_f64();
|
||||
assert_eq!(outgoing_pr, Some(1.5));
|
||||
let burst_active = iface_map
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some("burst_active"))
|
||||
.unwrap()
|
||||
.1
|
||||
.as_bool();
|
||||
assert_eq!(burst_active, Some(true));
|
||||
let pr_burst_active = iface_map
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some("pr_burst_active"))
|
||||
.unwrap()
|
||||
.1
|
||||
.as_bool();
|
||||
assert_eq!(pr_burst_active, Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
@@ -34,7 +34,13 @@ pub struct InterfaceStats {
|
||||
pub txb: u64,
|
||||
pub incoming_announce_frequency: f64,
|
||||
pub outgoing_announce_frequency: f64,
|
||||
pub incoming_pr_frequency: f64,
|
||||
pub outgoing_pr_frequency: f64,
|
||||
pub held_announces: u64,
|
||||
pub burst_active: bool,
|
||||
pub burst_activated: f64,
|
||||
pub pr_burst_active: bool,
|
||||
pub pr_burst_activated: f64,
|
||||
/// Python field name (not `online`).
|
||||
pub status: bool,
|
||||
/// Matches Python `Interface.MODE_*` integers.
|
||||
|
||||
+1437
-161
File diff suppressed because it is too large.
Load diff
@@ -235,7 +235,7 @@ pub async fn spawn_rncp_listener(
|
||||
dest_rx,
|
||||
&cfg.identity,
|
||||
&cfg.app_name,
|
||||
signing_key,
|
||||
Some(signing_key),
|
||||
);
|
||||
|
||||
let (completion_tx, mut completion_rx) = mpsc::channel::<ResourceCompletion>(64);
|
||||
|
||||
@@ -32,6 +32,7 @@ use rns_transport::messages::{
|
||||
AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
};
|
||||
|
||||
use crate::lifecycle::ShutdownSignal;
|
||||
use crate::link_manager::{
|
||||
ChannelSendError, LinkChannelMessage, LinkManager, LinkManagerCommand, register_destination,
|
||||
};
|
||||
@@ -132,6 +133,22 @@ pub struct RnshListenerConfig {
|
||||
pub async fn run_rnsh_listener(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
cfg: RnshListenerConfig,
|
||||
) -> Result<(), RnshError> {
|
||||
run_rnsh_listener_inner(transport_tx, cfg, None).await
|
||||
}
|
||||
|
||||
pub async fn run_rnsh_listener_with_shutdown(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
cfg: RnshListenerConfig,
|
||||
shutdown: ShutdownSignal,
|
||||
) -> Result<(), RnshError> {
|
||||
run_rnsh_listener_inner(transport_tx, cfg, Some(shutdown)).await
|
||||
}
|
||||
|
||||
async fn run_rnsh_listener_inner(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
cfg: RnshListenerConfig,
|
||||
shutdown: Option<ShutdownSignal>,
|
||||
) -> Result<(), RnshError> {
|
||||
let signing_key = cfg
|
||||
.identity
|
||||
@@ -152,7 +169,7 @@ pub async fn run_rnsh_listener(
|
||||
event_rx,
|
||||
&cfg.identity,
|
||||
RNSH_APP_NAME,
|
||||
signing_key,
|
||||
Some(signing_key),
|
||||
);
|
||||
|
||||
let announce_tx = transport_tx.clone();
|
||||
@@ -237,6 +254,15 @@ pub async fn run_rnsh_listener(
|
||||
} => {
|
||||
send_announce(&transport_tx, &cfg.identity, RNSH_APP_NAME).await?;
|
||||
}
|
||||
_ = async {
|
||||
if let Some(shutdown) = shutdown.as_ref() {
|
||||
shutdown.wait().await;
|
||||
} else {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
} => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//!
|
||||
//! 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.
|
||||
//! framed auth challenge (`#CHALLENGE#`), framed pickle request dictionaries,
|
||||
//! and framed pickle responses. Python 3.12+ uses tagged SHA-256 auth
|
||||
//! challenges, while Python 3.11 and older use raw MD5 HMAC responses.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -12,8 +13,23 @@ 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 MP_LEGACY_CHALLENGE_RANDOM_LEN: usize = 20;
|
||||
const MAX_MP_FRAME_SIZE: usize = 16 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum PythonAuthProtocol {
|
||||
LegacyMd5,
|
||||
Sha256,
|
||||
}
|
||||
|
||||
pub(crate) fn detect_python_auth_protocol(challenge: &[u8]) -> PythonAuthProtocol {
|
||||
if challenge.starts_with(MP_DIGEST_PREFIX) {
|
||||
PythonAuthProtocol::Sha256
|
||||
} else {
|
||||
PythonAuthProtocol::LegacyMd5
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum PyValue {
|
||||
None,
|
||||
@@ -45,6 +61,10 @@ pub enum RpcRequest {
|
||||
GetNextHop {
|
||||
destination_hash: Vec<u8>,
|
||||
},
|
||||
RequestPath {
|
||||
destination_hash: Vec<u8>,
|
||||
timeout_secs: Option<f64>,
|
||||
},
|
||||
GetFirstHopTimeout {
|
||||
destination_hash: Vec<u8>,
|
||||
},
|
||||
@@ -65,6 +85,8 @@ pub enum RpcRequest {
|
||||
DropAllVia {
|
||||
transport_hash: Vec<u8>,
|
||||
},
|
||||
DropPathTable,
|
||||
DropRecentAnnounces,
|
||||
DropAnnounceQueues,
|
||||
BlackholeIdentity {
|
||||
identity_hash: Vec<u8>,
|
||||
@@ -130,6 +152,18 @@ pub struct InterfaceStatEntry {
|
||||
pub held_announces: u64,
|
||||
pub incoming_announce_frequency: f64,
|
||||
pub outgoing_announce_frequency: f64,
|
||||
#[serde(default)]
|
||||
pub incoming_pr_frequency: f64,
|
||||
#[serde(default)]
|
||||
pub outgoing_pr_frequency: f64,
|
||||
#[serde(default)]
|
||||
pub burst_active: bool,
|
||||
#[serde(default)]
|
||||
pub burst_activated: f64,
|
||||
#[serde(default)]
|
||||
pub pr_burst_active: bool,
|
||||
#[serde(default)]
|
||||
pub pr_burst_activated: f64,
|
||||
pub clients: Option<u64>,
|
||||
pub announce_rate_target: Option<f64>,
|
||||
pub announce_rate_grace: Option<u32>,
|
||||
@@ -195,6 +229,18 @@ pub fn compute_auth_hmac(key: &[u8], challenge: &[u8]) -> [u8; 32] {
|
||||
out
|
||||
}
|
||||
|
||||
pub fn compute_legacy_auth_hmac(key: &[u8], challenge: &[u8]) -> [u8; 16] {
|
||||
use hmac::{Hmac, Mac};
|
||||
use md5::Md5;
|
||||
|
||||
let mut mac = Hmac::<Md5>::new_from_slice(key).expect("HMAC key can be any length");
|
||||
mac.update(challenge);
|
||||
let result = mac.finalize();
|
||||
let mut out = [0u8; 16];
|
||||
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;
|
||||
@@ -229,6 +275,17 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue {
|
||||
("get", PyValue::String("next_hop".to_string())),
|
||||
("destination_hash", PyValue::Bytes(destination_hash.clone())),
|
||||
]),
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash,
|
||||
timeout_secs,
|
||||
} => py_dict(vec![
|
||||
("request", PyValue::String("path".to_string())),
|
||||
("destination_hash", PyValue::Bytes(destination_hash.clone())),
|
||||
(
|
||||
"timeout",
|
||||
timeout_secs.map(PyValue::Float).unwrap_or(PyValue::None),
|
||||
),
|
||||
]),
|
||||
RpcRequest::GetFirstHopTimeout { destination_hash } => py_dict(vec![
|
||||
("get", PyValue::String("first_hop_timeout".to_string())),
|
||||
("destination_hash", PyValue::Bytes(destination_hash.clone())),
|
||||
@@ -255,6 +312,13 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue {
|
||||
("drop", PyValue::String("all_via".to_string())),
|
||||
("destination_hash", PyValue::Bytes(transport_hash.clone())),
|
||||
]),
|
||||
RpcRequest::DropPathTable => {
|
||||
py_dict(vec![("drop", PyValue::String("path_table".to_string()))])
|
||||
}
|
||||
RpcRequest::DropRecentAnnounces => py_dict(vec![(
|
||||
"drop",
|
||||
PyValue::String("recent_announces".to_string()),
|
||||
)]),
|
||||
RpcRequest::DropAnnounceQueues => py_dict(vec![(
|
||||
"drop",
|
||||
PyValue::String("announce_queues".to_string()),
|
||||
@@ -350,6 +414,8 @@ fn py_value_to_request(value: &PyValue) -> Result<RpcRequest, RpcError> {
|
||||
"all_via" => Ok(RpcRequest::DropAllVia {
|
||||
transport_hash: dict_bytes(entries, "destination_hash")?,
|
||||
}),
|
||||
"path_table" => Ok(RpcRequest::DropPathTable),
|
||||
"recent_announces" => Ok(RpcRequest::DropRecentAnnounces),
|
||||
"announce_queues" => Ok(RpcRequest::DropAnnounceQueues),
|
||||
other => Err(RpcError::Deserialize(format!(
|
||||
"unknown Python RPC drop path: {other}"
|
||||
@@ -357,6 +423,18 @@ fn py_value_to_request(value: &PyValue) -> Result<RpcRequest, RpcError> {
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(PyValue::String(path)) = dict_get(entries, "request") {
|
||||
return match path.as_str() {
|
||||
"path" => Ok(RpcRequest::RequestPath {
|
||||
destination_hash: dict_bytes(entries, "destination_hash")?,
|
||||
timeout_secs: dict_get(entries, "timeout").and_then(py_f64),
|
||||
}),
|
||||
other => Err(RpcError::Deserialize(format!(
|
||||
"unknown Python RPC request path: {other}"
|
||||
))),
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(PyValue::Bytes(identity_hash)) = dict_get(entries, "blackhole_identity") {
|
||||
return Ok(RpcRequest::BlackholeIdentity {
|
||||
identity_hash: identity_hash.clone(),
|
||||
@@ -454,6 +532,18 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
"outgoing_announce_frequency",
|
||||
PyValue::Float(e.outgoing_announce_frequency),
|
||||
),
|
||||
(
|
||||
"incoming_pr_frequency",
|
||||
PyValue::Float(e.incoming_pr_frequency),
|
||||
),
|
||||
(
|
||||
"outgoing_pr_frequency",
|
||||
PyValue::Float(e.outgoing_pr_frequency),
|
||||
),
|
||||
("burst_active", PyValue::Bool(e.burst_active)),
|
||||
("burst_activated", PyValue::Float(e.burst_activated)),
|
||||
("pr_burst_active", PyValue::Bool(e.pr_burst_active)),
|
||||
("pr_burst_activated", PyValue::Float(e.pr_burst_activated)),
|
||||
(
|
||||
"clients",
|
||||
e.clients
|
||||
@@ -577,13 +667,19 @@ fn py_value_to_response_for_request(
|
||||
Ok(RpcResponse::StringResult(py_optional_string(value)?))
|
||||
}
|
||||
RpcRequest::GetNextHop { .. } => Ok(RpcResponse::HashResult(py_optional_bytes(value)?)),
|
||||
RpcRequest::RequestPath { .. } => Ok(RpcResponse::BoolResult(match value {
|
||||
PyValue::Bool(v) => *v,
|
||||
PyValue::None => false,
|
||||
_ => py_required_int(value)? != 0,
|
||||
})),
|
||||
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::GetLinkCount
|
||||
| RpcRequest::DropAllVia { .. }
|
||||
| RpcRequest::DropPathTable
|
||||
| RpcRequest::DropRecentAnnounces => Ok(RpcResponse::IntResult(py_required_int(value)?)),
|
||||
RpcRequest::GetBlackholedIdentities => {
|
||||
Ok(RpcResponse::BlackholeList(parse_blackhole_list(value)?))
|
||||
}
|
||||
@@ -704,6 +800,24 @@ fn parse_interface_stats(value: &PyValue) -> Result<Vec<InterfaceStatEntry>, Rpc
|
||||
outgoing_announce_frequency: dict_get(m, "outgoing_announce_frequency")
|
||||
.and_then(py_f64)
|
||||
.unwrap_or(0.0),
|
||||
incoming_pr_frequency: dict_get(m, "incoming_pr_frequency")
|
||||
.and_then(py_f64)
|
||||
.unwrap_or(0.0),
|
||||
outgoing_pr_frequency: dict_get(m, "outgoing_pr_frequency")
|
||||
.and_then(py_f64)
|
||||
.unwrap_or(0.0),
|
||||
burst_active: dict_get(m, "burst_active")
|
||||
.and_then(py_bool)
|
||||
.unwrap_or(false),
|
||||
burst_activated: dict_get(m, "burst_activated")
|
||||
.and_then(py_f64)
|
||||
.unwrap_or(0.0),
|
||||
pr_burst_active: dict_get(m, "pr_burst_active")
|
||||
.and_then(py_bool)
|
||||
.unwrap_or(false),
|
||||
pr_burst_activated: dict_get(m, "pr_burst_activated")
|
||||
.and_then(py_f64)
|
||||
.unwrap_or(0.0),
|
||||
clients: match dict_get(m, "clients") {
|
||||
Some(PyValue::None) | None => None,
|
||||
Some(value) => py_u64(value),
|
||||
@@ -1313,6 +1427,18 @@ fn read_u64_le(data: &[u8], index: &mut usize) -> Result<u64, RpcError> {
|
||||
}
|
||||
|
||||
pub fn compute_python_auth_response(key: &[u8], message: &[u8]) -> Vec<u8> {
|
||||
compute_python_auth_response_for(detect_python_auth_protocol(message), key, message)
|
||||
}
|
||||
|
||||
pub(crate) fn compute_python_auth_response_for(
|
||||
protocol: PythonAuthProtocol,
|
||||
key: &[u8],
|
||||
message: &[u8],
|
||||
) -> Vec<u8> {
|
||||
if protocol == PythonAuthProtocol::LegacyMd5 {
|
||||
return compute_legacy_auth_hmac(key, message).to_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));
|
||||
@@ -1320,7 +1446,26 @@ pub fn compute_python_auth_response(key: &[u8], message: &[u8]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
pub fn verify_python_auth_response(key: &[u8], message: &[u8], response: &[u8]) -> bool {
|
||||
let protocol = if response.starts_with(MP_DIGEST_PREFIX) {
|
||||
PythonAuthProtocol::Sha256
|
||||
} else {
|
||||
PythonAuthProtocol::LegacyMd5
|
||||
};
|
||||
verify_python_auth_response_for(protocol, key, message, response)
|
||||
}
|
||||
|
||||
pub(crate) fn verify_python_auth_response_for(
|
||||
protocol: PythonAuthProtocol,
|
||||
key: &[u8],
|
||||
message: &[u8],
|
||||
response: &[u8],
|
||||
) -> bool {
|
||||
use subtle::ConstantTimeEq;
|
||||
if protocol == PythonAuthProtocol::LegacyMd5 {
|
||||
let expected = compute_legacy_auth_hmac(key, message);
|
||||
return expected.as_slice().ct_eq(response).into();
|
||||
}
|
||||
|
||||
if !response.starts_with(MP_DIGEST_PREFIX) {
|
||||
return false;
|
||||
}
|
||||
@@ -1330,6 +1475,14 @@ pub fn verify_python_auth_response(key: &[u8], message: &[u8], response: &[u8])
|
||||
}
|
||||
|
||||
pub fn new_python_challenge() -> Vec<u8> {
|
||||
new_python_challenge_for(PythonAuthProtocol::Sha256)
|
||||
}
|
||||
|
||||
pub(crate) fn new_python_challenge_for(protocol: PythonAuthProtocol) -> Vec<u8> {
|
||||
if protocol == PythonAuthProtocol::LegacyMd5 {
|
||||
return rns_crypto::random::random_bytes(MP_LEGACY_CHALLENGE_RANDOM_LEN);
|
||||
}
|
||||
|
||||
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));
|
||||
@@ -1494,8 +1647,9 @@ where
|
||||
return Err(RpcError::AuthFailed);
|
||||
}
|
||||
let challenge = &challenge_frame[MP_CHALLENGE.len()..];
|
||||
let protocol = detect_python_auth_protocol(challenge);
|
||||
|
||||
let response = compute_python_auth_response(rpc_key, challenge);
|
||||
let response = compute_python_auth_response_for(protocol, rpc_key, challenge);
|
||||
tokio::time::timeout(timeout, write_mp_frame(&mut stream, &response))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
@@ -1517,7 +1671,7 @@ where
|
||||
return Err(RpcError::AuthFailed);
|
||||
}
|
||||
|
||||
let client_challenge = new_python_challenge();
|
||||
let client_challenge = new_python_challenge_for(protocol);
|
||||
let mut client_challenge_frame =
|
||||
Vec::with_capacity(MP_CHALLENGE.len() + client_challenge.len());
|
||||
client_challenge_frame.extend_from_slice(MP_CHALLENGE);
|
||||
@@ -1542,7 +1696,7 @@ where
|
||||
"server auth response read timeout",
|
||||
))
|
||||
})??;
|
||||
if verify_python_auth_response(rpc_key, &client_challenge, &server_response) {
|
||||
if verify_python_auth_response_for(protocol, rpc_key, &client_challenge, &server_response) {
|
||||
tokio::time::timeout(timeout, write_mp_frame(&mut stream, MP_WELCOME))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
@@ -1640,6 +1794,89 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn interface_stat_entry() -> InterfaceStatEntry {
|
||||
InterfaceStatEntry {
|
||||
id: 7,
|
||||
name: "TestIf".to_string(),
|
||||
rx_bytes: 100,
|
||||
tx_bytes: 200,
|
||||
rx_rate: 10,
|
||||
tx_rate: 20,
|
||||
online: true,
|
||||
bitrate: 115_200,
|
||||
mtu: 500,
|
||||
mode: "Gateway".to_string(),
|
||||
role: "normal".to_string(),
|
||||
announce_queue: Some(2),
|
||||
held_announces: 3,
|
||||
incoming_announce_frequency: 4.0,
|
||||
outgoing_announce_frequency: 5.0,
|
||||
incoming_pr_frequency: 6.0,
|
||||
outgoing_pr_frequency: 7.0,
|
||||
burst_active: true,
|
||||
burst_activated: 1_700_000_001.0,
|
||||
pr_burst_active: true,
|
||||
pr_burst_activated: 1_700_000_002.0,
|
||||
clients: Some(4),
|
||||
announce_rate_target: Some(3600.0),
|
||||
announce_rate_grace: Some(5),
|
||||
announce_rate_penalty: Some(30.0),
|
||||
announce_cap: 0.02,
|
||||
ifac_size: 0,
|
||||
tx_drops: 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_interface_stats_response_roundtrip_includes_125_fields() {
|
||||
let resp = RpcResponse::InterfaceStats(vec![interface_stat_entry()]);
|
||||
let encoded = encode_response(&resp).unwrap();
|
||||
let decoded =
|
||||
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap();
|
||||
match decoded {
|
||||
RpcResponse::InterfaceStats(entries) => {
|
||||
assert_eq!(entries.len(), 1);
|
||||
let entry = &entries[0];
|
||||
assert_eq!(entry.incoming_pr_frequency, 6.0);
|
||||
assert_eq!(entry.outgoing_pr_frequency, 7.0);
|
||||
assert!(entry.burst_active);
|
||||
assert_eq!(entry.burst_activated, 1_700_000_001.0);
|
||||
assert!(entry.pr_burst_active);
|
||||
assert_eq!(entry.pr_burst_activated, 1_700_000_002.0);
|
||||
}
|
||||
_ => panic!("wrong variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_interface_stats_parser_defaults_missing_125_fields() {
|
||||
let legacy = py_dict(vec![(
|
||||
"interfaces",
|
||||
PyValue::List(vec![py_dict(vec![
|
||||
("name", PyValue::String("LegacyIf".to_string())),
|
||||
("rxb", PyValue::Int(1)),
|
||||
("txb", PyValue::Int(2)),
|
||||
("status", PyValue::Bool(true)),
|
||||
])]),
|
||||
)]);
|
||||
let encoded = encode_python_pickle(&legacy).unwrap();
|
||||
let decoded =
|
||||
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap();
|
||||
match decoded {
|
||||
RpcResponse::InterfaceStats(entries) => {
|
||||
assert_eq!(entries.len(), 1);
|
||||
let entry = &entries[0];
|
||||
assert_eq!(entry.incoming_pr_frequency, 0.0);
|
||||
assert_eq!(entry.outgoing_pr_frequency, 0.0);
|
||||
assert!(!entry.burst_active);
|
||||
assert_eq!(entry.burst_activated, 0.0);
|
||||
assert!(!entry.pr_burst_active);
|
||||
assert_eq!(entry.pr_burst_activated, 0.0);
|
||||
}
|
||||
_ => panic!("wrong variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_python_blackhole_dict_response_shape() {
|
||||
let identity_hash = vec![0x42; 16];
|
||||
@@ -1681,6 +1918,34 @@ mod tests {
|
||||
assert!(!verify_auth_hmac(wrong_key, challenge, &hmac));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_python_legacy_md5_auth_response() {
|
||||
let key = b"test_rpc_key";
|
||||
let challenge = b"python311challenge";
|
||||
let response = compute_python_auth_response(key, challenge);
|
||||
assert_eq!(response.len(), 16);
|
||||
assert!(verify_python_auth_response(key, challenge, &response));
|
||||
assert!(!verify_python_auth_response(
|
||||
b"wrong_key",
|
||||
challenge,
|
||||
&response
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_python_sha256_auth_response() {
|
||||
let key = b"test_rpc_key";
|
||||
let challenge = b"{sha256}python312pluschallenge";
|
||||
let response = compute_python_auth_response(key, challenge);
|
||||
assert!(response.starts_with(MP_DIGEST_PREFIX));
|
||||
assert!(verify_python_auth_response(key, challenge, &response));
|
||||
assert!(!verify_python_auth_response(
|
||||
b"wrong_key",
|
||||
challenge,
|
||||
&response
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_rpc_key() {
|
||||
let private_key = [0x42u8; 64];
|
||||
@@ -1699,10 +1964,16 @@ mod tests {
|
||||
RpcRequest::GetNextHopIfName {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash: vec![0; 16],
|
||||
timeout_secs: Some(0.01),
|
||||
},
|
||||
RpcRequest::GetLinkCount,
|
||||
RpcRequest::DropPath {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPathTable,
|
||||
RpcRequest::DropRecentAnnounces,
|
||||
RpcRequest::DropAnnounceQueues,
|
||||
RpcRequest::BlackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
|
||||
@@ -198,7 +198,11 @@ async fn handle_rpc_client(
|
||||
return Err(RpcError::AuthFailed);
|
||||
}
|
||||
let client_challenge = &client_challenge_frame[rpc::MP_CHALLENGE.len()..];
|
||||
let client_response = rpc::compute_python_auth_response(rpc_key, client_challenge);
|
||||
let client_response = rpc::compute_python_auth_response_for(
|
||||
rpc::detect_python_auth_protocol(client_challenge),
|
||||
rpc_key,
|
||||
client_challenge,
|
||||
);
|
||||
rpc::write_mp_frame(&mut stream, &client_response).await?;
|
||||
let client_welcome = rpc::read_mp_frame(&mut stream, 256).await?;
|
||||
if client_welcome != rpc::MP_WELCOME {
|
||||
@@ -222,20 +226,58 @@ async fn query_transport(
|
||||
query: rns_transport::messages::TransportQuery,
|
||||
) -> Option<rns_transport::messages::TransportQueryResponse> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
if transport_tx
|
||||
.send(TransportMessage::Rpc {
|
||||
let budget = std::time::Duration::from_secs(5);
|
||||
let started = std::time::Instant::now();
|
||||
match tokio::time::timeout(
|
||||
budget,
|
||||
transport_tx.send(TransportMessage::Rpc {
|
||||
query,
|
||||
response_tx: tx,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => return None,
|
||||
Err(_) => return None,
|
||||
}
|
||||
let remaining = budget.checked_sub(started.elapsed())?;
|
||||
tokio::time::timeout(remaining, rx)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.ok())
|
||||
}
|
||||
|
||||
async fn request_path(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
destination_hash: [u8; 16],
|
||||
timeout_secs: Option<f64>,
|
||||
) -> bool {
|
||||
let wait = std::time::Duration::from_secs_f64(timeout_secs.unwrap_or(5.0).max(0.1));
|
||||
if transport_tx
|
||||
.send(TransportMessage::RequestPath { destination_hash })
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let (reply, rx) = tokio::sync::oneshot::channel();
|
||||
if transport_tx
|
||||
.send(TransportMessage::AwaitPath {
|
||||
dest: destination_hash,
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
|
||||
match tokio::time::timeout(wait, rx).await {
|
||||
Ok(Ok(found)) => found,
|
||||
_ => false,
|
||||
}
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), rx)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.ok())
|
||||
}
|
||||
|
||||
async fn process_rpc_request(
|
||||
@@ -286,6 +328,12 @@ async fn process_rpc_request(
|
||||
held_announces: e.held_announces,
|
||||
incoming_announce_frequency: e.incoming_announce_frequency,
|
||||
outgoing_announce_frequency: e.outgoing_announce_frequency,
|
||||
incoming_pr_frequency: e.incoming_pr_frequency,
|
||||
outgoing_pr_frequency: e.outgoing_pr_frequency,
|
||||
burst_active: e.burst_active,
|
||||
burst_activated: e.burst_activated,
|
||||
pr_burst_active: e.pr_burst_active,
|
||||
pr_burst_activated: e.pr_burst_activated,
|
||||
clients: e.clients,
|
||||
announce_rate_target: e.announce_rate_target,
|
||||
announce_rate_grace: e.announce_rate_grace,
|
||||
@@ -297,7 +345,9 @@ async fn process_rpc_request(
|
||||
.collect();
|
||||
RpcResponse::InterfaceStats(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::InterfaceStats(Vec::new()),
|
||||
_ => RpcResponse::Error(
|
||||
"transport actor did not answer interface stats query".to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetRateTable => {
|
||||
@@ -360,6 +410,15 @@ async fn process_rpc_request(
|
||||
None => RpcResponse::HashResult(None),
|
||||
}
|
||||
}
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash,
|
||||
timeout_secs,
|
||||
} => match hash_to_array(&destination_hash) {
|
||||
Some(dest) => {
|
||||
RpcResponse::BoolResult(request_path(transport_tx, dest, timeout_secs).await)
|
||||
}
|
||||
None => RpcResponse::BoolResult(false),
|
||||
},
|
||||
RpcRequest::DropPath { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
if let Some(d) = dest {
|
||||
@@ -367,6 +426,22 @@ async fn process_rpc_request(
|
||||
}
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::DropPathTable => {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropPathTable).await
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::DropRecentAnnounces => {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropRecentAnnounces).await
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::DropAnnounceQueues => {
|
||||
let _ = query_transport(transport_tx, TransportQuery::DropAnnounceQueues).await;
|
||||
RpcResponse::Ok
|
||||
@@ -827,6 +902,10 @@ listener.close()
|
||||
RpcRequest::GetNextHop {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash: vec![0; 16],
|
||||
timeout_secs: Some(0.01),
|
||||
},
|
||||
RpcRequest::GetFirstHopTimeout {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
@@ -847,6 +926,8 @@ listener.close()
|
||||
RpcRequest::DropAllVia {
|
||||
transport_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPathTable,
|
||||
RpcRequest::DropRecentAnnounces,
|
||||
RpcRequest::DropAnnounceQueues,
|
||||
RpcRequest::BlackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
@@ -878,6 +959,44 @@ listener.close()
|
||||
let _ = tx.send(TransportMessage::Shutdown).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_path_rpc_sends_transport_request_and_awaits_result() {
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let dest = [0x42; 16];
|
||||
let handle = tokio::spawn(async move {
|
||||
process_rpc_request(
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash: dest.to_vec(),
|
||||
timeout_secs: Some(1.0),
|
||||
},
|
||||
&tx,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
match rx.recv().await.expect("RequestPath message") {
|
||||
TransportMessage::RequestPath { destination_hash } => {
|
||||
assert_eq!(destination_hash, dest)
|
||||
}
|
||||
other => panic!("expected RequestPath, got {other:?}"),
|
||||
}
|
||||
match rx.recv().await.expect("AwaitPath message") {
|
||||
TransportMessage::AwaitPath {
|
||||
dest: awaited,
|
||||
reply,
|
||||
} => {
|
||||
assert_eq!(awaited, dest);
|
||||
reply.send(true).unwrap();
|
||||
}
|
||||
other => panic!("expected AwaitPath, got {other:?}"),
|
||||
}
|
||||
|
||||
assert!(matches!(
|
||||
handle.await.unwrap(),
|
||||
RpcResponse::BoolResult(true)
|
||||
));
|
||||
}
|
||||
|
||||
fn portpicker_ephemeral() -> u16 {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.local_addr().unwrap().port()
|
||||
|
||||
@@ -42,7 +42,7 @@ use rns_runtime::rncp::{
|
||||
};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -197,7 +197,7 @@ fn load_or_create_identity(
|
||||
pub(crate) async fn main() {
|
||||
let args = Args::parse();
|
||||
if args.version {
|
||||
println!("rncp-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rncp-rs {RS_RETICULUM_VERSION}");
|
||||
return;
|
||||
}
|
||||
if args.phy_rates {
|
||||
@@ -228,6 +228,9 @@ pub(crate) async fn main() {
|
||||
}
|
||||
|
||||
async fn run_fetch(args: Args) -> ! {
|
||||
// Register before any slow init so an early SIGINT exits cleanly.
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
// In fetch mode the positionals are `<destination_hash> <remote_path>`.
|
||||
let (Some(dest_arg), Some(path_arg)) = (args.file.as_ref(), args.destination.as_ref()) else {
|
||||
eprintln!("rncp-rs: fetch mode requires <destination_hash> <remote_path>");
|
||||
@@ -264,7 +267,7 @@ async fn run_fetch(args: Args) -> ! {
|
||||
None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
};
|
||||
|
||||
let handle = start_reticulum(args.config.as_deref()).await;
|
||||
let handle = start_reticulum(args.config.as_deref(), shutdown.clone()).await;
|
||||
let paths = StoragePaths::from_config_dir(&handle.config_dir);
|
||||
let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir)
|
||||
{
|
||||
@@ -371,6 +374,9 @@ fn print_fetch_summary(outcome: &RncpFetchOutcome) {
|
||||
}
|
||||
|
||||
async fn run_send(args: Args) -> ! {
|
||||
// Register before any slow init so an early SIGINT exits cleanly.
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
let (Some(file_arg), Some(dest_arg)) = (args.file.as_ref(), args.destination.as_ref()) else {
|
||||
// Bare `rncp` prints help and exits 0.
|
||||
let mut cmd = <Args as clap::CommandFactory>::command();
|
||||
@@ -407,7 +413,7 @@ async fn run_send(args: Args) -> ! {
|
||||
}
|
||||
};
|
||||
|
||||
let handle = start_reticulum(args.config.as_deref()).await;
|
||||
let handle = start_reticulum(args.config.as_deref(), shutdown.clone()).await;
|
||||
|
||||
let paths = StoragePaths::from_config_dir(&handle.config_dir);
|
||||
let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir)
|
||||
@@ -525,6 +531,9 @@ fn human_rate(bps: f64) -> (f64, &'static str) {
|
||||
}
|
||||
|
||||
async fn run_listen(args: Args) -> ! {
|
||||
// Register before any slow init so an early SIGINT exits cleanly.
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
let save_dir = match args.save.as_deref() {
|
||||
Some(p) => {
|
||||
let path = expand_tilde(p);
|
||||
@@ -571,7 +580,7 @@ async fn run_listen(args: Args) -> ! {
|
||||
eprintln!("Warning: No allowed identities configured, rncp will not accept any files!");
|
||||
}
|
||||
|
||||
let handle = start_reticulum(args.config.as_deref()).await;
|
||||
let handle = start_reticulum(args.config.as_deref(), shutdown.clone()).await;
|
||||
let paths = StoragePaths::from_config_dir(&handle.config_dir);
|
||||
let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir)
|
||||
{
|
||||
@@ -695,6 +704,9 @@ async fn run_listen(args: Args) -> ! {
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = handle.shutdown.wait() => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -702,6 +714,7 @@ async fn run_listen(args: Args) -> ! {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
listener.shutdown().await;
|
||||
|
||||
process::exit(0);
|
||||
}
|
||||
@@ -802,9 +815,10 @@ fn rncp_allowed_identity_file_candidates() -> Vec<PathBuf> {
|
||||
paths
|
||||
}
|
||||
|
||||
async fn start_reticulum(config_dir: Option<&str>) -> rns_runtime::reticulum::ReticulumHandle {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
async fn start_reticulum(
|
||||
config_dir: Option<&str>,
|
||||
shutdown: ShutdownSignal,
|
||||
) -> rns_runtime::reticulum::ReticulumHandle {
|
||||
let is_foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
match rns_runtime::reticulum::init(config_dir, None, shutdown.clone(), is_foreground).await {
|
||||
Ok(h) => h,
|
||||
|
||||
@@ -8,13 +8,77 @@ pub fn run(cmd: HwCommands) {
|
||||
pin,
|
||||
nickname,
|
||||
output,
|
||||
mgmt_key,
|
||||
} => {
|
||||
cmd_provision(pin, nickname, output);
|
||||
cmd_provision(pin, nickname, output, mgmt_key);
|
||||
}
|
||||
HwCommands::List { dir } => cmd_list(dir),
|
||||
HwCommands::Info { hwid } => cmd_info(hwid),
|
||||
HwCommands::Verify { hwid } => cmd_verify(hwid),
|
||||
HwCommands::Test { hwid } => cmd_test(hwid),
|
||||
HwCommands::Test { hwid, pin } => cmd_test(hwid, pin),
|
||||
HwCommands::Attest => cmd_attest(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch on-card attestation certs and verify the chain to a bundled Yubico root.
|
||||
/// ATTEST + reading the F9 device cert are unauthenticated (no PIN).
|
||||
fn cmd_attest() {
|
||||
let mut session = match rns_ratkey::PcscPivSession::connect() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("Error connecting to hardware token: {e}");
|
||||
eprintln!("\nRun `rnid-rs hw detect` to check for connected devices.");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let device_cert = match session.read_attestation_cert() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("Error reading device attestation cert (slot F9): {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
println!(
|
||||
"Attesting {} (serial {}, firmware {})...\n",
|
||||
session.device_type().as_str(),
|
||||
session.serial().unwrap_or(0),
|
||||
session.firmware().unwrap_or("unknown"),
|
||||
);
|
||||
|
||||
let mut all_ok = true;
|
||||
for (label, slot) in [
|
||||
("9A (signing)", rns_ratkey::apdu::SLOT_AUTHENTICATION),
|
||||
("9D (encryption)", rns_ratkey::apdu::SLOT_KEY_MANAGEMENT),
|
||||
] {
|
||||
match session.attest_key(slot) {
|
||||
Ok(cert) => match rns_ratkey::attestation::verify_attestation(&cert, &device_cert) {
|
||||
Ok(v) => {
|
||||
println!("Slot {label}:");
|
||||
println!(" chain_verified: {}", v.chain_verified);
|
||||
println!(" root CA: {}", v.root_ca);
|
||||
println!(" {}", v.description);
|
||||
all_ok &= v.chain_verified;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Slot {label}: verification error: {e}");
|
||||
all_ok = false;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("Slot {label}: attest error: {e}");
|
||||
all_ok = false;
|
||||
}
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
if all_ok {
|
||||
println!("✓ Attestation chain cryptographically verified to a bundled Yubico root.");
|
||||
} else {
|
||||
eprintln!("✗ Attestation could not be fully verified.");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +130,42 @@ fn cmd_detect() {
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<PathBuf>) {
|
||||
/// Best-effort on-card attestation capture for the `.hwid`: the per-slot certs +
|
||||
/// the chain-verified flag. Empty on devices without PIV attestation (e.g. Nitrokey).
|
||||
fn capture_attestation(
|
||||
session: &mut rns_ratkey::PcscPivSession,
|
||||
) -> rns_ratkey::hwid::HwidAttestation {
|
||||
let device = match session.read_attestation_cert() {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Default::default(),
|
||||
};
|
||||
let ed = session
|
||||
.attest_key(rns_ratkey::apdu::SLOT_AUTHENTICATION)
|
||||
.ok();
|
||||
let x = session
|
||||
.attest_key(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT)
|
||||
.ok();
|
||||
let verified = ed
|
||||
.as_ref()
|
||||
.and_then(|c| rns_ratkey::attestation::verify_attestation(c, &device).ok())
|
||||
.map(|v| v.chain_verified)
|
||||
.unwrap_or(false);
|
||||
rns_ratkey::hwid::HwidAttestation {
|
||||
ed25519_cert: ed.map(hex::encode).unwrap_or_default(),
|
||||
x25519_cert: x.map(hex::encode).unwrap_or_default(),
|
||||
verified,
|
||||
}
|
||||
}
|
||||
|
||||
/// Factory-default PIV management key (24 bytes; AES-192 on YubiKey 5.7+).
|
||||
const DEFAULT_MGMT_KEY: &str = "010203040506070801020304050607080102030405060708";
|
||||
|
||||
fn cmd_provision(
|
||||
pin: Option<String>,
|
||||
nickname: Option<String>,
|
||||
output: Option<PathBuf>,
|
||||
mgmt_key: Option<String>,
|
||||
) {
|
||||
let pin = match pin {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
@@ -81,7 +180,7 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let mut session = match rns_ratkey::session::PivSession::connect() {
|
||||
let mut session = match rns_ratkey::PcscPivSession::connect() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("Error connecting to hardware token: {e}");
|
||||
@@ -95,12 +194,29 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// Slot 9A (PIV authentication), touch-always: prevents silent sign while PIN cache valid.
|
||||
// Key generation is an administrative op gated by the management key, not the PIN.
|
||||
let mgmt_key_hex = mgmt_key.unwrap_or_else(|| DEFAULT_MGMT_KEY.to_string());
|
||||
let mgmt_key_bytes = match hex::decode(mgmt_key_hex.trim()) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
eprintln!("Error: invalid --mgmt-key hex: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
if let Err(e) = session.authenticate_management_key(&mgmt_key_bytes) {
|
||||
eprintln!("Management key authentication failed: {e}");
|
||||
eprintln!("Pass --mgmt-key <hex> if the device uses a non-default management key.");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// Slot 9A (PIV authentication). PIN-once + touch-never: the PIN is the
|
||||
// session unlock; the app re-locks on timeout / quit. (Policies are burned
|
||||
// in permanently for a hardware-only identity.)
|
||||
println!("Generating Ed25519 key in slot 9A...");
|
||||
let ed_pub = match session.generate_ed25519(
|
||||
rns_ratkey::apdu::SLOT_AUTHENTICATION,
|
||||
Some(rns_ratkey::apdu::PIN_POLICY_ONCE),
|
||||
Some(rns_ratkey::apdu::TOUCH_POLICY_ALWAYS),
|
||||
Some(rns_ratkey::apdu::TOUCH_POLICY_NEVER),
|
||||
) {
|
||||
Ok(pub_key) => pub_key,
|
||||
Err(e) => {
|
||||
@@ -109,12 +225,13 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
|
||||
}
|
||||
};
|
||||
|
||||
// Slot 9D (PIV key management), touch-cached: one tap unlocks ECDH for a window (else every packet prompts).
|
||||
// Slot 9D (PIV key management). PIN-once + touch-never: ECDH runs on every
|
||||
// inbound packet, so per-op touch is impractical; the PIN gates the session.
|
||||
println!("Generating X25519 key in slot 9D...");
|
||||
let x_pub = match session.generate_x25519(
|
||||
rns_ratkey::apdu::SLOT_KEY_MANAGEMENT,
|
||||
Some(rns_ratkey::apdu::PIN_POLICY_ONCE),
|
||||
Some(rns_ratkey::apdu::TOUCH_POLICY_CACHED),
|
||||
Some(rns_ratkey::apdu::TOUCH_POLICY_NEVER),
|
||||
) {
|
||||
Ok(pub_key) => pub_key,
|
||||
Err(e) => {
|
||||
@@ -126,11 +243,15 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
|
||||
let identity_hash = rns_ratkey::provision::compute_identity_hash(&ed_pub, &x_pub);
|
||||
let hash_hex = hex::encode(identity_hash);
|
||||
|
||||
// Capture + verify the on-card attestation chain so the .hwid records it.
|
||||
let attestation = capture_attestation(&mut session);
|
||||
|
||||
println!("\nHardware identity provisioned:");
|
||||
println!(" Identity hash: {hash_hex}");
|
||||
println!(" Ed25519 public: {}", hex::encode(ed_pub));
|
||||
println!(" X25519 public: {}", hex::encode(x_pub));
|
||||
println!(" Device: {}", session.device_type().as_str());
|
||||
println!(" Attestation: chain_verified={}", attestation.verified);
|
||||
|
||||
if let Some(dir) = output {
|
||||
let identity_dir = dir.join(&hash_hex);
|
||||
@@ -164,10 +285,10 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
|
||||
},
|
||||
policy: rns_ratkey::hwid::HwidPolicy {
|
||||
pin_cache_timeout: 300,
|
||||
touch_signing: "always".to_string(),
|
||||
touch_encryption: "cached".to_string(),
|
||||
touch_signing: "never".to_string(),
|
||||
touch_encryption: "never".to_string(),
|
||||
},
|
||||
attestation: Default::default(),
|
||||
attestation: attestation.clone(),
|
||||
app: Default::default(),
|
||||
backup: Default::default(),
|
||||
};
|
||||
@@ -292,7 +413,22 @@ fn cmd_verify(hwid_path: PathBuf) {
|
||||
|
||||
println!("Verifying hardware identity {}...", config.identity.hash);
|
||||
|
||||
let session = match rns_ratkey::session::PivSession::connect() {
|
||||
let expected_ed = match config.ed25519_pub_bytes() {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
eprintln!("Error: .hwid has invalid Ed25519 key: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let expected_x = match config.x25519_pub_bytes() {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
eprintln!("Error: .hwid has invalid X25519 key: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut session = match rns_ratkey::PcscPivSession::connect() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("Error: cannot connect to hardware token: {e}");
|
||||
@@ -300,20 +436,42 @@ fn cmd_verify(hwid_path: PathBuf) {
|
||||
}
|
||||
};
|
||||
|
||||
let metadata = match session.read_metadata(rns_ratkey::apdu::SLOT_AUTHENTICATION) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
eprintln!("Error reading slot 9A: {e}");
|
||||
std::process::exit(1);
|
||||
// Reads the slot public keys from GET METADATA and compares against the .hwid.
|
||||
// This is the on-device confirmation of the metadata parser before it gates
|
||||
// HardwareIdentity construction.
|
||||
let mut ok = true;
|
||||
match session.read_public_key(rns_ratkey::apdu::SLOT_AUTHENTICATION) {
|
||||
Ok(dev_ed) if dev_ed == expected_ed => println!(" Slot 9A (Ed25519): MATCH"),
|
||||
Ok(_) => {
|
||||
println!(" Slot 9A (Ed25519): MISMATCH");
|
||||
ok = false;
|
||||
}
|
||||
};
|
||||
Err(e) => {
|
||||
println!(" Slot 9A (Ed25519): error reading key: {e}");
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
match session.read_public_key(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT) {
|
||||
Ok(dev_x) if dev_x == expected_x => println!(" Slot 9D (X25519): MATCH"),
|
||||
Ok(_) => {
|
||||
println!(" Slot 9D (X25519): MISMATCH");
|
||||
ok = false;
|
||||
}
|
||||
Err(e) => {
|
||||
println!(" Slot 9D (X25519): error reading key: {e}");
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
|
||||
println!(" Slot 9A metadata: {} bytes", metadata.len());
|
||||
println!(" Verification requires comparing public keys from device with .hwid file.");
|
||||
println!(" (Full verification implemented when hardware is available for testing)");
|
||||
if ok {
|
||||
println!("\nVerified: connected token matches this .hwid.");
|
||||
} else {
|
||||
println!("\nVerification FAILED: token does not match this .hwid.");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_test(hwid_path: PathBuf) {
|
||||
fn cmd_test(hwid_path: PathBuf, pin: Option<String>) {
|
||||
let config = match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
@@ -322,9 +480,18 @@ fn cmd_test(hwid_path: PathBuf) {
|
||||
}
|
||||
};
|
||||
|
||||
let pin = match pin {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
eprintln!("Error: --pin is required (PIN-once keys need one verification per session)");
|
||||
eprintln!("Usage: rnid-rs hw test <hwid> --pin <PIN>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
println!("Testing hardware identity {}...\n", config.identity.hash);
|
||||
|
||||
let session = match rns_ratkey::session::PivSession::connect() {
|
||||
let mut session = match rns_ratkey::PcscPivSession::connect() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("Error: cannot connect to hardware token: {e}");
|
||||
@@ -332,6 +499,12 @@ fn cmd_test(hwid_path: PathBuf) {
|
||||
}
|
||||
};
|
||||
|
||||
// PIN_POLICY_ONCE: a fresh session must verify the PIN before any private-key op.
|
||||
if let Err(e) = session.verify_pin(&pin) {
|
||||
eprintln!("PIN verification failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
println!("1. Testing Ed25519 signing in slot 9A...");
|
||||
let test_msg = b"RATKEY hardware identity test message";
|
||||
match session.sign_ed25519(rns_ratkey::apdu::SLOT_AUTHENTICATION, test_msg) {
|
||||
@@ -373,5 +546,33 @@ fn cmd_test(hwid_path: PathBuf) {
|
||||
}
|
||||
}
|
||||
|
||||
println!("3. Testing HardwareIdentity decrypt (on-device ECDH + HKDF + AES) end-to-end...");
|
||||
let mut hw = match rns_ratkey::HardwareIdentity::from_hwid(config.clone(), Box::new(session)) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
println!(" FAIL: cannot build HardwareIdentity: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let plaintext = b"RATKEY end-to-end decrypt test";
|
||||
let ciphertext = match hw.as_identity().encrypt(plaintext, None) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
println!(" FAIL: encrypt to hardware identity failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
match hw.decrypt(&ciphertext, None, false) {
|
||||
Ok(pt) if pt == plaintext => println!(" PASS: round-trip decrypt via on-device ECDH"),
|
||||
Ok(_) => {
|
||||
println!(" FAIL: decrypted plaintext mismatch");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Err(e) => {
|
||||
println!(" FAIL: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
println!("\nAll tests passed.");
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! rnid-rs - identity create/inspect/sign/verify/encrypt/decrypt.
|
||||
//!
|
||||
//! Python reference: `RNS/Utilities/rnid.py` from Reticulum 1.2.4.
|
||||
//! Python reference: `RNS/Utilities/rnid.py` from Reticulum 1.2.5.
|
||||
|
||||
mod rsg;
|
||||
|
||||
@@ -26,7 +26,7 @@ use rns_transport::messages::{
|
||||
#[cfg(feature = "hardware")]
|
||||
mod hw_commands;
|
||||
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.4";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
const DEFAULT_ASPECTS: &str = "rns.id";
|
||||
const PUB_EXT: &str = "pub";
|
||||
const SIG_EXT: &str = "rsg";
|
||||
@@ -159,6 +159,10 @@ struct Args {
|
||||
#[arg(short = 'B', long)]
|
||||
base32: bool,
|
||||
|
||||
/// Use hex-encoded input and output.
|
||||
#[arg(long)]
|
||||
hex: bool,
|
||||
|
||||
/// Print version and exit.
|
||||
#[arg(long)]
|
||||
version: bool,
|
||||
@@ -183,6 +187,9 @@ enum HwCommands {
|
||||
nickname: Option<String>,
|
||||
#[arg(short, long)]
|
||||
output: Option<PathBuf>,
|
||||
/// PIV management key (hex). Defaults to the factory key.
|
||||
#[arg(long)]
|
||||
mgmt_key: Option<String>,
|
||||
},
|
||||
List {
|
||||
#[arg(short, long)]
|
||||
@@ -196,7 +203,12 @@ enum HwCommands {
|
||||
},
|
||||
Test {
|
||||
hwid: PathBuf,
|
||||
#[arg(long)]
|
||||
pin: Option<String>,
|
||||
},
|
||||
/// Fetch the on-card attestation (slots 9A/9D + device F9) and verify the
|
||||
/// certificate chain to a bundled Yubico root. No PIN required.
|
||||
Attest,
|
||||
}
|
||||
|
||||
#[cfg(feature = "hardware")]
|
||||
@@ -226,7 +238,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
|
||||
async fn run(mut args: Args) -> ExitCode {
|
||||
if args.version {
|
||||
println!("rnid-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnid-rs {RS_RETICULUM_VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -271,8 +283,12 @@ async fn run(mut args: Args) -> ExitCode {
|
||||
eprintln!("The -i, -g, -m and -M args are mutually exclusive");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
if args.base64 && args.base32 {
|
||||
eprintln!("The -b and -B args are mutually exclusive");
|
||||
let encoding_count = [args.base64, args.base32, args.hex]
|
||||
.into_iter()
|
||||
.filter(|flag| *flag)
|
||||
.count();
|
||||
if encoding_count > 1 {
|
||||
eprintln!("The -b, -B and --hex args are mutually exclusive");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
|
||||
@@ -858,19 +874,6 @@ fn sign_file(identity: &Identity, args: &Args) -> ExitCode {
|
||||
return ExitCode::from(6);
|
||||
}
|
||||
};
|
||||
let Some(output_path) = args
|
||||
.write
|
||||
.clone()
|
||||
.or_else(|| Some(append_extension(input_path, SIG_EXT)))
|
||||
else {
|
||||
eprintln!("Signing requested, but no output specified");
|
||||
return ExitCode::from(253);
|
||||
};
|
||||
if let Err(e) = ensure_output_allowed(&output_path, args.force) {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(11);
|
||||
}
|
||||
|
||||
let signature = if args.raw {
|
||||
match rsg::create_raw_signature(identity, input) {
|
||||
Ok(signature) => signature.to_vec(),
|
||||
@@ -888,6 +891,37 @@ fn sign_file(identity: &Identity, args: &Args) -> ExitCode {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if !args.raw && (args.base64 || args.base32 || args.hex) {
|
||||
let encoded = if args.base64 {
|
||||
URL_SAFE.encode(&signature)
|
||||
} else if args.base32 {
|
||||
encode_base32(&signature)
|
||||
} else {
|
||||
hex::encode(&signature)
|
||||
};
|
||||
println!("\n{}\n", wrap_rsg(encoded.as_bytes()));
|
||||
println!(
|
||||
"Signed file {} with {}",
|
||||
input_path.display(),
|
||||
pretty_hash(&identity.hash)
|
||||
);
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
let Some(output_path) = args
|
||||
.write
|
||||
.clone()
|
||||
.or_else(|| Some(append_extension(input_path, SIG_EXT)))
|
||||
else {
|
||||
eprintln!("Signing requested, but no output specified");
|
||||
return ExitCode::from(253);
|
||||
};
|
||||
if let Err(e) = ensure_output_allowed(&output_path, args.force) {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(11);
|
||||
}
|
||||
|
||||
if let Err(e) = write_output(&output_path, &signature, args.stdout) {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(253);
|
||||
@@ -1301,6 +1335,36 @@ fn encode_key_text(bytes: &[u8], args: &Args) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn wrap_rsg(rsg: &[u8]) -> String {
|
||||
const HEADER: &[u8] = b"#### Start of rsg data ";
|
||||
const FOOTER: &[u8] = b" End of rsg data ####";
|
||||
const ROW_WIDTH: usize = 64;
|
||||
|
||||
let mut header = String::from_utf8_lossy(HEADER).into_owned();
|
||||
while header.len() < ROW_WIDTH {
|
||||
header.push('#');
|
||||
}
|
||||
|
||||
let mut footer = String::new();
|
||||
while footer.len() + FOOTER.len() < ROW_WIDTH {
|
||||
footer.push('#');
|
||||
}
|
||||
footer.push_str(&String::from_utf8_lossy(FOOTER));
|
||||
|
||||
let mut wrapped = String::new();
|
||||
wrapped.push_str(&header);
|
||||
wrapped.push('\n');
|
||||
for chunk in rsg.chunks(ROW_WIDTH) {
|
||||
wrapped.push_str(&String::from_utf8_lossy(chunk));
|
||||
for _ in chunk.len()..ROW_WIDTH {
|
||||
wrapped.push('=');
|
||||
}
|
||||
wrapped.push('\n');
|
||||
}
|
||||
wrapped.push_str(&footer);
|
||||
wrapped
|
||||
}
|
||||
|
||||
fn encode_base32(bytes: &[u8]) -> String {
|
||||
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
let mut out = String::new();
|
||||
|
||||
@@ -291,7 +291,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn message() -> &'static [u8] {
|
||||
b"Reticulum 1.2.4 rsg test payload"
|
||||
b"Reticulum 1.2.5 rsg test payload"
|
||||
}
|
||||
|
||||
fn pack_value(value: Value) -> Vec<u8> {
|
||||
|
||||
@@ -13,6 +13,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use clap::{CommandFactory, Parser};
|
||||
use rns_interface::{kiss, rnode, rnode_admin};
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
// rnodeconf support is staged: safe inspection/config modules are compiled now,
|
||||
// while hardware-gated flashing/signing paths are wired in behind explicit CLI flows.
|
||||
@@ -32,8 +33,6 @@ mod model;
|
||||
#[path = "rnodeconf/trust.rs"]
|
||||
mod trust;
|
||||
|
||||
const RNODECONF_VERSION: &str = "2.5.0";
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
name = "rnodeconf-rs",
|
||||
@@ -166,7 +165,7 @@ struct Args {
|
||||
pub(crate) fn main() -> ExitCode {
|
||||
let args = Args::parse();
|
||||
if args.version {
|
||||
println!("rnodeconf-rs {RNODECONF_VERSION}");
|
||||
println!("rnodeconf-rs {RS_RETICULUM_VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if let Some(trust_key) = args.trust_key.as_deref() {
|
||||
|
||||
@@ -27,7 +27,7 @@ const REMOTE_TIMEOUT_SECS: u64 = 30;
|
||||
const REMOTE_HOPS: u8 = 8;
|
||||
const MGMT_APP: &str = "rnstransport.remote.management";
|
||||
const BLACKHOLE_APP: &str = "rnstransport.info.blackhole";
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -130,7 +130,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
let args = Args::parse();
|
||||
|
||||
if args.version {
|
||||
println!("rnpath-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnpath-rs {RS_RETICULUM_VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -270,12 +270,20 @@ struct ClientCtx {
|
||||
}
|
||||
|
||||
async fn request(ctx: &ClientCtx, req: &RpcRequest) -> Result<RpcResponse, LocalRpcFailure> {
|
||||
request_with_timeout(ctx, req, ctx.timeout).await
|
||||
}
|
||||
|
||||
async fn request_with_timeout(
|
||||
ctx: &ClientCtx,
|
||||
req: &RpcRequest,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<RpcResponse, LocalRpcFailure> {
|
||||
let result = match &ctx.endpoint {
|
||||
SharedInstanceRpcEndpoint::Tcp(port) => {
|
||||
rpc::connect_and_request(*port, &ctx.rpc_key, req, ctx.timeout).await
|
||||
rpc::connect_and_request(*port, &ctx.rpc_key, req, timeout).await
|
||||
}
|
||||
SharedInstanceRpcEndpoint::Unix(socket_path) => {
|
||||
rpc::connect_unix_and_request(socket_path, &ctx.rpc_key, req, ctx.timeout).await
|
||||
rpc::connect_unix_and_request(socket_path, &ctx.rpc_key, req, timeout).await
|
||||
}
|
||||
};
|
||||
result.map_err(|source| LocalRpcFailure {
|
||||
@@ -754,13 +762,73 @@ async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode {
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
|
||||
let mut path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
|
||||
Ok(RpcResponse::PathTable(entries)) => entries
|
||||
.into_iter()
|
||||
.find(|entry| entry.hash.as_slice() == dest),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut next_hop = next_hop;
|
||||
let mut iface = iface;
|
||||
if next_hop.is_none() && path_entry.is_none() {
|
||||
let timeout_secs = ctx.timeout.as_secs_f64().max(0.1);
|
||||
let req = RpcRequest::RequestPath {
|
||||
destination_hash: dest.to_vec(),
|
||||
timeout_secs: Some(timeout_secs),
|
||||
};
|
||||
let rpc_timeout = ctx.timeout + std::time::Duration::from_secs(1);
|
||||
let found = match request_with_timeout(ctx, &req, rpc_timeout).await {
|
||||
Ok(RpcResponse::BoolResult(found)) => found,
|
||||
Ok(other) => {
|
||||
eprintln!("rnpath-rs: unexpected response: {other:?}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("rnpath-rs: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
|
||||
if found {
|
||||
next_hop = match request(
|
||||
ctx,
|
||||
&RpcRequest::GetNextHop {
|
||||
destination_hash: dest.to_vec(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(RpcResponse::HashResult(h)) => h,
|
||||
Ok(other) => {
|
||||
eprintln!("rnpath-rs: unexpected response: {other:?}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("rnpath-rs: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
iface = match request(
|
||||
ctx,
|
||||
&RpcRequest::GetNextHopIfName {
|
||||
destination_hash: dest.to_vec(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(RpcResponse::StringResult(s)) => s,
|
||||
_ => None,
|
||||
};
|
||||
path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
|
||||
Ok(RpcResponse::PathTable(entries)) => entries
|
||||
.into_iter()
|
||||
.find(|entry| entry.hash.as_slice() == dest),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
println!("Destination: {}", hex::encode(dest));
|
||||
match next_hop.as_ref() {
|
||||
Some(h) => println!(" Next hop : {}", hex::encode(h)),
|
||||
@@ -775,9 +843,7 @@ async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode {
|
||||
}
|
||||
|
||||
if next_hop.is_none() && path_entry.is_none() {
|
||||
println!(
|
||||
" Note : no cached local path was found; active path requests are not implemented in rnpath yet"
|
||||
);
|
||||
println!(" Note : path request timed out or no path was found");
|
||||
ExitCode::from(1)
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
|
||||
@@ -13,7 +13,7 @@ use rns_runtime::probe::{
|
||||
|
||||
const DEFAULT_PROBE_SIZE: usize = 16;
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -65,7 +65,7 @@ struct Args {
|
||||
pub(crate) async fn main() {
|
||||
let args = Args::parse();
|
||||
if args.version {
|
||||
println!("rnprobe-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnprobe-rs {RS_RETICULUM_VERSION}");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
|
||||
use clap::Parser;
|
||||
use tracing_subscriber::fmt::MakeWriter;
|
||||
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
|
||||
use rns_tools::{RETICULUM_COMPAT_VERSION, RS_RETICULUM_VERSION};
|
||||
const LOG_ROTATE_BYTES: u64 = 5 * 1024 * 1024;
|
||||
const RNSD_EXAMPLE_CONFIG: &str = r#"# This is an example Reticulum config file.
|
||||
|
||||
@@ -134,7 +134,7 @@ pub(crate) async fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
if args.version {
|
||||
println!("rnsd-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnsd-rs {RS_RETICULUM_VERSION}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -170,13 +170,14 @@ pub(crate) async fn main() {
|
||||
}
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(level)
|
||||
.with_writer(LogFileWriter { path: log_path })
|
||||
.with_writer(LogFileWriter::new(log_path))
|
||||
.with_ansi(false)
|
||||
.init();
|
||||
} else {
|
||||
tracing_subscriber::fmt().with_max_level(level).init();
|
||||
}
|
||||
|
||||
tracing::info!("rnsd-rs {RETICULUM_COMPAT_VERSION} starting");
|
||||
tracing::info!("rnsd-rs {RS_RETICULUM_VERSION} starting");
|
||||
|
||||
let shutdown = rns_runtime::lifecycle::ShutdownSignal::new();
|
||||
let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone());
|
||||
@@ -214,7 +215,7 @@ async fn run_interactive_shell(handle: rns_runtime::reticulum::ReticulumHandle)
|
||||
let mut stdout = io::stdout();
|
||||
let _ = writeln!(
|
||||
stdout,
|
||||
"rnsd-rs {RETICULUM_COMPAT_VERSION} interactive console"
|
||||
"rnsd-rs {RS_RETICULUM_VERSION} interactive console"
|
||||
);
|
||||
let _ = writeln!(
|
||||
stdout,
|
||||
@@ -387,23 +388,50 @@ fn rotate_log_if_needed(path: &Path) -> std::io::Result<()> {
|
||||
|
||||
#[derive(Clone)]
|
||||
struct LogFileWriter {
|
||||
path: PathBuf,
|
||||
/// One persistent file handle + in-memory size counter shared across
|
||||
/// `make_writer` calls — tracing calls it per event, so per-event opens
|
||||
/// and per-write stats would dominate logging cost.
|
||||
shared: std::sync::Arc<std::sync::Mutex<RotatingLogFile>>,
|
||||
}
|
||||
|
||||
impl LogFileWriter {
|
||||
fn new(path: PathBuf) -> Self {
|
||||
Self {
|
||||
shared: std::sync::Arc::new(std::sync::Mutex::new(RotatingLogFile {
|
||||
path,
|
||||
file: None,
|
||||
size: 0,
|
||||
})),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> MakeWriter<'a> for LogFileWriter {
|
||||
type Writer = Box<dyn Write + Send + 'a>;
|
||||
type Writer = SharedLogWriter;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
match OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&self.path)
|
||||
{
|
||||
Ok(file) => Box::new(RotatingLogFile {
|
||||
path: self.path.clone(),
|
||||
file: Some(file),
|
||||
}),
|
||||
Err(_) => Box::new(std::io::stderr()),
|
||||
SharedLogWriter(self.shared.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-event writer handle; locks the shared rotating file for each write
|
||||
/// and falls back to stderr if the logfile cannot be opened.
|
||||
struct SharedLogWriter(std::sync::Arc<std::sync::Mutex<RotatingLogFile>>);
|
||||
|
||||
impl Write for SharedLogWriter {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let mut inner = self.0.lock().expect("log writer mutex poisoned");
|
||||
match inner.write(buf) {
|
||||
Ok(n) => Ok(n),
|
||||
Err(_) => std::io::stderr().write(buf),
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
let mut inner = self.0.lock().expect("log writer mutex poisoned");
|
||||
match inner.flush() {
|
||||
Ok(()) => Ok(()),
|
||||
Err(_) => std::io::stderr().flush(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,23 +439,25 @@ impl<'a> MakeWriter<'a> for LogFileWriter {
|
||||
struct RotatingLogFile {
|
||||
path: PathBuf,
|
||||
file: Option<File>,
|
||||
/// Current logfile size, maintained in memory; stat only happens at open.
|
||||
size: u64,
|
||||
}
|
||||
|
||||
impl RotatingLogFile {
|
||||
fn file_mut(&mut self) -> io::Result<&mut File> {
|
||||
if self.file.is_none() {
|
||||
self.file = Some(
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&self.path)?,
|
||||
);
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&self.path)?;
|
||||
self.size = file.metadata().map(|m| m.len()).unwrap_or(0);
|
||||
self.file = Some(file);
|
||||
}
|
||||
Ok(self.file.as_mut().expect("log file was just opened"))
|
||||
}
|
||||
|
||||
fn rotate_if_needed(&mut self) -> io::Result<()> {
|
||||
if self.path.metadata().map(|m| m.len()).unwrap_or(0) <= LOG_ROTATE_BYTES {
|
||||
if self.size <= LOG_ROTATE_BYTES {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -449,6 +479,7 @@ impl RotatingLogFile {
|
||||
.append(true)
|
||||
.open(&self.path)?,
|
||||
);
|
||||
self.size = 0;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -456,6 +487,7 @@ impl RotatingLogFile {
|
||||
impl Write for RotatingLogFile {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let written = self.file_mut()?.write(buf)?;
|
||||
self.size += written as u64;
|
||||
self.rotate_if_needed()?;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
@@ -19,11 +19,12 @@ use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers};
|
||||
use rns_runtime::platform::{StoragePaths, resolve_config_dir};
|
||||
use rns_runtime::rnsh::{
|
||||
RnshClientConfig, RnshError, RnshListenerConfig, RnshWindowSize, rnsh_client_execute,
|
||||
run_rnsh_listener,
|
||||
run_rnsh_listener_with_shutdown,
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
const RNS_VERSION: &str = "1.2.2";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
const RNSH_PROTOCOL_VERSION: &str = "0.2.0";
|
||||
const APP_NAME: &str = "rnsh";
|
||||
const DEFAULT_SERVICE_NAME: &str = "default";
|
||||
@@ -86,7 +87,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
|
||||
async fn run(mut args: Args) -> ExitCode {
|
||||
if args.version {
|
||||
println!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})");
|
||||
println!("rnsh-rs {RS_RETICULUM_VERSION} (protocol {RNSH_PROTOCOL_VERSION})");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -120,9 +121,12 @@ async fn run(mut args: Args) -> ExitCode {
|
||||
}
|
||||
|
||||
async fn run_listener(args: Args) -> ExitCode {
|
||||
// Register before any slow init so an early SIGINT exits cleanly.
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
init_logging(args.verbose, args.quiet);
|
||||
|
||||
let handle = match start_reticulum(args.config.as_deref()).await {
|
||||
let handle = match start_reticulum(args.config.as_deref(), shutdown.clone()).await {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
eprintln!("rnsh-rs: failed to start reticulum: {e}");
|
||||
@@ -160,7 +164,9 @@ async fn run_listener(args: Args) -> ExitCode {
|
||||
announce_period: args.announce,
|
||||
};
|
||||
|
||||
match run_rnsh_listener(handle.transport_tx.clone(), cfg).await {
|
||||
match run_rnsh_listener_with_shutdown(handle.transport_tx.clone(), cfg, handle.shutdown.clone())
|
||||
.await
|
||||
{
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("rnsh-rs: {e}");
|
||||
@@ -170,6 +176,9 @@ async fn run_listener(args: Args) -> ExitCode {
|
||||
}
|
||||
|
||||
async fn run_initiator(args: Args) -> ExitCode {
|
||||
// Register before any slow init so an early SIGINT exits cleanly.
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
init_logging(args.verbose, args.quiet);
|
||||
|
||||
let destination = match args.destination.as_deref().and_then(parse_hash16) {
|
||||
@@ -180,7 +189,7 @@ async fn run_initiator(args: Args) -> ExitCode {
|
||||
}
|
||||
};
|
||||
|
||||
let handle = match start_reticulum(args.config.as_deref()).await {
|
||||
let handle = match start_reticulum(args.config.as_deref(), shutdown.clone()).await {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
eprintln!("rnsh-rs: failed to start reticulum: {e}");
|
||||
@@ -251,9 +260,8 @@ async fn run_initiator(args: Args) -> ExitCode {
|
||||
|
||||
async fn start_reticulum(
|
||||
config_dir: Option<&Path>,
|
||||
shutdown: ShutdownSignal,
|
||||
) -> Result<rns_runtime::reticulum::ReticulumHandle, rns_runtime::reticulum::ReticulumError> {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
let is_foreground = Arc::new(AtomicBool::new(true));
|
||||
let config = config_dir.and_then(|path| path.to_str());
|
||||
rns_runtime::reticulum::init(config, None, shutdown, is_foreground).await
|
||||
@@ -871,8 +879,8 @@ mod tests {
|
||||
#[test]
|
||||
fn version_string_uses_rust_command_name() {
|
||||
assert_eq!(
|
||||
format!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
|
||||
"rnsh-rs 1.2.2 (protocol 0.2.0)"
|
||||
format!("rnsh-rs {RS_RETICULUM_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
|
||||
format!("rnsh-rs {} (protocol 0.2.0)", env!("CARGO_PKG_VERSION"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const DEFAULT_TIMEOUT_SECS: u64 = 5;
|
||||
const REMOTE_TIMEOUT_SECS: u64 = 30;
|
||||
const REMOTE_HOPS: u8 = 8;
|
||||
const MGMT_APP: &str = "rnstransport.remote.management";
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.4";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -44,15 +44,23 @@ struct Args {
|
||||
#[arg(short = 'A', long)]
|
||||
announce_stats: bool,
|
||||
|
||||
/// Show path request frequency stats.
|
||||
#[arg(short = 'P', long = "pr-stats")]
|
||||
pr_stats: bool,
|
||||
|
||||
/// Show link table entry count.
|
||||
#[arg(short, long)]
|
||||
link_stats: bool,
|
||||
|
||||
/// Only show interfaces with active announce or path request bursts.
|
||||
#[arg(short = 'B', long)]
|
||||
burst: bool,
|
||||
|
||||
/// Display traffic totals.
|
||||
#[arg(short, long)]
|
||||
totals: bool,
|
||||
|
||||
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held.
|
||||
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held.
|
||||
#[arg(short, long)]
|
||||
sort: Option<String>,
|
||||
|
||||
@@ -117,7 +125,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
let args = Args::parse();
|
||||
|
||||
if args.version {
|
||||
println!("rnstatus-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnstatus-rs {RS_RETICULUM_VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if let Err(e) = validate_args(&args) {
|
||||
@@ -200,6 +208,10 @@ async fn run_local_once(args: &Args) -> ExitCode {
|
||||
match local_rpc_request(&endpoint, &rpc_key, &RpcRequest::GetInterfaceStats, timeout).await
|
||||
{
|
||||
Ok(RpcResponse::InterfaceStats(v)) => v,
|
||||
Ok(RpcResponse::Error(e)) => {
|
||||
eprintln!("rnstatus-rs: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
Ok(other) => {
|
||||
eprintln!("rnstatus-rs: unexpected response: {other:?}");
|
||||
return ExitCode::from(1);
|
||||
@@ -323,6 +335,8 @@ enum SortKey {
|
||||
Announces,
|
||||
AnnounceRx,
|
||||
AnnounceTx,
|
||||
PathRequestRx,
|
||||
PathRequestTx,
|
||||
Held,
|
||||
}
|
||||
|
||||
@@ -353,10 +367,12 @@ fn parse_sort_key(value: Option<&str>) -> Result<Option<SortKey>, String> {
|
||||
"announces" | "announce" => SortKey::Announces,
|
||||
"arx" => SortKey::AnnounceRx,
|
||||
"atx" => SortKey::AnnounceTx,
|
||||
"prx" => SortKey::PathRequestRx,
|
||||
"ptx" => SortKey::PathRequestTx,
|
||||
"held" => SortKey::Held,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held; got {value}"
|
||||
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held; got {value}"
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -374,6 +390,8 @@ fn local_stat_sort_value(e: &rpc::InterfaceStatEntry, key: SortKey) -> f64 {
|
||||
SortKey::Announces => e.incoming_announce_frequency + e.outgoing_announce_frequency,
|
||||
SortKey::AnnounceRx => e.incoming_announce_frequency,
|
||||
SortKey::AnnounceTx => e.outgoing_announce_frequency,
|
||||
SortKey::PathRequestRx => e.incoming_pr_frequency,
|
||||
SortKey::PathRequestTx => e.outgoing_pr_frequency,
|
||||
SortKey::Held => e.held_announces as f64,
|
||||
}
|
||||
}
|
||||
@@ -394,6 +412,24 @@ fn interface_matches_filter(name: &str, filter: Option<&str>) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn interface_matches_burst_filter(
|
||||
name: &str,
|
||||
burst_active: bool,
|
||||
pr_burst_active: bool,
|
||||
args: &Args,
|
||||
) -> bool {
|
||||
if !args.burst {
|
||||
return interface_matches_filter(name, args.filter.as_deref());
|
||||
}
|
||||
|
||||
burst_active
|
||||
|| pr_burst_active
|
||||
|| args.filter.as_deref().is_some_and(|filter| {
|
||||
name.to_ascii_lowercase()
|
||||
.contains(&filter.to_ascii_lowercase())
|
||||
})
|
||||
}
|
||||
|
||||
fn filtered_local_stats<'a>(
|
||||
stats: &'a [rpc::InterfaceStatEntry],
|
||||
args: &Args,
|
||||
@@ -401,7 +437,14 @@ fn filtered_local_stats<'a>(
|
||||
let mut entries: Vec<_> = stats
|
||||
.iter()
|
||||
.filter(|entry| args.all || visible_by_default(&entry.name))
|
||||
.filter(|entry| interface_matches_filter(&entry.name, args.filter.as_deref()))
|
||||
.filter(|entry| {
|
||||
interface_matches_burst_filter(
|
||||
&entry.name,
|
||||
entry.burst_active,
|
||||
entry.pr_burst_active,
|
||||
args,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
if let Ok(Some(key)) = parse_sort_key(args.sort.as_deref()) {
|
||||
entries.sort_by(|a, b| {
|
||||
@@ -457,6 +500,7 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
}
|
||||
if entry.incoming_announce_frequency > 0.0
|
||||
|| entry.outgoing_announce_frequency > 0.0
|
||||
|| entry.burst_active
|
||||
{
|
||||
print_announce_frequency(
|
||||
entry.incoming_announce_frequency,
|
||||
@@ -465,9 +509,18 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
entry.announce_rate_target,
|
||||
entry.announce_rate_penalty,
|
||||
entry.announce_rate_grace,
|
||||
burst_status_text(entry.burst_active, entry.burst_activated),
|
||||
);
|
||||
}
|
||||
}
|
||||
if args.pr_stats {
|
||||
print_path_request_frequency(
|
||||
entry.incoming_pr_frequency,
|
||||
entry.outgoing_pr_frequency,
|
||||
entry.clients,
|
||||
burst_status_text(entry.pr_burst_active, entry.pr_burst_activated),
|
||||
);
|
||||
}
|
||||
println!(
|
||||
" Traffic : {} rx / {} tx",
|
||||
format::pretty_size(entry.rx_bytes),
|
||||
@@ -514,7 +567,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
print!(",");
|
||||
}
|
||||
print!(
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
|
||||
json_str(&e.name),
|
||||
e.online,
|
||||
json_str(&e.mode),
|
||||
@@ -531,6 +584,12 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
e.held_announces,
|
||||
e.incoming_announce_frequency,
|
||||
e.outgoing_announce_frequency,
|
||||
e.incoming_pr_frequency,
|
||||
e.outgoing_pr_frequency,
|
||||
e.burst_active,
|
||||
e.burst_activated,
|
||||
e.pr_burst_active,
|
||||
e.pr_burst_activated,
|
||||
opt_u64_json(e.clients),
|
||||
opt_f64_json(e.announce_rate_target),
|
||||
opt_u32_json(e.announce_rate_grace),
|
||||
@@ -902,6 +961,12 @@ struct RemoteInterface {
|
||||
held_announces: u64,
|
||||
incoming_announce_frequency: f64,
|
||||
outgoing_announce_frequency: f64,
|
||||
incoming_pr_frequency: f64,
|
||||
outgoing_pr_frequency: f64,
|
||||
burst_active: bool,
|
||||
burst_activated: f64,
|
||||
pr_burst_active: bool,
|
||||
pr_burst_activated: f64,
|
||||
clients: Option<u64>,
|
||||
announce_rate_target: Option<f64>,
|
||||
announce_rate_grace: Option<u32>,
|
||||
@@ -922,6 +987,8 @@ impl RemoteInterface {
|
||||
}
|
||||
SortKey::AnnounceRx => self.incoming_announce_frequency,
|
||||
SortKey::AnnounceTx => self.outgoing_announce_frequency,
|
||||
SortKey::PathRequestRx => self.incoming_pr_frequency,
|
||||
SortKey::PathRequestTx => self.outgoing_pr_frequency,
|
||||
SortKey::Held => self.held_announces as f64,
|
||||
}
|
||||
}
|
||||
@@ -972,7 +1039,14 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
ifs.iter()
|
||||
.filter_map(|iface| iface.as_map().map(|m| remote_interface_from_map(m)))
|
||||
.filter(|iface| args.all || visible_by_default(&iface.name))
|
||||
.filter(|iface| interface_matches_filter(&iface.name, args.filter.as_deref()))
|
||||
.filter(|iface| {
|
||||
interface_matches_burst_filter(
|
||||
&iface.name,
|
||||
iface.burst_active,
|
||||
iface.pr_burst_active,
|
||||
args,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
@@ -994,7 +1068,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
print!(",");
|
||||
}
|
||||
print!(
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
|
||||
json_str(&iface.name),
|
||||
iface.online,
|
||||
iface.mode,
|
||||
@@ -1010,6 +1084,12 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
iface.held_announces,
|
||||
iface.incoming_announce_frequency,
|
||||
iface.outgoing_announce_frequency,
|
||||
iface.incoming_pr_frequency,
|
||||
iface.outgoing_pr_frequency,
|
||||
iface.burst_active,
|
||||
iface.burst_activated,
|
||||
iface.pr_burst_active,
|
||||
iface.pr_burst_activated,
|
||||
opt_u64_json(iface.clients),
|
||||
opt_f64_json(iface.announce_rate_target),
|
||||
opt_u32_json(iface.announce_rate_grace),
|
||||
@@ -1058,6 +1138,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
}
|
||||
if iface.incoming_announce_frequency > 0.0
|
||||
|| iface.outgoing_announce_frequency > 0.0
|
||||
|| iface.burst_active
|
||||
{
|
||||
print_announce_frequency(
|
||||
iface.incoming_announce_frequency,
|
||||
@@ -1066,9 +1147,18 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
iface.announce_rate_target,
|
||||
iface.announce_rate_penalty,
|
||||
iface.announce_rate_grace,
|
||||
burst_status_text(iface.burst_active, iface.burst_activated),
|
||||
);
|
||||
}
|
||||
}
|
||||
if args.pr_stats {
|
||||
print_path_request_frequency(
|
||||
iface.incoming_pr_frequency,
|
||||
iface.outgoing_pr_frequency,
|
||||
iface.clients,
|
||||
burst_status_text(iface.pr_burst_active, iface.pr_burst_activated),
|
||||
);
|
||||
}
|
||||
println!(
|
||||
" Traffic : {} rx / {} tx",
|
||||
format::pretty_size(iface.rxb),
|
||||
@@ -1118,6 +1208,12 @@ fn remote_interface_from_map(m: &[(rmpv::Value, rmpv::Value)]) -> RemoteInterfac
|
||||
.unwrap_or(0.0),
|
||||
outgoing_announce_frequency: map_f64_or_u64(m, "outgoing_announce_frequency")
|
||||
.unwrap_or(0.0),
|
||||
incoming_pr_frequency: map_f64_or_u64(m, "incoming_pr_frequency").unwrap_or(0.0),
|
||||
outgoing_pr_frequency: map_f64_or_u64(m, "outgoing_pr_frequency").unwrap_or(0.0),
|
||||
burst_active: map_bool(m, "burst_active").unwrap_or(false),
|
||||
burst_activated: map_f64_or_u64(m, "burst_activated").unwrap_or(0.0),
|
||||
pr_burst_active: map_bool(m, "pr_burst_active").unwrap_or(false),
|
||||
pr_burst_activated: map_f64_or_u64(m, "pr_burst_activated").unwrap_or(0.0),
|
||||
clients: map_u64(m, "clients"),
|
||||
announce_rate_target: map_f64_or_u64(m, "announce_rate_target"),
|
||||
announce_rate_grace: map_u64(m, "announce_rate_grace")
|
||||
@@ -1157,6 +1253,7 @@ fn print_announce_frequency(
|
||||
target: Option<f64>,
|
||||
penalty: Option<f64>,
|
||||
grace: Option<u32>,
|
||||
burst_text: String,
|
||||
) {
|
||||
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
|
||||
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
|
||||
@@ -1166,7 +1263,38 @@ fn print_announce_frequency(
|
||||
.unwrap_or_default();
|
||||
let limits = announce_rate_limits_text(target, penalty, grace);
|
||||
println!(" Announces: {outgoing_text}{per_client}");
|
||||
println!(" {incoming_text} {limits}");
|
||||
println!(" {incoming_text} {limits}{burst_text}");
|
||||
}
|
||||
|
||||
fn print_path_request_frequency(
|
||||
incoming: f64,
|
||||
outgoing: f64,
|
||||
clients: Option<u64>,
|
||||
burst_text: String,
|
||||
) {
|
||||
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
|
||||
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
|
||||
let per_client = clients
|
||||
.filter(|clients| *clients > 0)
|
||||
.map(|clients| format!(" {}/c", format::pretty_frequency(outgoing / clients as f64)))
|
||||
.unwrap_or_default();
|
||||
println!(" Path Rqs.: {outgoing_text}{per_client}");
|
||||
println!(" {incoming_text} {burst_text}");
|
||||
}
|
||||
|
||||
fn burst_status_text(active: bool, activated: f64) -> String {
|
||||
if !active || activated <= 0.0 {
|
||||
return String::new();
|
||||
}
|
||||
let age = (unix_now() - activated).max(0.0);
|
||||
format!(" burst for {}", format::pretty_time(age))
|
||||
}
|
||||
|
||||
fn unix_now() -> f64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64()
|
||||
}
|
||||
|
||||
fn announce_rate_limits_text(
|
||||
@@ -1246,6 +1374,131 @@ fn json_str(s: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_args() -> Args {
|
||||
Args {
|
||||
all: true,
|
||||
announce_stats: false,
|
||||
pr_stats: false,
|
||||
link_stats: false,
|
||||
burst: false,
|
||||
totals: false,
|
||||
sort: None,
|
||||
reverse: false,
|
||||
json: false,
|
||||
config: None,
|
||||
remote: None,
|
||||
identity: None,
|
||||
timeout: None,
|
||||
discovered: false,
|
||||
discovered_details: false,
|
||||
monitor: false,
|
||||
monitor_interval: 1.0,
|
||||
version: false,
|
||||
verbose: 0,
|
||||
quiet: 0,
|
||||
filter: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn local_entry(
|
||||
name: &str,
|
||||
burst_active: bool,
|
||||
pr_burst_active: bool,
|
||||
) -> rpc::InterfaceStatEntry {
|
||||
rpc::InterfaceStatEntry {
|
||||
id: 1,
|
||||
name: name.to_string(),
|
||||
rx_bytes: 0,
|
||||
tx_bytes: 0,
|
||||
rx_rate: 0,
|
||||
tx_rate: 0,
|
||||
online: true,
|
||||
bitrate: 1,
|
||||
mtu: 500,
|
||||
mode: "Full".to_string(),
|
||||
role: "normal".to_string(),
|
||||
announce_queue: None,
|
||||
held_announces: 0,
|
||||
incoming_announce_frequency: 0.0,
|
||||
outgoing_announce_frequency: 0.0,
|
||||
incoming_pr_frequency: 2.0,
|
||||
outgoing_pr_frequency: 3.0,
|
||||
burst_active,
|
||||
burst_activated: if burst_active { 1_700_000_000.0 } else { 0.0 },
|
||||
pr_burst_active,
|
||||
pr_burst_activated: if pr_burst_active {
|
||||
1_700_000_001.0
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
clients: None,
|
||||
announce_rate_target: None,
|
||||
announce_rate_grace: None,
|
||||
announce_rate_penalty: None,
|
||||
announce_cap: 0.0,
|
||||
ifac_size: 0,
|
||||
tx_drops: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_key_accepts_path_request_rates() {
|
||||
assert_eq!(
|
||||
parse_sort_key(Some("prx")).unwrap(),
|
||||
Some(SortKey::PathRequestRx)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_sort_key(Some("ptx")).unwrap(),
|
||||
Some(SortKey::PathRequestTx)
|
||||
);
|
||||
|
||||
let entry = local_entry("SortIf", false, false);
|
||||
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestRx), 2.0);
|
||||
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestTx), 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pr_and_burst_flags_parse() {
|
||||
let args = Args::try_parse_from(["rnstatus-rs", "-P", "-B"]).unwrap();
|
||||
assert!(args.pr_stats);
|
||||
assert!(args.burst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burst_filter_includes_active_bursts_or_name_matches() {
|
||||
let stats = vec![
|
||||
local_entry("InactiveIf", false, false),
|
||||
local_entry("AnnounceBurstIf", true, false),
|
||||
local_entry("PrBurstIf", false, true),
|
||||
local_entry("ManualMatchIf", false, false),
|
||||
];
|
||||
let mut args = test_args();
|
||||
args.burst = true;
|
||||
args.filter = Some("manual".to_string());
|
||||
|
||||
let names: Vec<_> = filtered_local_stats(&stats, &args)
|
||||
.into_iter()
|
||||
.map(|entry| entry.name.as_str())
|
||||
.collect();
|
||||
|
||||
assert_eq!(names, vec!["AnnounceBurstIf", "PrBurstIf", "ManualMatchIf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_status_parser_defaults_missing_125_fields() {
|
||||
let iface = remote_interface_from_map(&[
|
||||
(rmpv::Value::from("name"), rmpv::Value::from("LegacyIf")),
|
||||
(rmpv::Value::from("status"), rmpv::Value::from(true)),
|
||||
]);
|
||||
|
||||
assert_eq!(iface.incoming_pr_frequency, 0.0);
|
||||
assert_eq!(iface.outgoing_pr_frequency, 0.0);
|
||||
assert!(!iface.burst_active);
|
||||
assert_eq!(iface.burst_activated, 0.0);
|
||||
assert!(!iface.pr_burst_active);
|
||||
assert_eq!(iface.pr_burst_activated, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_rpc_auth_failure_explains_config_mismatch_and_port_owner() {
|
||||
let endpoint = SharedInstanceRpcEndpoint::Tcp(37429);
|
||||
|
||||
@@ -2,3 +2,9 @@
|
||||
|
||||
pub mod format;
|
||||
pub mod hash;
|
||||
|
||||
/// rsReticulum package version printed by CLI `--version` output.
|
||||
pub const RS_RETICULUM_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Python Reticulum version these tools track for CLI/protocol parity.
|
||||
pub const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
|
||||
@@ -0,0 +1,177 @@
|
||||
#[cfg(unix)]
|
||||
use std::fs;
|
||||
#[cfg(unix)]
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(unix)]
|
||||
use std::process::{Child, Command, Stdio};
|
||||
#[cfg(unix)]
|
||||
use std::thread;
|
||||
#[cfg(unix)]
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[cfg(unix)]
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl TempDir {
|
||||
fn new(prefix: &str) -> Self {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("system clock before unix epoch")
|
||||
.as_nanos();
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"rsreticulum-{prefix}-{}-{nonce}",
|
||||
std::process::id()
|
||||
));
|
||||
fs::create_dir_all(&path).expect("create tempdir");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn write_config(tmp: &TempDir) {
|
||||
fs::write(
|
||||
tmp.path().join("config"),
|
||||
"[reticulum]\nshare_instance = No\nenable_transport = No\n\n[interfaces]\n",
|
||||
)
|
||||
.expect("write config");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn wait_until_running(child: &mut Child, settle: Duration) -> bool {
|
||||
let deadline = Instant::now() + settle;
|
||||
while Instant::now() < deadline {
|
||||
if child.try_wait().expect("poll child").is_some() {
|
||||
return false;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Sends SIGINT after a settle period and asserts a clean exit. Retries once
|
||||
/// with a longer settle if the child died from the raw signal (exit by signal
|
||||
/// 2): under full-workspace load the child can still be booting when the
|
||||
/// first SIGINT lands, before its handler is registered. A real handler
|
||||
/// regression fails both attempts.
|
||||
#[cfg(unix)]
|
||||
fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
let settles = [Duration::from_secs(3), Duration::from_secs(8)];
|
||||
let last_attempt = settles.len() - 1;
|
||||
for (attempt, settle) in settles.into_iter().enumerate() {
|
||||
let mut child = spawn();
|
||||
if !wait_until_running(&mut child, settle) {
|
||||
let output = child.wait_with_output().expect("collect child output");
|
||||
panic!(
|
||||
"{name} exited before SIGINT\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
let status = Command::new("kill")
|
||||
.arg("-INT")
|
||||
.arg(child.id().to_string())
|
||||
.status()
|
||||
.expect("send SIGINT");
|
||||
assert!(status.success(), "kill -INT failed with {status}");
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let exit_status = loop {
|
||||
if let Some(status) = child.try_wait().expect("poll child after SIGINT") {
|
||||
break Some(status);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
break None;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
};
|
||||
|
||||
match exit_status {
|
||||
Some(status) if status.success() => return,
|
||||
Some(status) if attempt < last_attempt && status.signal() == Some(2) => {
|
||||
let _ = child.wait_with_output();
|
||||
continue;
|
||||
}
|
||||
Some(status) => {
|
||||
let output = child.wait_with_output().expect("collect child output");
|
||||
panic!(
|
||||
"{name} exited unsuccessfully after SIGINT: {status}\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
None => {
|
||||
let _ = child.kill();
|
||||
let output = child
|
||||
.wait_with_output()
|
||||
.expect("collect killed child output");
|
||||
panic!(
|
||||
"{name} did not exit after SIGINT\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
unreachable!("attempt loop either returns or panics");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rncp_listener_exits_on_sigint() {
|
||||
let tmp = TempDir::new("rncp-sigint");
|
||||
write_config(&tmp);
|
||||
assert_sigint_exits(
|
||||
|| {
|
||||
Command::new(env!("CARGO_BIN_EXE_rncp-rs"))
|
||||
.arg("--config")
|
||||
.arg(tmp.path())
|
||||
.arg("-l")
|
||||
.arg("-n")
|
||||
.arg("-S")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn rncp-rs listener")
|
||||
},
|
||||
"rncp-rs",
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rnsh_listener_exits_on_sigint() {
|
||||
let tmp = TempDir::new("rnsh-sigint");
|
||||
write_config(&tmp);
|
||||
assert_sigint_exits(
|
||||
|| {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnsh-rs"))
|
||||
.arg("--config")
|
||||
.arg(tmp.path())
|
||||
.arg("-l")
|
||||
.arg("-n")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn rnsh-rs listener")
|
||||
},
|
||||
"rnsh-rs",
|
||||
);
|
||||
}
|
||||
@@ -135,7 +135,12 @@ fn rnid_flag_conflicts_are_rejected() {
|
||||
let tmp = TempDir::new("rnid-flag-conflicts");
|
||||
|
||||
let output = rnid(&tmp, ["-b", "-B"]);
|
||||
assert_failure(&output, Some(1), "-b and -B", "base64/base32 conflict");
|
||||
assert_failure(
|
||||
&output,
|
||||
Some(1),
|
||||
"-b, -B and --hex",
|
||||
"base64/base32 conflict",
|
||||
);
|
||||
|
||||
let generated = tmp.join("identity");
|
||||
let output = rnid(
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Output, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rns_identity::destination::Destination;
|
||||
use rns_identity::identity::Identity;
|
||||
|
||||
const PROBE_APP: &str = "rnstransport.probe";
|
||||
const COMMAND_TIMEOUT_SECS: &str = "4";
|
||||
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(prefix: &str) -> Self {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("system clock before unix epoch")
|
||||
.as_nanos();
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"rsreticulum-{prefix}-{}-{nonce}",
|
||||
std::process::id()
|
||||
));
|
||||
fs::create_dir_all(&path).expect("create tempdir");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
|
||||
self.path.join(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
struct ChildGuard {
|
||||
label: &'static str,
|
||||
child: Option<Child>,
|
||||
}
|
||||
|
||||
impl ChildGuard {
|
||||
fn spawn<I, S>(label: &'static str, program: &str, args: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
let child = Command::new(program)
|
||||
.args(args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn child process");
|
||||
Self {
|
||||
label,
|
||||
child: Some(child),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_wait(&mut self) -> Option<std::process::ExitStatus> {
|
||||
self.child
|
||||
.as_mut()
|
||||
.and_then(|child| child.try_wait().expect("poll child status"))
|
||||
}
|
||||
|
||||
fn terminate_and_output_text(&mut self) -> (String, String) {
|
||||
let Some(mut child) = self.child.take() else {
|
||||
return ("<not started>\n".to_string(), String::new());
|
||||
};
|
||||
let _ = child.kill();
|
||||
let output = child.wait_with_output().expect("collect child output");
|
||||
output_text(&output)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(mut child) = self.child.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn free_tcp_ports(count: usize) -> Vec<u16> {
|
||||
let listeners: Vec<TcpListener> = (0..count)
|
||||
.map(|_| TcpListener::bind("127.0.0.1:0").expect("bind free tcp port"))
|
||||
.collect();
|
||||
listeners
|
||||
.iter()
|
||||
.map(|listener| listener.local_addr().expect("local addr").port())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn write_responder_config(tmp: &TempDir, shared_port: u16, control_port: u16, link_port: u16) {
|
||||
let config = format!(
|
||||
"[reticulum]\n\
|
||||
share_instance = Yes\n\
|
||||
shared_instance_type = tcp\n\
|
||||
shared_instance_port = {shared_port}\n\
|
||||
instance_control_port = {control_port}\n\
|
||||
rpc_key = 5151515151515151515151515151515151515151515151515151515151515151\n\
|
||||
enable_transport = No\n\
|
||||
respond_to_probes = Yes\n\
|
||||
\n\
|
||||
[logging]\n\
|
||||
loglevel = 1\n\
|
||||
\n\
|
||||
[interfaces]\n\
|
||||
\n\
|
||||
[[Matrix TCP Server]]\n\
|
||||
type = TCPServerInterface\n\
|
||||
enabled = Yes\n\
|
||||
listen_ip = 127.0.0.1\n\
|
||||
listen_port = {link_port}\n"
|
||||
);
|
||||
fs::write(tmp.join("config"), config).expect("write responder config");
|
||||
}
|
||||
|
||||
fn write_origin_config(tmp: &TempDir, shared_port: u16, control_port: u16, link_port: u16) {
|
||||
let config = format!(
|
||||
"[reticulum]\n\
|
||||
share_instance = Yes\n\
|
||||
shared_instance_type = tcp\n\
|
||||
shared_instance_port = {shared_port}\n\
|
||||
instance_control_port = {control_port}\n\
|
||||
rpc_key = 5252525252525252525252525252525252525252525252525252525252525252\n\
|
||||
enable_transport = No\n\
|
||||
\n\
|
||||
[logging]\n\
|
||||
loglevel = 1\n\
|
||||
\n\
|
||||
[interfaces]\n\
|
||||
\n\
|
||||
[[Matrix TCP Client]]\n\
|
||||
type = TCPClientInterface\n\
|
||||
enabled = Yes\n\
|
||||
target_host = 127.0.0.1\n\
|
||||
target_port = {link_port}\n"
|
||||
);
|
||||
fs::write(tmp.join("config"), config).expect("write origin config");
|
||||
}
|
||||
|
||||
fn output_text(output: &Output) -> (String, String) {
|
||||
(
|
||||
String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
fn rnstatus_json(tmp: &TempDir) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnstatus-rs"))
|
||||
.arg("--config")
|
||||
.arg(tmp.path())
|
||||
.arg("--json")
|
||||
.arg("--all")
|
||||
.arg("--timeout")
|
||||
.arg("1")
|
||||
.output()
|
||||
.expect("run rnstatus-rs")
|
||||
}
|
||||
|
||||
fn poll_shared_server(
|
||||
daemon: &mut ChildGuard,
|
||||
tmp: &TempDir,
|
||||
deadline_after: Duration,
|
||||
) -> Result<(), String> {
|
||||
let deadline = Instant::now() + deadline_after;
|
||||
let mut last_status = None;
|
||||
let mut last_stdout = String::new();
|
||||
let mut last_stderr = String::new();
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = daemon.try_wait() {
|
||||
return Err(format!(
|
||||
"{} exited before shared server was ready: {status}",
|
||||
daemon.label
|
||||
));
|
||||
}
|
||||
|
||||
let output = rnstatus_json(tmp);
|
||||
last_status = output.status.code();
|
||||
(last_stdout, last_stderr) = output_text(&output);
|
||||
if output.status.success() {
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_slice(&output.stdout).expect("rnstatus-rs JSON output");
|
||||
let ready = value
|
||||
.get("interfaces")
|
||||
.and_then(|v| v.as_array())
|
||||
.is_some_and(|interfaces| {
|
||||
interfaces.iter().any(|entry| {
|
||||
entry.get("role").and_then(|v| v.as_str()) == Some("shared_server")
|
||||
})
|
||||
});
|
||||
if ready {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"rnstatus-rs did not report {} shared server before the deadline\n\
|
||||
last rnstatus status: {last_status:?}\n\
|
||||
--- last rnstatus stdout ---\n{last_stdout}\n\
|
||||
--- last rnstatus stderr ---\n{last_stderr}",
|
||||
daemon.label
|
||||
))
|
||||
}
|
||||
|
||||
fn read_probe_hash(responder: &mut ChildGuard, tmp: &TempDir) -> Result<[u8; 16], String> {
|
||||
let path = tmp.join("storage").join("probe_identity");
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut last_error = String::new();
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = responder.try_wait() {
|
||||
return Err(format!(
|
||||
"{} exited before probe identity was ready: {status}",
|
||||
responder.label
|
||||
));
|
||||
}
|
||||
|
||||
match Identity::from_file(&path) {
|
||||
Ok(identity) => {
|
||||
return Ok(Destination::hash_from_name_and_identity(
|
||||
PROBE_APP,
|
||||
Some(&identity.hash),
|
||||
));
|
||||
}
|
||||
Err(e) => last_error = e.to_string(),
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
Err(format!(
|
||||
"probe identity was not readable at {}\nlast error: {last_error}",
|
||||
path.display()
|
||||
))
|
||||
}
|
||||
|
||||
fn run_rnpath(origin: &TempDir, probe_hash_hex: &str) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnpath-rs"))
|
||||
.arg("--config")
|
||||
.arg(origin.path())
|
||||
.arg("-w")
|
||||
.arg(COMMAND_TIMEOUT_SECS)
|
||||
.arg(probe_hash_hex)
|
||||
.output()
|
||||
.expect("run rnpath-rs")
|
||||
}
|
||||
|
||||
fn run_rnprobe(origin: &TempDir, probe_hash_hex: &str) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnprobe-rs"))
|
||||
.arg("--config")
|
||||
.arg(origin.path())
|
||||
.arg("--json")
|
||||
.arg("-t")
|
||||
.arg(COMMAND_TIMEOUT_SECS)
|
||||
.arg(PROBE_APP)
|
||||
.arg(probe_hash_hex)
|
||||
.output()
|
||||
.expect("run rnprobe-rs")
|
||||
}
|
||||
|
||||
fn poll_command_success<F>(
|
||||
label: &str,
|
||||
deadline_after: Duration,
|
||||
mut run: F,
|
||||
) -> Result<Output, String>
|
||||
where
|
||||
F: FnMut() -> Output,
|
||||
{
|
||||
let deadline = Instant::now() + deadline_after;
|
||||
let mut last_output = None;
|
||||
while Instant::now() < deadline {
|
||||
let output = run();
|
||||
if output.status.success() {
|
||||
return Ok(output);
|
||||
}
|
||||
last_output = Some(output);
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
|
||||
let Some(output) = last_output else {
|
||||
return Err(format!("{label} was not run"));
|
||||
};
|
||||
let (stdout, stderr) = output_text(&output);
|
||||
Err(format!(
|
||||
"{label} did not succeed before the deadline\n\
|
||||
last status: {}\n\
|
||||
--- last stdout ---\n{stdout}\n\
|
||||
--- last stderr ---\n{stderr}",
|
||||
output.status
|
||||
))
|
||||
}
|
||||
|
||||
fn panic_with_daemon_outputs(
|
||||
message: String,
|
||||
responder: &mut ChildGuard,
|
||||
path_origin: &mut ChildGuard,
|
||||
cold_origin: &mut ChildGuard,
|
||||
) -> ! {
|
||||
let (responder_stdout, responder_stderr) = responder.terminate_and_output_text();
|
||||
let (path_stdout, path_stderr) = path_origin.terminate_and_output_text();
|
||||
let (cold_stdout, cold_stderr) = cold_origin.terminate_and_output_text();
|
||||
panic!(
|
||||
"{message}\n\
|
||||
--- responder stdout ---\n{responder_stdout}\n\
|
||||
--- responder stderr ---\n{responder_stderr}\n\
|
||||
--- path origin stdout ---\n{path_stdout}\n\
|
||||
--- path origin stderr ---\n{path_stderr}\n\
|
||||
--- cold origin stdout ---\n{cold_stdout}\n\
|
||||
--- cold origin stderr ---\n{cold_stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_probe_destination_supports_active_path_and_probe_matrix() {
|
||||
let responder_tmp = TempDir::new("rnprobe-rnpath-responder");
|
||||
let path_origin_tmp = TempDir::new("rnprobe-rnpath-path-origin");
|
||||
let cold_origin_tmp = TempDir::new("rnprobe-rnpath-cold-origin");
|
||||
let ports = free_tcp_ports(7);
|
||||
let link_port = ports[0];
|
||||
|
||||
write_responder_config(&responder_tmp, ports[1], ports[2], link_port);
|
||||
write_origin_config(&path_origin_tmp, ports[3], ports[4], link_port);
|
||||
write_origin_config(&cold_origin_tmp, ports[5], ports[6], link_port);
|
||||
|
||||
let mut responder = ChildGuard::spawn(
|
||||
"responder rnsd-rs",
|
||||
env!("CARGO_BIN_EXE_rnsd-rs"),
|
||||
["--config".as_ref(), responder_tmp.path().as_os_str()],
|
||||
);
|
||||
if let Err(message) = poll_shared_server(&mut responder, &responder_tmp, Duration::from_secs(5))
|
||||
{
|
||||
let mut placeholder = ChildGuard {
|
||||
label: "path origin rnsd-rs",
|
||||
child: None,
|
||||
};
|
||||
let mut cold_placeholder = ChildGuard {
|
||||
label: "cold origin rnsd-rs",
|
||||
child: None,
|
||||
};
|
||||
panic_with_daemon_outputs(
|
||||
message,
|
||||
&mut responder,
|
||||
&mut placeholder,
|
||||
&mut cold_placeholder,
|
||||
);
|
||||
}
|
||||
|
||||
let probe_hash = match read_probe_hash(&mut responder, &responder_tmp) {
|
||||
Ok(hash) => hash,
|
||||
Err(message) => {
|
||||
let mut placeholder = ChildGuard {
|
||||
label: "path origin rnsd-rs",
|
||||
child: None,
|
||||
};
|
||||
let mut cold_placeholder = ChildGuard {
|
||||
label: "cold origin rnsd-rs",
|
||||
child: None,
|
||||
};
|
||||
panic_with_daemon_outputs(
|
||||
message,
|
||||
&mut responder,
|
||||
&mut placeholder,
|
||||
&mut cold_placeholder,
|
||||
);
|
||||
}
|
||||
};
|
||||
let probe_hash_hex = hex::encode(probe_hash);
|
||||
|
||||
let mut path_origin = ChildGuard::spawn(
|
||||
"path origin rnsd-rs",
|
||||
env!("CARGO_BIN_EXE_rnsd-rs"),
|
||||
["--config".as_ref(), path_origin_tmp.path().as_os_str()],
|
||||
);
|
||||
if let Err(message) =
|
||||
poll_shared_server(&mut path_origin, &path_origin_tmp, Duration::from_secs(5))
|
||||
{
|
||||
let mut cold_placeholder = ChildGuard {
|
||||
label: "cold origin rnsd-rs",
|
||||
child: None,
|
||||
};
|
||||
panic_with_daemon_outputs(
|
||||
message,
|
||||
&mut responder,
|
||||
&mut path_origin,
|
||||
&mut cold_placeholder,
|
||||
);
|
||||
}
|
||||
|
||||
let mut cold_origin = ChildGuard::spawn(
|
||||
"cold origin rnsd-rs",
|
||||
env!("CARGO_BIN_EXE_rnsd-rs"),
|
||||
["--config".as_ref(), cold_origin_tmp.path().as_os_str()],
|
||||
);
|
||||
if let Err(message) =
|
||||
poll_shared_server(&mut cold_origin, &cold_origin_tmp, Duration::from_secs(5))
|
||||
{
|
||||
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin);
|
||||
}
|
||||
|
||||
let rnpath = poll_command_success(
|
||||
"rnpath-rs active path request",
|
||||
Duration::from_secs(16),
|
||||
|| run_rnpath(&path_origin_tmp, &probe_hash_hex),
|
||||
);
|
||||
let rnpath = match rnpath {
|
||||
Ok(output) => output,
|
||||
Err(message) => {
|
||||
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
|
||||
}
|
||||
};
|
||||
let (rnpath_stdout, _rnpath_stderr) = output_text(&rnpath);
|
||||
assert!(
|
||||
rnpath_stdout.contains(&format!("Destination: {probe_hash_hex}")),
|
||||
"rnpath-rs output did not include the requested destination\n{rnpath_stdout}"
|
||||
);
|
||||
assert!(
|
||||
!rnpath_stdout.contains("(no known path)"),
|
||||
"rnpath-rs reported no known path after active request\n{rnpath_stdout}"
|
||||
);
|
||||
|
||||
let known_path_probe = poll_command_success(
|
||||
"rnprobe-rs with rnpath-populated path",
|
||||
Duration::from_secs(16),
|
||||
|| run_rnprobe(&path_origin_tmp, &probe_hash_hex),
|
||||
);
|
||||
let known_path_probe = match known_path_probe {
|
||||
Ok(output) => output,
|
||||
Err(message) => {
|
||||
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
|
||||
}
|
||||
};
|
||||
assert_probe_json_ok(&known_path_probe, &probe_hash_hex);
|
||||
|
||||
let cold_probe = poll_command_success(
|
||||
"rnprobe-rs cold active-path probe",
|
||||
Duration::from_secs(16),
|
||||
|| run_rnprobe(&cold_origin_tmp, &probe_hash_hex),
|
||||
);
|
||||
let cold_probe = match cold_probe {
|
||||
Ok(output) => output,
|
||||
Err(message) => {
|
||||
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
|
||||
}
|
||||
};
|
||||
assert_probe_json_ok(&cold_probe, &probe_hash_hex);
|
||||
}
|
||||
|
||||
fn assert_probe_json_ok(output: &Output, expected_hash: &str) {
|
||||
let (stdout, stderr) = output_text(output);
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(stdout.trim()).expect("rnprobe-rs JSON output");
|
||||
assert_eq!(
|
||||
value.get("status").and_then(|v| v.as_str()),
|
||||
Some("ok"),
|
||||
"rnprobe-rs did not report ok\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("destination").and_then(|v| v.as_str()),
|
||||
Some(expected_hash),
|
||||
"rnprobe-rs returned the wrong destination\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
||||
);
|
||||
assert!(
|
||||
value.get("rtt_ms").and_then(|v| v.as_f64()).is_some(),
|
||||
"rnprobe-rs JSON did not include an RTT\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Output, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(prefix: &str) -> Self {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("system clock before unix epoch")
|
||||
.as_nanos();
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"rsreticulum-{prefix}-{}-{nonce}",
|
||||
std::process::id()
|
||||
));
|
||||
fs::create_dir_all(&path).expect("create tempdir");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
|
||||
self.path.join(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
struct ChildGuard {
|
||||
child: Option<Child>,
|
||||
}
|
||||
|
||||
impl ChildGuard {
|
||||
fn spawn<I, S>(program: &str, args: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
let child = Command::new(program)
|
||||
.args(args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn child process");
|
||||
Self { child: Some(child) }
|
||||
}
|
||||
|
||||
fn try_wait(&mut self) -> Option<std::process::ExitStatus> {
|
||||
self.child
|
||||
.as_mut()
|
||||
.and_then(|child| child.try_wait().expect("poll child status"))
|
||||
}
|
||||
|
||||
fn terminate_and_output(mut self) -> Output {
|
||||
let mut child = self.child.take().expect("child already taken");
|
||||
let _ = child.kill();
|
||||
child.wait_with_output().expect("collect child output")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(mut child) = self.child.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn free_tcp_port_pair() -> (u16, u16) {
|
||||
let first = TcpListener::bind("127.0.0.1:0").expect("bind first free tcp port");
|
||||
let second = TcpListener::bind("127.0.0.1:0").expect("bind second free tcp port");
|
||||
let first_port = first.local_addr().expect("first local addr").port();
|
||||
let second_port = second.local_addr().expect("second local addr").port();
|
||||
(first_port, second_port)
|
||||
}
|
||||
|
||||
fn write_stale_python_destination_table(storage_dir: &Path, entries: usize) {
|
||||
fs::create_dir_all(storage_dir).expect("create storage dir");
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("system clock before unix epoch")
|
||||
.as_secs_f64();
|
||||
let mut table = rns_transport::path_table::PathTable::new();
|
||||
for i in 0..entries {
|
||||
let mut dest = [0u8; 16];
|
||||
dest[..8].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
dest[8..].copy_from_slice(&(!i as u64).to_be_bytes());
|
||||
|
||||
let mut packet_hash = [0u8; 32];
|
||||
packet_hash[..8].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
packet_hash[8..16].copy_from_slice(&(entries as u64).to_be_bytes());
|
||||
packet_hash[16..24].copy_from_slice(&(0xA5A5_A5A5_A5A5_A5A5u64).to_be_bytes());
|
||||
packet_hash[24..].copy_from_slice(&(!i as u64).to_be_bytes());
|
||||
|
||||
let mut entry = rns_transport::path_table::PathEntry::new(
|
||||
None,
|
||||
1,
|
||||
7,
|
||||
rns_transport::constants::InterfaceMode::Gateway,
|
||||
);
|
||||
entry.timestamp = now;
|
||||
entry.expires = now + 3600.0;
|
||||
entry.packet_hash = Some(packet_hash);
|
||||
table.insert(dest, entry);
|
||||
}
|
||||
|
||||
let mut names = std::collections::HashMap::new();
|
||||
names.insert(7u64, "Border_TCP".to_string());
|
||||
rns_transport::persistence::save_python_destination_table(
|
||||
&table,
|
||||
&names,
|
||||
&storage_dir.join("destination_table"),
|
||||
)
|
||||
.expect("write Python destination_table");
|
||||
}
|
||||
|
||||
fn output_text(output: &Output) -> (String, String) {
|
||||
(
|
||||
String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
fn rnstatus_json(tmp: &TempDir, timeout_secs: &str) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnstatus-rs"))
|
||||
.arg("--config")
|
||||
.arg(tmp.path())
|
||||
.arg("--json")
|
||||
.arg("--all")
|
||||
.arg("--timeout")
|
||||
.arg(timeout_secs)
|
||||
.output()
|
||||
.expect("run rnstatus-rs")
|
||||
}
|
||||
|
||||
fn poll_rnstatus_until<F>(
|
||||
daemon: &mut ChildGuard,
|
||||
tmp: &TempDir,
|
||||
deadline_after: Duration,
|
||||
timeout_secs: &str,
|
||||
predicate: F,
|
||||
) -> Result<(), String>
|
||||
where
|
||||
F: Fn(&[serde_json::Value]) -> bool,
|
||||
{
|
||||
let deadline = Instant::now() + deadline_after;
|
||||
let mut last_status = None;
|
||||
let mut last_stdout = String::new();
|
||||
let mut last_stderr = String::new();
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = daemon.try_wait() {
|
||||
return Err(format!(
|
||||
"rnsd-rs exited before rnstatus-rs succeeded: {status}"
|
||||
));
|
||||
}
|
||||
|
||||
let output = rnstatus_json(tmp, timeout_secs);
|
||||
last_status = output.status.code();
|
||||
(last_stdout, last_stderr) = output_text(&output);
|
||||
|
||||
if output.status.success() {
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_slice(&output.stdout).expect("rnstatus-rs JSON output");
|
||||
let interfaces = value
|
||||
.get("interfaces")
|
||||
.and_then(|v| v.as_array())
|
||||
.expect("interfaces array");
|
||||
if predicate(interfaces) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"rnstatus-rs did not report the expected interface before the deadline\n\
|
||||
last rnstatus status: {last_status:?}\n\
|
||||
--- last rnstatus stdout ---\n{last_stdout}\n\
|
||||
--- last rnstatus stderr ---\n{last_stderr}"
|
||||
))
|
||||
}
|
||||
|
||||
fn panic_with_daemon_output(message: String, daemon: ChildGuard) -> ! {
|
||||
let daemon_output = daemon.terminate_and_output();
|
||||
let (daemon_stdout, daemon_stderr) = output_text(&daemon_output);
|
||||
panic!(
|
||||
"{message}\n\
|
||||
--- daemon stdout ---\n{daemon_stdout}\n\
|
||||
--- daemon stderr ---\n{daemon_stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rnsd_rnstatus_cli_survives_stale_python_destination_table() {
|
||||
let tmp = TempDir::new("rnsd-rnstatus-stale-python-table");
|
||||
let (shared_port, control_port) = free_tcp_port_pair();
|
||||
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
|
||||
let config = format!(
|
||||
"[reticulum]\n\
|
||||
share_instance = Yes\n\
|
||||
shared_instance_type = tcp\n\
|
||||
shared_instance_port = {shared_port}\n\
|
||||
instance_control_port = {control_port}\n\
|
||||
rpc_key = {rpc_key_hex}\n\
|
||||
enable_transport = Yes\n\
|
||||
\n\
|
||||
[logging]\n\
|
||||
loglevel = 1\n\
|
||||
\n\
|
||||
[interfaces]\n"
|
||||
);
|
||||
fs::write(tmp.join("config"), config).expect("write config");
|
||||
write_stale_python_destination_table(&tmp.join("storage"), 512);
|
||||
|
||||
let mut daemon = ChildGuard::spawn(
|
||||
env!("CARGO_BIN_EXE_rnsd-rs"),
|
||||
["--config".as_ref(), tmp.path().as_os_str()],
|
||||
);
|
||||
|
||||
if let Err(message) = poll_rnstatus_until(
|
||||
&mut daemon,
|
||||
&tmp,
|
||||
Duration::from_secs(5),
|
||||
"1",
|
||||
|interfaces| {
|
||||
interfaces
|
||||
.iter()
|
||||
.any(|entry| entry.get("role").and_then(|v| v.as_str()) == Some("shared_server"))
|
||||
},
|
||||
) {
|
||||
panic_with_daemon_output(message, daemon);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires network access to a public Reticulum TCP peer"]
|
||||
fn rnsd_rnstatus_cli_public_tcp_testnet_smoke() {
|
||||
let tmp = TempDir::new("rnsd-rnstatus-public-tcp-testnet");
|
||||
let (shared_port, control_port) = free_tcp_port_pair();
|
||||
let host = std::env::var("RSRETICULUM_LIVE_TCP_HOST")
|
||||
.unwrap_or_else(|_| "rns.ratspeak.org".to_string());
|
||||
let port = std::env::var("RSRETICULUM_LIVE_TCP_PORT")
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<u16>().ok())
|
||||
.unwrap_or(4242);
|
||||
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
|
||||
let config = format!(
|
||||
"[reticulum]\n\
|
||||
share_instance = Yes\n\
|
||||
shared_instance_type = tcp\n\
|
||||
shared_instance_port = {shared_port}\n\
|
||||
instance_control_port = {control_port}\n\
|
||||
rpc_key = {rpc_key_hex}\n\
|
||||
enable_transport = No\n\
|
||||
\n\
|
||||
[logging]\n\
|
||||
loglevel = 1\n\
|
||||
\n\
|
||||
[interfaces]\n\
|
||||
\n\
|
||||
[[Public TCP]]\n\
|
||||
type = TCPClientInterface\n\
|
||||
enabled = Yes\n\
|
||||
target_host = {host}\n\
|
||||
target_port = {port}\n"
|
||||
);
|
||||
fs::write(tmp.join("config"), config).expect("write config");
|
||||
|
||||
let mut daemon = ChildGuard::spawn(
|
||||
env!("CARGO_BIN_EXE_rnsd-rs"),
|
||||
["--config".as_ref(), tmp.path().as_os_str()],
|
||||
);
|
||||
|
||||
if let Err(message) = poll_rnstatus_until(
|
||||
&mut daemon,
|
||||
&tmp,
|
||||
Duration::from_secs(10),
|
||||
"2",
|
||||
|interfaces| {
|
||||
interfaces.iter().any(|entry| {
|
||||
entry.get("name").and_then(|v| v.as_str()) == Some("Public TCP")
|
||||
&& entry.get("online").and_then(|v| v.as_bool()) == Some(true)
|
||||
})
|
||||
},
|
||||
) {
|
||||
panic_with_daemon_output(
|
||||
format!("{message}\nexpected Public TCP to come online for {host}:{port}"),
|
||||
daemon,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn installed_tools_report_rsreticulum_package_version() {
|
||||
let expected = env!("CARGO_PKG_VERSION");
|
||||
let tools = [
|
||||
("rnsd-rs", env!("CARGO_BIN_EXE_rnsd-rs")),
|
||||
("rnstatus-rs", env!("CARGO_BIN_EXE_rnstatus-rs")),
|
||||
("rnpath-rs", env!("CARGO_BIN_EXE_rnpath-rs")),
|
||||
("rnid-rs", env!("CARGO_BIN_EXE_rnid-rs")),
|
||||
("rnprobe-rs", env!("CARGO_BIN_EXE_rnprobe-rs")),
|
||||
("rncp-rs", env!("CARGO_BIN_EXE_rncp-rs")),
|
||||
("rnodeconf-rs", env!("CARGO_BIN_EXE_rnodeconf-rs")),
|
||||
("rnsh-rs", env!("CARGO_BIN_EXE_rnsh-rs")),
|
||||
];
|
||||
|
||||
for (name, program) in tools {
|
||||
let output = Command::new(program)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.unwrap_or_else(|err| panic!("failed to run {name} --version: {err}"));
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{name} --version failed with status {}\n--- stdout ---\n{}\n--- stderr ---\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
stdout.starts_with(&format!("{name} {expected}")),
|
||||
"{name} --version did not report package version {expected:?}\n--- stdout ---\n{stdout}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::now_f64;
|
||||
|
||||
impl TransportActor {
|
||||
#[tracing::instrument(
|
||||
@@ -34,7 +35,7 @@ impl TransportActor {
|
||||
packet.raw.clone()
|
||||
};
|
||||
|
||||
let (parsed, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
|
||||
let (mut parsed, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
|
||||
Ok((header, offset)) => (header, offset),
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
@@ -89,6 +90,8 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
parsed.hops = self.adjusted_inbound_hops(parsed.hops, packet.interface_id);
|
||||
|
||||
tracing::debug!(
|
||||
pkt_type = ?parsed.flags.packet_type,
|
||||
dest = %hex::encode(parsed.destination_hash),
|
||||
@@ -133,13 +136,73 @@ impl TransportActor {
|
||||
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 (announce_data, validated_identity) = {
|
||||
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"
|
||||
);
|
||||
match announce_data.verify_signature(&header.destination_hash) {
|
||||
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;
|
||||
}
|
||||
(announce_data, validated_identity)
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Python validates the announce signature before ingress accounting,
|
||||
// and only holds still-unknown destinations. Known re-announces and
|
||||
// path responses for paths we already know must continue refreshing
|
||||
// route state during an ingress burst.
|
||||
let announced_destination_known = self.path_table.get(&header.destination_hash).is_some();
|
||||
let answers_path_request = self.path_requests.contains_key(&header.destination_hash)
|
||||
|| self
|
||||
.discovery_path_requests
|
||||
@@ -147,6 +210,7 @@ impl TransportActor {
|
||||
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
|
||||
entry.ingress.received_announce();
|
||||
if !is_from_local_client
|
||||
&& !announced_destination_known
|
||||
&& !answers_path_request
|
||||
&& entry.ingress.should_ingress_limit()
|
||||
{
|
||||
@@ -165,6 +229,36 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
let known_public_key = self
|
||||
.recent_announces
|
||||
.get(&header.destination_hash)
|
||||
.and_then(|entry| entry.public_key);
|
||||
if let Err(e) = announce_data.validate_destination_binding(
|
||||
&header.destination_hash,
|
||||
&validated_identity,
|
||||
known_public_key.as_ref(),
|
||||
) {
|
||||
tracing::warn!(
|
||||
dest = hex::encode(header.destination_hash),
|
||||
error = %e,
|
||||
"announce validation failed, dropping"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::debug!(
|
||||
dest = hex::encode(header.destination_hash),
|
||||
app_data_present = announce_data.app_data.is_some(),
|
||||
"announce validated"
|
||||
);
|
||||
|
||||
let announce_app_data = announce_data.app_data.clone();
|
||||
let announce_public_key = Some(validated_identity.get_public_key());
|
||||
let announce_ratchet = announce_data.ratchet;
|
||||
let announce_name_hash = announce_data.name_hash;
|
||||
let announce_identity_hash = Some(validated_identity.hash);
|
||||
let announce_random_hash = announce_data.random_hash;
|
||||
|
||||
let mut rate_blocked = false;
|
||||
|
||||
// Per-interface rate limiting is opt-in and suppresses rebroadcast
|
||||
@@ -206,95 +300,6 @@ impl TransportActor {
|
||||
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)
|
||||
@@ -342,7 +347,11 @@ impl TransportActor {
|
||||
.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 suppressed =
|
||||
self.is_path_interface_suppressed(header.destination_hash, interface_id, now_f64());
|
||||
let should_add = if suppressed {
|
||||
false
|
||||
} else 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 {
|
||||
@@ -369,10 +378,12 @@ impl TransportActor {
|
||||
&& 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 rebroadcast_raw = self.transport_announce_from_raw(
|
||||
raw,
|
||||
header.destination_hash,
|
||||
header.hops,
|
||||
rns_wire::context::PacketContext::None,
|
||||
);
|
||||
let announce_entry = crate::announce::AnnounceEntry {
|
||||
timestamp: now,
|
||||
retransmit_timeout: if is_from_local_client {
|
||||
@@ -380,7 +391,11 @@ impl TransportActor {
|
||||
} else {
|
||||
now + rand_window()
|
||||
},
|
||||
retries: 0,
|
||||
retries: if is_from_local_client {
|
||||
PATHFINDER_R
|
||||
} else {
|
||||
0
|
||||
},
|
||||
received_from: header.transport_id.unwrap_or(header.destination_hash),
|
||||
hops: header.hops,
|
||||
packet_raw: rebroadcast_raw,
|
||||
@@ -411,8 +426,23 @@ impl TransportActor {
|
||||
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));
|
||||
let announce_packet_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
entry.packet_hash = Some(announce_packet_hash);
|
||||
let tunnel_path = crate::tunnel::TunnelPath {
|
||||
timestamp: entry.timestamp,
|
||||
next_hop: entry.next_hop,
|
||||
hops: entry.hops,
|
||||
expires: entry.expires,
|
||||
random_blobs: entry.random_blobs.iter().copied().collect(),
|
||||
packet_hash: entry.packet_hash,
|
||||
};
|
||||
self.path_table.insert(header.destination_hash, entry);
|
||||
if let Some(tunnel) = self.tunnel_table.get_mut_by_interface(interface_id) {
|
||||
tunnel
|
||||
.tunnel_paths
|
||||
.insert(header.destination_hash, tunnel_path);
|
||||
tunnel.expires = now_f64() + TUNNEL_TIMEOUT as f64;
|
||||
}
|
||||
self.state_dirty = true;
|
||||
// Wake any callers waiting on a path for this destination.
|
||||
self.fire_path_waiters(&header.destination_hash);
|
||||
@@ -441,15 +471,22 @@ impl TransportActor {
|
||||
dest = hex::encode(header.destination_hash),
|
||||
hops = header.hops,
|
||||
announce_emitted,
|
||||
interface_id,
|
||||
suppressed,
|
||||
"ignoring replayed or stale announce"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Diagnostics + identity cache (metadata only — raw bytes go to the
|
||||
// disk announce cache below, Python `Transport.cache` parity).
|
||||
// `retained` pins survive re-announce so a fresh announce never
|
||||
// silently un-pins an RPC-retained destination. Swept by
|
||||
// `cleanup_known_destinations` (linger + 7-day eviction).
|
||||
let now_ts = now_f64();
|
||||
let raw_vec = raw.to_vec();
|
||||
let announce_packet_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
let is_path_response = header.context == rns_wire::context::PacketContext::PathResponse;
|
||||
self.cache_announce_to_disk(&announce_packet_hash, raw, interface_id);
|
||||
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) => {
|
||||
@@ -459,7 +496,8 @@ impl TransportActor {
|
||||
e.timestamp = now_ts;
|
||||
e.public_key = announce_public_key;
|
||||
e.ratchet = announce_ratchet;
|
||||
e.raw_packet = raw_vec;
|
||||
e.packet_hash = Some(announce_packet_hash);
|
||||
e.is_path_response = is_path_response;
|
||||
e.name_hash = announce_name_hash;
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(v) => {
|
||||
@@ -470,8 +508,10 @@ impl TransportActor {
|
||||
timestamp: now_ts,
|
||||
public_key: announce_public_key,
|
||||
ratchet: announce_ratchet,
|
||||
raw_packet: raw_vec,
|
||||
packet_hash: Some(announce_packet_hash),
|
||||
is_path_response,
|
||||
retained: false,
|
||||
last_used: None,
|
||||
name_hash: announce_name_hash,
|
||||
});
|
||||
self.state_dirty = true;
|
||||
@@ -568,7 +608,7 @@ impl TransportActor {
|
||||
let from_local_client = self.is_local_client_interface(interface_id);
|
||||
let for_local_client = self
|
||||
.path_table
|
||||
.get(&header.destination_hash)
|
||||
.get_live(&header.destination_hash)
|
||||
.is_some_and(|path| self.is_local_client_interface(path.interface_id));
|
||||
|
||||
let path_request_dest = Self::path_request_dest_hash();
|
||||
@@ -589,15 +629,6 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
@@ -669,28 +700,6 @@ impl TransportActor {
|
||||
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;
|
||||
@@ -717,20 +726,29 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.is_transport_enabled || from_local_client || for_local_client {
|
||||
if 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"
|
||||
);
|
||||
if let Some((target_interface, forwarded)) = self.transport_forward_candidate(
|
||||
raw,
|
||||
header,
|
||||
interface_id,
|
||||
from_local_client,
|
||||
for_local_client,
|
||||
) {
|
||||
let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type);
|
||||
self.reverse_table.insert_with_outbound(
|
||||
pkt_hash,
|
||||
interface_id,
|
||||
header.hops,
|
||||
Some(target_interface),
|
||||
);
|
||||
self.send_to_interface(target_interface, &forwarded);
|
||||
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
|
||||
path.touch();
|
||||
}
|
||||
trace!(
|
||||
dest = hex::encode(header.destination_hash),
|
||||
via_interface = target_interface,
|
||||
"data packet forwarded"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -743,16 +761,20 @@ impl TransportActor {
|
||||
let from_local_client = self.is_local_client_interface(interface_id);
|
||||
let for_local_client = self
|
||||
.path_table
|
||||
.get(&header.destination_hash)
|
||||
.get_live(&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);
|
||||
}
|
||||
let link_request_for_this_instance = header.transport_id.is_none()
|
||||
|| header
|
||||
.transport_id
|
||||
.zip(self.transport_identity_hash)
|
||||
.is_some_and(|(packet_transport_id, our_transport_id)| {
|
||||
packet_transport_id == our_transport_id
|
||||
});
|
||||
|
||||
if self.local_destinations.contains(&header.destination_hash) {
|
||||
if self.local_destinations.contains(&header.destination_hash)
|
||||
&& link_request_for_this_instance
|
||||
{
|
||||
if let Some(tx) = self.destination_channels.get(&header.destination_hash) {
|
||||
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::LinkRequest {
|
||||
raw: raw.clone(),
|
||||
@@ -766,18 +788,22 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(path) = (self.is_transport_enabled || from_local_client || for_local_client)
|
||||
.then(|| self.path_table.get(&header.destination_hash))
|
||||
.flatten()
|
||||
{
|
||||
let target_interface = path.interface_id;
|
||||
if let Some((target_interface, forwarded)) = self.transport_forward_candidate(
|
||||
raw,
|
||||
header,
|
||||
interface_id,
|
||||
from_local_client,
|
||||
for_local_client,
|
||||
) {
|
||||
let Some(path) = self.path_table.get_live(&header.destination_hash) else {
|
||||
return;
|
||||
};
|
||||
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);
|
||||
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
|
||||
path.touch();
|
||||
}
|
||||
|
||||
// Cache the relay so the matching LRPROOF can be routed back to
|
||||
// the initiator without a fresh path lookup. Proof timeout scales
|
||||
@@ -824,6 +850,92 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
fn transport_forward_candidate(
|
||||
&self,
|
||||
raw: &[u8],
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
interface_id: InterfaceId,
|
||||
from_local_client: bool,
|
||||
for_local_client: bool,
|
||||
) -> Option<(InterfaceId, Vec<u8>)> {
|
||||
let path = self.path_table.get_live(&header.destination_hash)?;
|
||||
if path.interface_id == interface_id && !for_local_client {
|
||||
return None;
|
||||
}
|
||||
|
||||
let may_forward_for_shared_client = from_local_client || for_local_client;
|
||||
let addressed_to_us = header
|
||||
.transport_id
|
||||
.zip(self.transport_identity_hash)
|
||||
.is_some_and(|(packet_transport_id, our_transport_id)| {
|
||||
packet_transport_id == our_transport_id
|
||||
});
|
||||
|
||||
// Upstream Transport only relays in-transport packets when the Header2
|
||||
// transport id names this instance. Shared-instance local-client edges
|
||||
// are the exception: they are allowed to use the local path cache even
|
||||
// when packets arrive without normal transport wrapping.
|
||||
if may_forward_for_shared_client && header.transport_id.is_some() && !addressed_to_us {
|
||||
return None;
|
||||
}
|
||||
|
||||
if !may_forward_for_shared_client && (!self.is_transport_enabled || !addressed_to_us) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let forwarded = self.rewrite_forwarded_transport_packet(raw, header, path)?;
|
||||
Some((path.interface_id, forwarded))
|
||||
}
|
||||
|
||||
fn rewrite_forwarded_transport_packet(
|
||||
&self,
|
||||
raw: &[u8],
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
path: &crate::path_table::PathEntry,
|
||||
) -> Option<Vec<u8>> {
|
||||
let payload_offset = header.size();
|
||||
if raw.len() < payload_offset {
|
||||
return None;
|
||||
}
|
||||
|
||||
if path.hops > 1 {
|
||||
let next_hop = path.next_hop?;
|
||||
let mut flags = header.flags;
|
||||
flags.header_type = rns_wire::flags::HeaderType::Header2;
|
||||
flags.transport_type = rns_wire::flags::TransportType::Transport;
|
||||
let new_header = rns_wire::header::PacketHeader {
|
||||
flags,
|
||||
hops: header.hops,
|
||||
transport_id: Some(next_hop),
|
||||
destination_hash: header.destination_hash,
|
||||
context: header.context,
|
||||
};
|
||||
let mut forwarded = new_header.pack();
|
||||
forwarded.extend_from_slice(&raw[payload_offset..]);
|
||||
Some(forwarded)
|
||||
} else if path.hops == 1 {
|
||||
let mut flags = header.flags;
|
||||
flags.header_type = rns_wire::flags::HeaderType::Header1;
|
||||
flags.transport_type = rns_wire::flags::TransportType::Broadcast;
|
||||
let new_header = rns_wire::header::PacketHeader {
|
||||
flags,
|
||||
hops: header.hops,
|
||||
transport_id: None,
|
||||
destination_hash: header.destination_hash,
|
||||
context: header.context,
|
||||
};
|
||||
let mut forwarded = new_header.pack();
|
||||
forwarded.extend_from_slice(&raw[payload_offset..]);
|
||||
Some(forwarded)
|
||||
} else {
|
||||
let mut forwarded = raw.to_vec();
|
||||
if forwarded.len() >= 2 {
|
||||
forwarded[1] = header.hops;
|
||||
}
|
||||
Some(forwarded)
|
||||
}
|
||||
}
|
||||
|
||||
fn process_proof(
|
||||
&mut self,
|
||||
raw: &bytes::Bytes,
|
||||
@@ -843,7 +955,9 @@ impl TransportActor {
|
||||
.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) {
|
||||
if header.context != rns_wire::context::PacketContext::Lrproof
|
||||
&& let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash)
|
||||
{
|
||||
let rtt = receipt
|
||||
.get_rtt()
|
||||
.or_else(|| Some(receipt.sent_at.elapsed()));
|
||||
@@ -878,38 +992,49 @@ impl TransportActor {
|
||||
// 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.
|
||||
// Proofs start at hops=0 at the destination. We normalise inbound
|
||||
// hops before dispatch, matching Python Transport's increment-on-
|
||||
// receive rule, so the proof must equal the remaining hops recorded
|
||||
// when the request was forwarded.
|
||||
if header.context == rns_wire::context::PacketContext::Lrproof {
|
||||
if self.is_transport_enabled || from_local_client || for_local_client_link {
|
||||
if 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;
|
||||
let destination_hash = link_entry.destination_hash;
|
||||
|
||||
// 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
|
||||
};
|
||||
let hops_match = header.hops == expected_hops;
|
||||
if hops_match && _interface_id == outbound_interface {
|
||||
if !self.validate_transit_lrproof(raw, header, link_entry) {
|
||||
return;
|
||||
}
|
||||
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
if !self.packet_hashlist.insert(pkt_hash) {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
"duplicate LRPROOF dropped after link-table claim"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let mut forwarded = raw.to_vec();
|
||||
if forwarded.len() >= 2 {
|
||||
forwarded[1] = header.hops.saturating_add(1);
|
||||
forwarded[1] = header.hops;
|
||||
}
|
||||
if let Some(entry) = self.link_table.get_mut(&header.destination_hash) {
|
||||
entry.validated = true;
|
||||
}
|
||||
self.send_to_interface(target_interface, &forwarded);
|
||||
if !self.is_shared_instance {
|
||||
self.use_destination(&destination_hash);
|
||||
}
|
||||
debug!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
via_interface = target_interface,
|
||||
hops = header.hops + 1,
|
||||
hops = header.hops,
|
||||
"link proof (LRPROOF) routed via link table"
|
||||
);
|
||||
return;
|
||||
@@ -918,7 +1043,7 @@ impl TransportActor {
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
expected_hops,
|
||||
actual_hops = header.hops,
|
||||
"link proof hop mismatch, not transporting (expected hops+1 == remaining_hops)"
|
||||
"link proof hop mismatch, not transporting"
|
||||
);
|
||||
} else {
|
||||
warn!(
|
||||
@@ -934,13 +1059,18 @@ impl TransportActor {
|
||||
// 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) {
|
||||
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id: _interface_id,
|
||||
}) {
|
||||
let delivered =
|
||||
tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id: _interface_id,
|
||||
});
|
||||
if let Err(e) = delivered {
|
||||
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)");
|
||||
} else {
|
||||
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
self.packet_hashlist.insert(pkt_hash);
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -966,7 +1096,11 @@ impl TransportActor {
|
||||
);
|
||||
} else {
|
||||
let target_interface = reverse_entry.receiving_interface;
|
||||
self.send_to_interface(target_interface, raw);
|
||||
let mut forwarded = raw.to_vec();
|
||||
if forwarded.len() >= 2 {
|
||||
forwarded[1] = header.hops;
|
||||
}
|
||||
self.send_to_interface(target_interface, &forwarded);
|
||||
trace!(
|
||||
dest = hex::encode(header.destination_hash),
|
||||
via_interface = target_interface,
|
||||
@@ -976,7 +1110,11 @@ impl TransportActor {
|
||||
}
|
||||
} else {
|
||||
let target_interface = reverse_entry.receiving_interface;
|
||||
self.send_to_interface(target_interface, raw);
|
||||
let mut forwarded = raw.to_vec();
|
||||
if forwarded.len() >= 2 {
|
||||
forwarded[1] = header.hops;
|
||||
}
|
||||
self.send_to_interface(target_interface, &forwarded);
|
||||
trace!(
|
||||
dest = hex::encode(header.destination_hash),
|
||||
via_interface = target_interface,
|
||||
@@ -1023,10 +1161,43 @@ impl TransportActor {
|
||||
return false;
|
||||
}
|
||||
|
||||
let target_interface = if interface_id == entry.receiving_interface {
|
||||
entry.interface_id
|
||||
let target_interface = if entry.interface_id == entry.receiving_interface {
|
||||
if header.hops == entry.remaining_hops || header.hops == entry.taken_hops {
|
||||
entry.interface_id
|
||||
} else {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
actual_hops = header.hops,
|
||||
remaining_hops = entry.remaining_hops,
|
||||
taken_hops = entry.taken_hops,
|
||||
"link packet hop mismatch, not transporting"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} else if interface_id == entry.receiving_interface {
|
||||
if header.hops == entry.taken_hops {
|
||||
entry.interface_id
|
||||
} else {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
actual_hops = header.hops,
|
||||
expected_hops = entry.taken_hops,
|
||||
"link packet initiator-side hop mismatch, not transporting"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} else if interface_id == entry.interface_id {
|
||||
entry.receiving_interface
|
||||
if header.hops == entry.remaining_hops {
|
||||
entry.receiving_interface
|
||||
} else {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
actual_hops = header.hops,
|
||||
expected_hops = entry.remaining_hops,
|
||||
"link packet destination-side hop mismatch, not transporting"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
warn!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
@@ -1040,7 +1211,26 @@ impl TransportActor {
|
||||
|
||||
let mut forwarded = raw.to_vec();
|
||||
if forwarded.len() >= 2 {
|
||||
forwarded[1] = header.hops.saturating_add(1);
|
||||
forwarded[1] = header.hops;
|
||||
}
|
||||
let skip_hashlist = matches!(
|
||||
header.context,
|
||||
rns_wire::context::PacketContext::Keepalive
|
||||
| rns_wire::context::PacketContext::Resource
|
||||
| rns_wire::context::PacketContext::ResourceReq
|
||||
| rns_wire::context::PacketContext::ResourcePrf
|
||||
| rns_wire::context::PacketContext::CacheRequest
|
||||
| rns_wire::context::PacketContext::Channel
|
||||
);
|
||||
if !skip_hashlist {
|
||||
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
if !self.packet_hashlist.insert(pkt_hash) {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
packet_kind, "duplicate link-table packet dropped after claim"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(entry) = self.link_table.get_mut(&header.destination_hash) {
|
||||
entry.timestamp = now_f64();
|
||||
@@ -1049,10 +1239,92 @@ impl TransportActor {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
via_interface = target_interface,
|
||||
hops = header.hops.saturating_add(1),
|
||||
hops = header.hops,
|
||||
packet_kind,
|
||||
"link packet routed via link table"
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
fn validate_transit_lrproof(
|
||||
&self,
|
||||
raw: &[u8],
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
link_entry: &crate::link_table::LinkEntry,
|
||||
) -> bool {
|
||||
let payload_offset = header.size();
|
||||
if raw.len() < payload_offset {
|
||||
warn!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
raw_len = raw.len(),
|
||||
"link proof missing payload, not transporting"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
let proof_data = &raw[payload_offset..];
|
||||
if proof_data.len() != 96 && proof_data.len() != 99 {
|
||||
warn!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
proof_len = proof_data.len(),
|
||||
"malformed link request proof length, not transporting"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut signature = [0u8; 64];
|
||||
signature.copy_from_slice(&proof_data[..64]);
|
||||
let responder_x25519_pub = &proof_data[64..96];
|
||||
let signalling = if proof_data.len() == 99 {
|
||||
&proof_data[96..99]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
|
||||
let Some(destination_public_key) = self
|
||||
.recent_announces
|
||||
.get(&link_entry.destination_hash)
|
||||
.and_then(|announce| announce.public_key)
|
||||
else {
|
||||
warn!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
destination = hex::encode(link_entry.destination_hash),
|
||||
"link request proof has no known destination identity, not transporting"
|
||||
);
|
||||
return false;
|
||||
};
|
||||
|
||||
let mut destination_ed25519 = [0u8; 32];
|
||||
destination_ed25519.copy_from_slice(&destination_public_key[32..64]);
|
||||
let verify_key =
|
||||
match rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&destination_ed25519) {
|
||||
Ok(key) => key,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
destination = hex::encode(link_entry.destination_hash),
|
||||
error = %err,
|
||||
"link request proof destination identity is invalid, not transporting"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + signalling.len());
|
||||
signed_data.extend_from_slice(&header.destination_hash);
|
||||
signed_data.extend_from_slice(responder_x25519_pub);
|
||||
signed_data.extend_from_slice(&destination_ed25519);
|
||||
signed_data.extend_from_slice(signalling);
|
||||
|
||||
if verify_key.verify(&signed_data, &signature).is_ok() {
|
||||
true
|
||||
} else {
|
||||
warn!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
destination = hex::encode(link_entry.destination_hash),
|
||||
"invalid link request proof signature, not transporting"
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::now_f64;
|
||||
|
||||
impl TransportActor {
|
||||
pub(super) fn on_tick(&mut self) {
|
||||
@@ -21,7 +22,10 @@ impl TransportActor {
|
||||
&& self.state_dirty
|
||||
&& now - self.last_state_save >= STATE_SAVE_INTERVAL_SECS
|
||||
{
|
||||
self.save_routing_state();
|
||||
// Async: the fsync chain (F_FULLFSYNC per file on macOS) stalls
|
||||
// the actor for seconds if run inline, starving control queries
|
||||
// and inbound routing.
|
||||
self.save_routing_state_async();
|
||||
}
|
||||
|
||||
if now - self.last_tables_cull >= TABLES_CULL_INTERVAL {
|
||||
@@ -30,6 +34,8 @@ impl TransportActor {
|
||||
self.path_table.cull_expired_batch(100);
|
||||
self.reverse_table.cull_expired_batch(100);
|
||||
self.tunnel_table.cull_expired_batch(50);
|
||||
self.cull_stale_tunnel_paths(now);
|
||||
self.cull_path_interface_suppressions(now);
|
||||
|
||||
// Drop entries pointing to interfaces that have gone away —
|
||||
// those routes could never be used anyway.
|
||||
@@ -38,23 +44,28 @@ impl TransportActor {
|
||||
self.reverse_table.cull_dead_interfaces(&active_interfaces);
|
||||
self.link_table.cull_dead_interfaces(&active_interfaces);
|
||||
|
||||
// An unvalidated link whose proof window elapsed means the
|
||||
// cached path is probably stale — expire it and re-resolve so
|
||||
// the next attempt doesn't hammer a dead route.
|
||||
let (_, expired_dests) = self.link_table.cull_stale(LINK_TIMEOUT);
|
||||
for dest_hash in expired_dests {
|
||||
self.path_table.expire(&dest_hash);
|
||||
self.on_path_request(dest_hash);
|
||||
debug!(
|
||||
dest = hex::encode(dest_hash),
|
||||
"unvalidated link expired -- path expired and re-discovery triggered"
|
||||
);
|
||||
// Failed link establishment can mean either a stale path or a
|
||||
// topology change. Queue rediscovery so automated path requests
|
||||
// are bounded and throttled like upstream Reticulum 1.2.5.
|
||||
let (_, expired_links) = self.link_table.cull_stale(LINK_TIMEOUT);
|
||||
let mut queued_dests = HashSet::new();
|
||||
for expired_link in expired_links {
|
||||
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now)
|
||||
{
|
||||
if queued_dests.insert(request.destination_hash) {
|
||||
self.queue_discovery_path_request(
|
||||
request.destination_hash,
|
||||
request.blocked_interface,
|
||||
now,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cull may have removed path/tunnel entries — flag for save so
|
||||
// the on-disk file reflects the current routing state. False
|
||||
// positives (cull found nothing) cost one no-op file rewrite at
|
||||
// the next 10 s tick.
|
||||
// the next periodic flush.
|
||||
self.state_dirty = true;
|
||||
self.last_tables_cull = now;
|
||||
}
|
||||
@@ -127,17 +138,20 @@ impl TransportActor {
|
||||
// ones (Delivered/Failed/Culled) were already signalled out.
|
||||
self.receipt_table
|
||||
.retain(|_, r| r.status == ReceiptStatus::Sent);
|
||||
while self.receipt_table.len() > MAX_RECEIPTS {
|
||||
if let Some(oldest_key) = self
|
||||
let excess = self.receipt_table.len().saturating_sub(MAX_RECEIPTS);
|
||||
if excess > 0 {
|
||||
// Cull the oldest in one sorted pass — a min-scan per
|
||||
// eviction is O(n·k) on burst overflow.
|
||||
let mut by_age: Vec<([u8; 16], std::time::Instant)> = self
|
||||
.receipt_table
|
||||
.iter()
|
||||
.min_by_key(|(_, r)| r.sent_at)
|
||||
.map(|(k, _)| *k)
|
||||
{
|
||||
if let Some(r) = self.receipt_table.get_mut(&oldest_key) {
|
||||
r.cull();
|
||||
.map(|(k, r)| (*k, r.sent_at))
|
||||
.collect();
|
||||
by_age.sort_unstable_by_key(|(_, sent_at)| *sent_at);
|
||||
for (key, _) in by_age.into_iter().take(excess) {
|
||||
if let Some(mut receipt) = self.receipt_table.remove(&key) {
|
||||
receipt.cull();
|
||||
}
|
||||
self.receipt_table.remove(&oldest_key);
|
||||
}
|
||||
}
|
||||
self.last_receipts_check = now;
|
||||
@@ -151,17 +165,184 @@ impl TransportActor {
|
||||
|
||||
self.expire_path_waiters(now);
|
||||
|
||||
// Drop pending path-request markers older than 30 s so a retried
|
||||
// request isn't treated as "still in flight".
|
||||
self.path_requests.retain(|_, last| now - *last < 30.0);
|
||||
// Drop pending path-request markers after the upstream gate timeout.
|
||||
self.path_requests
|
||||
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
|
||||
self.discovery_path_requests
|
||||
.retain(|_, request| now < request.timeout);
|
||||
self.discovery_pr_tags
|
||||
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
|
||||
// Python `max_pr_tags` hard cap on top of the time gate: a tag storm
|
||||
// inside the gate window must not grow the map without bound.
|
||||
if self.discovery_pr_tags.len() > MAX_DISCOVERY_PR_TAGS {
|
||||
let mut by_age: Vec<(Vec<u8>, f64)> = self
|
||||
.discovery_pr_tags
|
||||
.iter()
|
||||
.map(|(tag, last)| (tag.clone(), *last))
|
||||
.collect();
|
||||
by_age.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
|
||||
let excess = self.discovery_pr_tags.len() - MAX_DISCOVERY_PR_TAGS;
|
||||
for (tag, _) in by_age.into_iter().take(excess) {
|
||||
self.discovery_pr_tags.remove(&tag);
|
||||
}
|
||||
}
|
||||
|
||||
self.process_pending_discovery_path_requests(now);
|
||||
self.process_announce_queues(now);
|
||||
}
|
||||
|
||||
pub(super) fn queue_discovery_path_request(
|
||||
&mut self,
|
||||
destination_hash: [u8; 16],
|
||||
blocked_interface: Option<InterfaceId>,
|
||||
now: f64,
|
||||
) -> bool {
|
||||
if self.pending_discovery_prs.len() >= MAX_QUEUED_DISCOVERY_PRS {
|
||||
trace!(
|
||||
dest = hex::encode(destination_hash),
|
||||
"dropping queued discovery path request because queue is full"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
let was_empty = self.pending_discovery_prs.is_empty();
|
||||
self.pending_discovery_prs
|
||||
.push_back(PendingDiscoveryPathRequest {
|
||||
destination_hash,
|
||||
blocked_interface,
|
||||
});
|
||||
if was_empty {
|
||||
self.last_discovery_pr_tx = now;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn process_pending_discovery_path_requests(&mut self, now: f64) {
|
||||
if self.pending_discovery_prs.is_empty() {
|
||||
return;
|
||||
}
|
||||
if now - self.last_discovery_pr_tx < DISCOVERY_PR_TX_THROTTLE {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(request) = self.pending_discovery_prs.pop_front() else {
|
||||
return;
|
||||
};
|
||||
self.last_discovery_pr_tx = now;
|
||||
|
||||
if let Some(blocked_interface) = request.blocked_interface {
|
||||
let ids: Vec<InterfaceId> = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.filter_map(|(&id, entry)| {
|
||||
if id == blocked_interface || !entry.direction.outbound {
|
||||
None
|
||||
} else {
|
||||
Some(id)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for id in ids {
|
||||
self.send_path_request(request.destination_hash, id, None, false);
|
||||
}
|
||||
} else {
|
||||
let mut request_tag = [0u8; 16];
|
||||
{
|
||||
use rand::RngCore;
|
||||
rand::thread_rng().fill_bytes(&mut request_tag);
|
||||
}
|
||||
let ids: Vec<InterfaceId> = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.filter_map(|(&id, entry)| entry.direction.outbound.then_some(id))
|
||||
.collect();
|
||||
for id in ids {
|
||||
self.send_path_request(request.destination_hash, id, Some(&request_tag), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn handle_expired_unvalidated_link(
|
||||
&mut self,
|
||||
expired_link: crate::link_table::ExpiredLink,
|
||||
now: f64,
|
||||
) {
|
||||
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now) {
|
||||
self.queue_discovery_path_request(
|
||||
request.destination_hash,
|
||||
request.blocked_interface,
|
||||
now,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn rediscovery_request_for_expired_link(
|
||||
&mut self,
|
||||
expired_link: crate::link_table::ExpiredLink,
|
||||
now: f64,
|
||||
) -> Option<PendingDiscoveryPathRequest> {
|
||||
let destination_hash = expired_link.destination_hash;
|
||||
let last_path_request = self
|
||||
.path_requests
|
||||
.get(&destination_hash)
|
||||
.copied()
|
||||
.unwrap_or(0.0);
|
||||
let path_request_throttle = now - last_path_request < PATH_REQUEST_MI;
|
||||
|
||||
let mut blocked_interface = None;
|
||||
let mut should_request = false;
|
||||
|
||||
if !self.path_table.has_path(&destination_hash) {
|
||||
should_request = true;
|
||||
} else if !path_request_throttle {
|
||||
if expired_link.taken_hops == 0 {
|
||||
should_request = true;
|
||||
} else if self.path_table.hops_to(&destination_hash) == Some(1)
|
||||
|| expired_link.taken_hops == 1
|
||||
{
|
||||
should_request = true;
|
||||
blocked_interface = Some(expired_link.receiving_interface);
|
||||
self.mark_failed_link_path_unresponsive(&expired_link);
|
||||
}
|
||||
}
|
||||
|
||||
if !should_request {
|
||||
return None;
|
||||
}
|
||||
|
||||
if !self.is_transport_enabled {
|
||||
self.path_table.expire(&destination_hash);
|
||||
}
|
||||
|
||||
debug!(
|
||||
dest = hex::encode(destination_hash),
|
||||
blocked_interface, "unvalidated link expired -- queued re-discovery"
|
||||
);
|
||||
|
||||
Some(PendingDiscoveryPathRequest {
|
||||
destination_hash,
|
||||
blocked_interface,
|
||||
})
|
||||
}
|
||||
|
||||
fn mark_failed_link_path_unresponsive(
|
||||
&mut self,
|
||||
expired_link: &crate::link_table::ExpiredLink,
|
||||
) {
|
||||
if !self.is_transport_enabled {
|
||||
return;
|
||||
}
|
||||
let receiving_is_boundary = self
|
||||
.interfaces
|
||||
.get(&expired_link.receiving_interface)
|
||||
.is_some_and(|entry| entry.mode == InterfaceMode::Boundary);
|
||||
if !receiving_is_boundary {
|
||||
self.path_table
|
||||
.set_state(expired_link.destination_hash, PathState::Unresponsive);
|
||||
}
|
||||
}
|
||||
|
||||
/// Called on background → foreground. Resets every `last_*_check` so the
|
||||
/// next `on_tick` runs all maintenance paths in one go.
|
||||
pub(super) fn on_resume(&mut self) {
|
||||
@@ -271,10 +452,49 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sweep `recent_announces`. Keep retained + pathed entries; reap the
|
||||
/// rest past `DESTINATION_TIMEOUT` (7 days). No count cap.
|
||||
pub(super) fn cull_stale_tunnel_paths(&mut self, now: f64) {
|
||||
let mut removed = 0usize;
|
||||
for (tunnel_id, tunnel) in self.tunnel_table.iter_mut() {
|
||||
let stale: Vec<[u8; 16]> = tunnel
|
||||
.tunnel_paths
|
||||
.iter()
|
||||
.filter_map(|(dest_hash, tunnel_path)| {
|
||||
if now > tunnel_path.timestamp + TUNNEL_PATH_TIMEOUT as f64 {
|
||||
return Some(*dest_hash);
|
||||
}
|
||||
|
||||
let active = self.path_table.get_live(dest_hash)?;
|
||||
let current_timebase =
|
||||
path_timebase_from_random_blobs(active.random_blobs.iter());
|
||||
let tunnel_timebase =
|
||||
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
|
||||
(current_timebase > tunnel_timebase).then_some(*dest_hash)
|
||||
})
|
||||
.collect();
|
||||
|
||||
for dest_hash in stale {
|
||||
tunnel.tunnel_paths.remove(&dest_hash);
|
||||
removed += 1;
|
||||
debug!(
|
||||
dest = hex::encode(dest_hash),
|
||||
tunnel = hex::encode(&tunnel_id[..16]),
|
||||
"removed stale tunnel path"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if removed > 0 {
|
||||
self.state_dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Sweep `recent_announces`, mirroring Python
|
||||
/// `Identity.clean_known_destinations`: retained + pathed entries are
|
||||
/// kept; pathless never-used entries die after `UNUSED_DESTINATION_LINGER`
|
||||
/// (6 min); pathless used entries die after `DESTINATION_TIMEOUT * 1.25`
|
||||
/// idle since last use.
|
||||
pub(super) fn cleanup_known_destinations(&mut self, now: f64) {
|
||||
let threshold = DESTINATION_TIMEOUT as f64;
|
||||
let used_threshold = DESTINATION_TIMEOUT as f64 * 1.25;
|
||||
|
||||
let before = self.recent_announces.len();
|
||||
// Collect into a Vec; the has-path borrow on path_table fights an
|
||||
@@ -289,12 +509,11 @@ impl TransportActor {
|
||||
if self.path_table.has_path(&a.dest_hash) {
|
||||
return None;
|
||||
}
|
||||
let idle = now - a.timestamp;
|
||||
if idle > threshold {
|
||||
Some(a.dest_hash)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let stale = match a.last_used {
|
||||
None => now - a.timestamp > UNUSED_DESTINATION_LINGER,
|
||||
Some(last_used) => now - last_used.max(a.timestamp) > used_threshold,
|
||||
};
|
||||
if stale { Some(a.dest_hash) } else { None }
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -381,7 +600,13 @@ mod cleanup_tests {
|
||||
use crate::actor::RecentAnnounce;
|
||||
use crate::path_table::PathEntry;
|
||||
|
||||
fn insert_entry(actor: &mut TransportActor, hash: u8, timestamp: f64, retained: bool) {
|
||||
fn insert_entry_with_last_used(
|
||||
actor: &mut TransportActor,
|
||||
hash: u8,
|
||||
timestamp: f64,
|
||||
retained: bool,
|
||||
last_used: Option<f64>,
|
||||
) {
|
||||
let entry = RecentAnnounce {
|
||||
dest_hash: [hash; 16],
|
||||
hops: 0,
|
||||
@@ -389,13 +614,23 @@ mod cleanup_tests {
|
||||
timestamp,
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
raw_packet: Vec::new(),
|
||||
packet_hash: None,
|
||||
is_path_response: false,
|
||||
retained,
|
||||
last_used,
|
||||
name_hash: [0u8; 10],
|
||||
};
|
||||
actor.recent_announces.insert(entry.dest_hash, entry);
|
||||
}
|
||||
|
||||
fn insert_entry(actor: &mut TransportActor, hash: u8, timestamp: f64, retained: bool) {
|
||||
insert_entry_with_last_used(actor, hash, timestamp, retained, None);
|
||||
}
|
||||
|
||||
fn insert_used_entry(actor: &mut TransportActor, hash: u8, timestamp: f64, last_used: f64) {
|
||||
insert_entry_with_last_used(actor, hash, timestamp, false, Some(last_used));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_survives_cleanup() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
@@ -418,28 +653,29 @@ mod cleanup_tests {
|
||||
assert_eq!(actor.recent_announces.len(), 1);
|
||||
}
|
||||
|
||||
// Pre-collapse, a never-used pathless entry was reaped after 6 min.
|
||||
// Under the uniform 7-d policy, an entry only ten minutes old survives.
|
||||
#[test]
|
||||
fn pathless_kept_well_below_destination_timeout() {
|
||||
fn pathless_never_used_kept_inside_linger() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let now = 10_000.0;
|
||||
let ten_minutes_old = now - 10.0 * 60.0;
|
||||
insert_entry(&mut actor, 0x03, ten_minutes_old, /*retained=*/ false);
|
||||
insert_entry(
|
||||
&mut actor,
|
||||
0x03,
|
||||
now - UNUSED_DESTINATION_LINGER + 1.0,
|
||||
/*retained=*/ false,
|
||||
);
|
||||
|
||||
actor.cleanup_known_destinations(now);
|
||||
assert_eq!(actor.recent_announces.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathless_reaped_past_destination_timeout() {
|
||||
fn pathless_never_used_reaped_after_linger() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let now = 10_000_000.0;
|
||||
let timeout = DESTINATION_TIMEOUT as f64;
|
||||
let now = 10_000.0;
|
||||
insert_entry(
|
||||
&mut actor,
|
||||
0x05,
|
||||
now - timeout - 1.0,
|
||||
now - UNUSED_DESTINATION_LINGER - 1.0,
|
||||
/*retained=*/ false,
|
||||
);
|
||||
|
||||
@@ -448,18 +684,51 @@ mod cleanup_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathless_kept_just_inside_destination_timeout() {
|
||||
fn pathless_used_survives_destination_timeout_idle() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let now = 10_000_000.0;
|
||||
let timeout = DESTINATION_TIMEOUT as f64;
|
||||
insert_entry(
|
||||
&mut actor,
|
||||
0x07,
|
||||
now - timeout + 1.0,
|
||||
/*retained=*/ false,
|
||||
);
|
||||
// Announce far past linger; 7 d idle since use is inside the
|
||||
// 7 d * 1.25 window, so the use pin keeps it alive.
|
||||
insert_used_entry(&mut actor, 0x07, now - timeout * 2.0, now - timeout);
|
||||
|
||||
actor.cleanup_known_destinations(now);
|
||||
assert_eq!(actor.recent_announces.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathless_used_reaped_past_destination_timeout_x125() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let now = 10_000_000.0;
|
||||
let threshold = DESTINATION_TIMEOUT as f64 * 1.25;
|
||||
insert_used_entry(
|
||||
&mut actor,
|
||||
0x09,
|
||||
now - threshold - 2.0,
|
||||
now - threshold - 1.0,
|
||||
);
|
||||
|
||||
actor.cleanup_known_destinations(now);
|
||||
assert!(actor.recent_announces.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_pr_tags_capped_at_max() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let now = crate::now_f64();
|
||||
// All inside PATH_REQUEST_GATE_TIMEOUT, so only the count cap trims.
|
||||
for i in 0..=MAX_DISCOVERY_PR_TAGS {
|
||||
let tag = (i as u64).to_be_bytes().to_vec();
|
||||
actor.discovery_pr_tags.insert(tag, now - (i as f64) * 1e-4);
|
||||
}
|
||||
assert_eq!(actor.discovery_pr_tags.len(), MAX_DISCOVERY_PR_TAGS + 1);
|
||||
|
||||
actor.on_tick();
|
||||
|
||||
assert_eq!(actor.discovery_pr_tags.len(), MAX_DISCOVERY_PR_TAGS);
|
||||
let oldest = (MAX_DISCOVERY_PR_TAGS as u64).to_be_bytes().to_vec();
|
||||
assert!(!actor.discovery_pr_tags.contains_key(&oldest));
|
||||
let newest = 0u64.to_be_bytes();
|
||||
assert!(actor.discovery_pr_tags.contains_key(newest.as_slice()));
|
||||
}
|
||||
}
|
||||
+2718
-214
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::now_f64;
|
||||
|
||||
impl TransportActor {
|
||||
pub(super) fn on_outbound(&mut self, request: crate::messages::OutboundRequest) {
|
||||
@@ -57,7 +58,7 @@ impl TransportActor {
|
||||
self.broadcast_on_interfaces(&request.raw, None);
|
||||
}
|
||||
rns_wire::flags::DestinationType::Single | rns_wire::flags::DestinationType::Link => {
|
||||
if let Some(path) = self.path_table.get(&request.destination_hash) {
|
||||
if let Some(path) = self.path_table.get_live(&request.destination_hash) {
|
||||
let target_interface = path.interface_id;
|
||||
let path_hops = path.hops;
|
||||
let path_next_hop = path.next_hop;
|
||||
@@ -112,8 +113,8 @@ impl TransportActor {
|
||||
|
||||
// Touch the path so an actively-used route isn't culled
|
||||
// for staleness while traffic is still flowing on it.
|
||||
if let Some(path) = self.path_table.get_mut(&request.destination_hash) {
|
||||
path.timestamp = now_f64();
|
||||
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) {
|
||||
path.touch();
|
||||
}
|
||||
} else {
|
||||
let iface_names: Vec<&str> = self
|
||||
@@ -128,7 +129,9 @@ impl TransportActor {
|
||||
"outbound: no path, broadcasting"
|
||||
);
|
||||
self.broadcast_on_interfaces(&request.raw, None);
|
||||
self.on_path_request(request.destination_hash);
|
||||
if parsed.flags.packet_type != rns_wire::flags::PacketType::Proof {
|
||||
self.on_automatic_path_request(request.destination_hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,13 +186,13 @@ impl TransportActor {
|
||||
let mut requested_hash = [0u8; 32];
|
||||
requested_hash.copy_from_slice(payload);
|
||||
|
||||
let dest_hash: Option<[u8; 16]> = self
|
||||
let dest_and_hops: Option<([u8; 16], u8)> = self
|
||||
.path_table
|
||||
.iter()
|
||||
.find(|(_, entry)| entry.packet_hash == Some(requested_hash))
|
||||
.map(|(dest, _)| *dest.as_bytes());
|
||||
.map(|(dest, entry)| (*dest.as_bytes(), entry.hops));
|
||||
|
||||
let Some(dest) = dest_hash else {
|
||||
let Some((dest, cached_hops)) = dest_and_hops else {
|
||||
trace!(
|
||||
hash = %hex::encode(requested_hash),
|
||||
"cache request miss — no path entry with matching packet hash"
|
||||
@@ -197,24 +200,13 @@ impl TransportActor {
|
||||
return;
|
||||
};
|
||||
|
||||
let (cached_raw, cached_hops) = match self.recent_announces.get(&dest) {
|
||||
Some(cached) => (cached.raw_packet.clone(), cached.hops),
|
||||
None => {
|
||||
trace!(
|
||||
dest = %hex::encode(dest),
|
||||
"cache request: path entry found but no cached announce for destination"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if cached_raw.is_empty() {
|
||||
let Some(cached_raw) = self.cached_announce_raw(&requested_hash) else {
|
||||
trace!(
|
||||
dest = %hex::encode(dest),
|
||||
"cache request: announce cached but no raw packet (v1 persistence), ignoring"
|
||||
"cache request: path entry found but no cached announce on disk"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
debug!(
|
||||
dest = %hex::encode(dest),
|
||||
@@ -283,6 +275,10 @@ impl TransportActor {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
|
||||
entry.ingress.received_path_request();
|
||||
}
|
||||
|
||||
let now = now_f64();
|
||||
let mut unique_tag = Vec::with_capacity(32);
|
||||
unique_tag.extend_from_slice(&requested_dest);
|
||||
@@ -321,7 +317,7 @@ impl TransportActor {
|
||||
}
|
||||
|
||||
if !is_from_local_client {
|
||||
if let Some(path) = self.path_table.get(&requested_dest) {
|
||||
if let Some(path) = self.path_table.get_live(&requested_dest) {
|
||||
if self.is_local_client_interface(path.interface_id) {
|
||||
self.pending_local_path_requests
|
||||
.insert(requested_dest, interface_id);
|
||||
@@ -333,7 +329,7 @@ impl TransportActor {
|
||||
// shared instance's path cache even when the instance is not a transport
|
||||
// node. Ordinary peers still require transport mode.
|
||||
if let Some(path) = (self.is_transport_enabled || is_from_local_client)
|
||||
.then(|| self.path_table.get(&requested_dest))
|
||||
.then(|| self.path_table.get_live(&requested_dest))
|
||||
.flatten()
|
||||
{
|
||||
let requestor_is_next_hop =
|
||||
@@ -359,14 +355,10 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
let cached_raw: Option<(u8, Vec<u8>)> =
|
||||
self.recent_announces.get(&requested_dest).and_then(|a| {
|
||||
if a.raw_packet.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some((path.hops, a.raw_packet.clone()))
|
||||
}
|
||||
});
|
||||
let cached_raw: Option<(u8, Vec<u8>)> = path
|
||||
.packet_hash
|
||||
.and_then(|hash| self.cached_announce_raw(&hash))
|
||||
.map(|raw| (path.hops, raw));
|
||||
if let Some((hops, raw)) = cached_raw {
|
||||
debug!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
@@ -424,29 +416,39 @@ impl TransportActor {
|
||||
);
|
||||
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, false);
|
||||
} else if self.is_transport_enabled && should_search_unknown {
|
||||
let should_forward = match self.discovery_path_requests.entry(requested_dest) {
|
||||
std::collections::hash_map::Entry::Occupied(_) => {
|
||||
debug!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
"not forwarding path request — discovery request is already waiting"
|
||||
);
|
||||
false
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
debug!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
"forwarding path request on other interfaces"
|
||||
);
|
||||
entry.insert(DiscoveryPathRequest {
|
||||
requesting_interface: interface_id,
|
||||
timeout: now + PATH_REQUEST_TIMEOUT,
|
||||
});
|
||||
true
|
||||
}
|
||||
};
|
||||
if should_forward {
|
||||
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
|
||||
if self.discovery_path_requests.contains_key(&requested_dest) {
|
||||
debug!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
"not forwarding path request — discovery request is already waiting"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let ingress_limited = self
|
||||
.interfaces
|
||||
.get_mut(&interface_id)
|
||||
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
|
||||
if ingress_limited {
|
||||
debug!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
interface_id,
|
||||
"not forwarding recursive path request — ingress PR burst active"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
debug!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
"forwarding path request on other interfaces"
|
||||
);
|
||||
self.discovery_path_requests.insert(
|
||||
requested_dest,
|
||||
DiscoveryPathRequest {
|
||||
requesting_interface: interface_id,
|
||||
timeout: now + PATH_REQUEST_TIMEOUT,
|
||||
},
|
||||
);
|
||||
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
|
||||
} else if self.has_local_client_interfaces() {
|
||||
debug!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
@@ -501,16 +503,61 @@ impl TransportActor {
|
||||
raw
|
||||
}
|
||||
|
||||
fn send_path_request(
|
||||
pub(super) fn send_path_request(
|
||||
&mut self,
|
||||
destination_hash: [u8; 16],
|
||||
interface_id: InterfaceId,
|
||||
tag: Option<&[u8]>,
|
||||
_recursive: bool,
|
||||
recursive: bool,
|
||||
) {
|
||||
let raw = self.build_path_request_packet(destination_hash, tag);
|
||||
let now = now_f64();
|
||||
{
|
||||
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
|
||||
return;
|
||||
};
|
||||
if !entry.direction.outbound {
|
||||
return;
|
||||
}
|
||||
|
||||
if recursive {
|
||||
if entry.ingress.should_egress_limit_pr() {
|
||||
trace!(
|
||||
dest = %hex::encode(destination_hash),
|
||||
interface_id,
|
||||
"skipping recursive path request — egress PR limit active"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if !entry.announce_queue.is_empty() {
|
||||
trace!(
|
||||
dest = %hex::encode(destination_hash),
|
||||
interface_id,
|
||||
"skipping recursive path request — announce queue is not empty"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if now < entry.announce_allowed_at {
|
||||
trace!(
|
||||
dest = %hex::encode(destination_hash),
|
||||
interface_id,
|
||||
"skipping recursive path request — announce cap window active"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let bitrate = entry.bitrate.max(1) as f64;
|
||||
let tx_time = (raw.len() as f64 * 8.0) / bitrate;
|
||||
let wait_time = tx_time / entry.announce_cap.max(0.001);
|
||||
entry.announce_allowed_at = now + wait_time;
|
||||
}
|
||||
}
|
||||
|
||||
self.send_to_interface(interface_id, &raw);
|
||||
self.path_requests.insert(destination_hash, now_f64());
|
||||
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
|
||||
entry.ingress.sent_path_request();
|
||||
}
|
||||
self.path_requests.insert(destination_hash, now);
|
||||
}
|
||||
|
||||
fn forward_path_request(
|
||||
@@ -537,60 +584,29 @@ impl TransportActor {
|
||||
}
|
||||
|
||||
pub(super) fn on_path_request(&mut self, destination_hash: [u8; 16]) {
|
||||
let now = now_f64();
|
||||
|
||||
if let Some(last) = self.path_requests.get(&destination_hash) {
|
||||
if now - last < PATH_REQUEST_MI {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
self.path_requests.insert(destination_hash, now);
|
||||
self.broadcast_path_request(destination_hash);
|
||||
}
|
||||
|
||||
pub(super) fn on_automatic_path_request(&mut self, destination_hash: [u8; 16]) {
|
||||
if self.path_table.has_path(&destination_hash) {
|
||||
return;
|
||||
}
|
||||
if let Some(last) = self.path_requests.get(&destination_hash) {
|
||||
if now_f64() - last < PATH_REQUEST_MI {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.broadcast_path_request(destination_hash);
|
||||
}
|
||||
|
||||
// Python Transport.request_path sends a PLAIN packet to the
|
||||
// rnstransport.path.request destination. The payload is the requested
|
||||
// destination hash, optionally followed by the transport identity hash,
|
||||
// and a random tag used for request deduplication.
|
||||
fn broadcast_path_request(&mut self, destination_hash: [u8; 16]) {
|
||||
let mut request_tag = [0u8; 16];
|
||||
{
|
||||
use rand::RngCore;
|
||||
rand::thread_rng().fill_bytes(&mut request_tag);
|
||||
}
|
||||
|
||||
let mut request_data = Vec::with_capacity(48);
|
||||
request_data.extend_from_slice(&destination_hash);
|
||||
if self.is_transport_enabled {
|
||||
if let Some(identity_hash) = self.transport_identity_hash {
|
||||
request_data.extend_from_slice(&identity_hash);
|
||||
}
|
||||
}
|
||||
request_data.extend_from_slice(&request_tag);
|
||||
|
||||
let path_request_dest = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
"rnstransport.path.request",
|
||||
None,
|
||||
);
|
||||
let flags = rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
context_flag: false,
|
||||
transport_type: rns_wire::flags::TransportType::Broadcast,
|
||||
destination_type: rns_wire::flags::DestinationType::Plain,
|
||||
packet_type: rns_wire::flags::PacketType::Data,
|
||||
};
|
||||
let path_request_header = rns_wire::header::PacketHeader {
|
||||
flags,
|
||||
hops: 0,
|
||||
transport_id: None,
|
||||
destination_hash: path_request_dest,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
};
|
||||
let mut request_raw = path_request_header.pack();
|
||||
request_raw.extend_from_slice(&request_data);
|
||||
self.broadcast_on_interfaces(&request_raw, None);
|
||||
self.forward_path_request(destination_hash, None, Some(&request_tag), false);
|
||||
|
||||
debug!(
|
||||
dest = hex::encode(destination_hash),
|
||||
@@ -622,10 +638,19 @@ impl TransportActor {
|
||||
if let Some(existing) = self.path_table.get(dest_hash) {
|
||||
let old_hops = existing.hops;
|
||||
let old_expires = existing.expires;
|
||||
// Only overwrite a live path if the tunnel copy is at least
|
||||
// as short, or the live entry is already stale.
|
||||
if tunnel_path.hops <= old_hops || now > old_expires {
|
||||
should_add = true;
|
||||
let current_timebase =
|
||||
path_timebase_from_random_blobs(existing.random_blobs.iter());
|
||||
let tunnel_timebase =
|
||||
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
|
||||
if tunnel_timebase >= current_timebase {
|
||||
should_add = true;
|
||||
} else {
|
||||
debug!(
|
||||
dest = hex::encode(dest_hash),
|
||||
"did not restore tunnel path: existing path is more recent"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
debug!(
|
||||
dest = hex::encode(dest_hash),
|
||||
@@ -644,12 +669,12 @@ impl TransportActor {
|
||||
if should_add {
|
||||
let entry = crate::path_table::PathEntry {
|
||||
timestamp: now,
|
||||
next_hop: None,
|
||||
next_hop: tunnel_path.next_hop,
|
||||
hops: tunnel_path.hops,
|
||||
expires: tunnel_path.expires,
|
||||
random_blobs: tunnel_path.random_blobs.iter().copied().collect(),
|
||||
interface_id,
|
||||
packet_hash: None,
|
||||
packet_hash: tunnel_path.packet_hash,
|
||||
};
|
||||
self.path_table.insert(*dest_hash, entry);
|
||||
self.state_dirty = true;
|
||||
@@ -675,6 +700,7 @@ impl TransportActor {
|
||||
);
|
||||
}
|
||||
}
|
||||
self.state_dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,126 +4,352 @@ 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)
|
||||
crate::now_f64()
|
||||
}
|
||||
|
||||
fn recent_announce_from_cached_packet(
|
||||
dest_hash: [u8; 16],
|
||||
hops: u8,
|
||||
timestamp: f64,
|
||||
raw_packet: Vec<u8>,
|
||||
) -> RecentAnnounce {
|
||||
let mut recent = RecentAnnounce {
|
||||
dest_hash,
|
||||
hops,
|
||||
app_data: None,
|
||||
timestamp,
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
packet_hash: None,
|
||||
is_path_response: false,
|
||||
retained: false,
|
||||
last_used: None,
|
||||
name_hash: [0u8; 10],
|
||||
};
|
||||
|
||||
if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&raw_packet)
|
||||
&& header.flags.packet_type == rns_wire::flags::PacketType::Announce
|
||||
&& header.destination_hash == dest_hash
|
||||
&& raw_packet.len() >= offset
|
||||
{
|
||||
recent.packet_hash = Some(rns_wire::hash::packet_hash(
|
||||
&raw_packet,
|
||||
header.flags.header_type,
|
||||
));
|
||||
recent.is_path_response = header.context == rns_wire::context::PacketContext::PathResponse;
|
||||
if let Ok(announce) = rns_identity::announce::AnnounceData::unpack(
|
||||
&raw_packet[offset..],
|
||||
header.flags.context_flag,
|
||||
) {
|
||||
recent.app_data = announce.app_data;
|
||||
recent.public_key = Some(announce.public_key);
|
||||
recent.ratchet = announce.ratchet;
|
||||
recent.name_hash = announce.name_hash;
|
||||
}
|
||||
}
|
||||
|
||||
recent
|
||||
}
|
||||
|
||||
fn python_announce_cache_index(
|
||||
announce_cache_dir: &std::path::Path,
|
||||
) -> Option<std::collections::HashSet<String>> {
|
||||
match std::fs::read_dir(announce_cache_dir) {
|
||||
Ok(entries) => {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for entry in entries.flatten() {
|
||||
if let Some(name) = entry.file_name().to_str()
|
||||
&& name.len() == 64
|
||||
&& name.as_bytes().iter().all(u8::is_ascii_hexdigit)
|
||||
{
|
||||
names.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
Some(names)
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
Some(std::collections::HashSet::new())
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_indexed_python_cached_announce(
|
||||
announce_cache_dir: &std::path::Path,
|
||||
cache_index: Option<&std::collections::HashSet<String>>,
|
||||
packet_hash: &[u8; 32],
|
||||
) -> Result<Option<crate::persistence::PythonCachedAnnounce>, crate::persistence::PersistenceError>
|
||||
{
|
||||
if let Some(index) = cache_index {
|
||||
let name = hex::encode(packet_hash);
|
||||
if !index.contains(&name) {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
crate::persistence::load_python_cached_announce(announce_cache_dir, packet_hash)
|
||||
}
|
||||
|
||||
/// Owned copy of everything `write_routing_snapshot` persists, so the disk
|
||||
/// I/O (fsync-heavy on macOS: F_FULLFSYNC per file + dir) can run on the
|
||||
/// blocking pool without borrowing the actor.
|
||||
pub(super) struct RoutingSnapshot {
|
||||
pub path_table: crate::path_table::PathTable,
|
||||
pub tunnel_table: crate::tunnel::TunnelTable,
|
||||
pub blackhole_table: crate::blackhole::BlackholeTable,
|
||||
pub recent_announces: Vec<RecentAnnounce>,
|
||||
pub interface_names: std::collections::HashMap<u64, String>,
|
||||
pub transport_identity_hash: Option<[u8; 16]>,
|
||||
}
|
||||
|
||||
/// Persist a routing snapshot. Runs on the blocking pool for periodic saves
|
||||
/// and inline for shutdown; must not touch the actor.
|
||||
pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSnapshot) {
|
||||
let interface_names = &snapshot.interface_names;
|
||||
|
||||
let path_table_path = dir.join("path_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_path_table(&snapshot.path_table, interface_names, &path_table_path)
|
||||
{
|
||||
trace!("failed to save path table: {}", e);
|
||||
} else {
|
||||
debug!("saved path table ({} entries)", snapshot.path_table.len());
|
||||
}
|
||||
|
||||
let destination_table_path = dir.join("destination_table");
|
||||
if let Err(e) = crate::persistence::save_python_destination_table(
|
||||
&snapshot.path_table,
|
||||
interface_names,
|
||||
&destination_table_path,
|
||||
) {
|
||||
trace!("failed to save Python destination_table: {}", e);
|
||||
}
|
||||
|
||||
let blackhole_path = dir.join("blackhole_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_blackhole_table(&snapshot.blackhole_table, &blackhole_path)
|
||||
{
|
||||
trace!("failed to save blackhole table: {}", e);
|
||||
} else {
|
||||
debug!(
|
||||
"saved blackhole table ({} entries)",
|
||||
snapshot.blackhole_table.len()
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(local_identity_hash) = snapshot.transport_identity_hash {
|
||||
let blackhole_dir = dir.join("blackhole");
|
||||
if let Err(e) = crate::persistence::save_python_blackhole_files(
|
||||
&snapshot.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(snapshot.recent_announces.iter(), &announce_path)
|
||||
{
|
||||
trace!("failed to save announce cache: {}", e);
|
||||
} else {
|
||||
debug!(
|
||||
"saved announce cache ({} entries)",
|
||||
snapshot.recent_announces.len()
|
||||
);
|
||||
}
|
||||
|
||||
// Per-announce Python cache files are written event-driven at receive
|
||||
// (`cache_announce_to_disk`), not re-serialized here every cycle.
|
||||
|
||||
let tunnel_path = dir.join("tunnel_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_tunnel_table(&snapshot.tunnel_table, interface_names, &tunnel_path)
|
||||
{
|
||||
trace!("failed to save tunnel table: {}", e);
|
||||
} else {
|
||||
debug!(
|
||||
"saved tunnel table ({} entries)",
|
||||
snapshot.tunnel_table.len()
|
||||
);
|
||||
}
|
||||
|
||||
let python_tunnels_path = dir.join("tunnels");
|
||||
if let Err(e) = crate::persistence::save_python_tunnel_table(
|
||||
&snapshot.tunnel_table,
|
||||
interface_names,
|
||||
&python_tunnels_path,
|
||||
) {
|
||||
trace!("failed to save Python tunnels table: {}", e);
|
||||
}
|
||||
|
||||
debug!(
|
||||
paths = snapshot.path_table.len(),
|
||||
announces = snapshot.recent_announces.len(),
|
||||
tunnels = snapshot.tunnel_table.len(),
|
||||
blackhole = snapshot.blackhole_table.len(),
|
||||
"flushed routing state"
|
||||
);
|
||||
}
|
||||
|
||||
impl TransportActor {
|
||||
/// Fetch raw announce bytes from the disk announce cache
|
||||
/// (`cache/announces/<packet_hash>`). Misses are normal: legacy entries,
|
||||
/// cleaned cache files, or shared-instance client mode.
|
||||
pub(super) fn cached_announce_raw(&self, packet_hash: &[u8; 32]) -> Option<Vec<u8>> {
|
||||
let dir = self.storage_dir.as_ref()?;
|
||||
let announce_cache_dir = dir.join("cache").join("announces");
|
||||
match crate::persistence::load_python_cached_announce(&announce_cache_dir, packet_hash) {
|
||||
Ok(Some(cached)) => Some(cached.raw_packet),
|
||||
Ok(None) => None,
|
||||
Err(e) => {
|
||||
trace!("failed to load cached announce: {}", e);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Event-driven announce cache write at receive (Python parity:
|
||||
/// `Transport.cache(packet, force_cache=True)` on announce ingest).
|
||||
/// One file per announce packet; skipped when the file already exists
|
||||
/// (SINGLE announces are retransmitted byte-identical). No fsync — the
|
||||
/// cache is best-effort and rebuilt from live traffic, and an fsync
|
||||
/// chain here would stall the actor on every announce.
|
||||
pub(super) fn cache_announce_to_disk(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
raw: &[u8],
|
||||
interface_id: InterfaceId,
|
||||
) {
|
||||
if self.shared_instance_client_mode {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = self.storage_dir.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let announce_cache_dir = dir.join("cache").join("announces");
|
||||
let interface_name = self
|
||||
.interfaces
|
||||
.get(&interface_id)
|
||||
.map(|entry| entry.name.clone());
|
||||
if let Err(e) = crate::persistence::write_python_cached_announce_if_absent(
|
||||
&announce_cache_dir,
|
||||
packet_hash,
|
||||
raw,
|
||||
interface_name.as_deref(),
|
||||
) {
|
||||
trace!("failed to write announce cache file: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
fn routing_snapshot(&self) -> RoutingSnapshot {
|
||||
RoutingSnapshot {
|
||||
path_table: self.path_table.clone(),
|
||||
tunnel_table: self.tunnel_table.clone(),
|
||||
blackhole_table: self.blackhole_table.clone(),
|
||||
recent_announces: self.recent_announces.values().cloned().collect(),
|
||||
interface_names: self
|
||||
.interfaces
|
||||
.iter()
|
||||
.map(|(&id, entry)| (id, entry.name.clone()))
|
||||
.collect(),
|
||||
transport_identity_hash: self.transport_identity_hash,
|
||||
}
|
||||
}
|
||||
|
||||
/// Periodic flush used by `on_tick`: snapshot on the actor (cheap clones)
|
||||
/// and push the fsync-heavy writes to the blocking pool. A save already
|
||||
/// in flight keeps `state_dirty` set so the next tick retries — two
|
||||
/// writers would race on the shared `<file>.tmp` names.
|
||||
pub(super) fn save_routing_state_async(&mut self) {
|
||||
if self.shared_instance_client_mode {
|
||||
trace!("skipping routing-state save in shared-instance client mode");
|
||||
self.state_dirty = false;
|
||||
self.last_state_save = now();
|
||||
return;
|
||||
}
|
||||
let Some(dir) = self.storage_dir.clone() else {
|
||||
self.state_dirty = false;
|
||||
self.last_state_save = now();
|
||||
return;
|
||||
};
|
||||
if self
|
||||
.routing_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
trace!("routing-state save already in flight; retry next interval");
|
||||
return;
|
||||
}
|
||||
self.routing_save_in_flight
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
let snapshot = self.routing_snapshot();
|
||||
let in_flight = self.routing_save_in_flight.clone();
|
||||
match tokio::runtime::Handle::try_current() {
|
||||
Ok(handle) => {
|
||||
handle.spawn_blocking(move || {
|
||||
write_routing_snapshot(&dir, &snapshot);
|
||||
in_flight.store(false, std::sync::atomic::Ordering::Release);
|
||||
});
|
||||
}
|
||||
Err(_) => {
|
||||
// No runtime (tests, exotic embedders): write inline.
|
||||
write_routing_snapshot(&dir, &snapshot);
|
||||
in_flight.store(false, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
}
|
||||
self.state_dirty = false;
|
||||
self.last_state_save = now();
|
||||
}
|
||||
|
||||
/// Wait (bounded) for an in-flight async save so a synchronous save
|
||||
/// can't race it on the shared `<file>.tmp` paths.
|
||||
pub(super) fn wait_for_routing_save(&self) {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
while self
|
||||
.routing_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
if std::time::Instant::now() >= deadline {
|
||||
tracing::warn!("in-flight routing-state save did not finish before sync save");
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Synchronous: used by shutdown / falling-edge / RPC-forced saves where
|
||||
/// completion must be guaranteed before proceeding.
|
||||
pub(super) fn save_routing_state(&mut self) {
|
||||
if let Some(ref dir) = self.storage_dir {
|
||||
let interface_names: std::collections::HashMap<u64, String> = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.map(|(&id, entry)| (id, entry.name.clone()))
|
||||
.collect();
|
||||
if self.shared_instance_client_mode {
|
||||
trace!("skipping routing-state save in shared-instance client mode");
|
||||
self.state_dirty = false;
|
||||
self.last_state_save = now();
|
||||
return;
|
||||
}
|
||||
|
||||
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.wait_for_routing_save();
|
||||
if let Some(dir) = self.storage_dir.clone() {
|
||||
let snapshot = self.routing_snapshot();
|
||||
write_routing_snapshot(&dir, &snapshot);
|
||||
}
|
||||
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.
|
||||
/// hashlist, synchronously. Shutdown-only: the process is exiting, so
|
||||
/// blocking the actor is fine and completion must be guaranteed.
|
||||
pub(super) fn save_state(&mut self) {
|
||||
// Routing state first so the order matches the periodic-save shape.
|
||||
self.save_routing_state();
|
||||
if self.shared_instance_client_mode {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(ref dir) = self.storage_dir {
|
||||
let hashlist_path = dir.join("packet_hashlist");
|
||||
@@ -136,6 +362,47 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Falling-edge (foreground→background) flush. Same coverage as
|
||||
/// `save_state` but entirely off-actor: on desktop the edge fires on
|
||||
/// every window focus loss, and the inline fsync chain (F_FULLFSYNC per
|
||||
/// file on macOS) stalls routing + control queries for seconds.
|
||||
pub(super) fn save_state_async(&mut self) {
|
||||
self.save_routing_state_async();
|
||||
if self.shared_instance_client_mode {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = self.storage_dir.clone() else {
|
||||
return;
|
||||
};
|
||||
if self
|
||||
.hashlist_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
trace!("hashlist save already in flight; skipping");
|
||||
return;
|
||||
}
|
||||
self.hashlist_save_in_flight
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
let hashlist = self.packet_hashlist.clone();
|
||||
let in_flight = self.hashlist_save_in_flight.clone();
|
||||
let entries = hashlist.len();
|
||||
let write = move || {
|
||||
let hashlist_path = dir.join("packet_hashlist");
|
||||
if let Err(e) = crate::persistence::save_hashlist(&hashlist, &hashlist_path) {
|
||||
trace!("failed to save hashlist: {}", e);
|
||||
} else {
|
||||
info!(entries, "flushed hashlist");
|
||||
}
|
||||
in_flight.store(false, std::sync::atomic::Ordering::Release);
|
||||
};
|
||||
match tokio::runtime::Handle::try_current() {
|
||||
Ok(handle) => {
|
||||
handle.spawn_blocking(write);
|
||||
}
|
||||
Err(_) => write(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn on_shutdown(&mut self) {
|
||||
self.save_state();
|
||||
}
|
||||
@@ -186,13 +453,15 @@ impl TransportActor {
|
||||
let mut missing_cache = 0usize;
|
||||
let mut pending = 0usize;
|
||||
let announce_cache_dir = dir.join("cache").join("announces");
|
||||
let announce_cache_index = python_announce_cache_index(&announce_cache_dir);
|
||||
for pe in entries {
|
||||
if pe.expires <= now_ts {
|
||||
expired += 1;
|
||||
continue;
|
||||
}
|
||||
let cached = match crate::persistence::load_python_cached_announce(
|
||||
let cached = match load_indexed_python_cached_announce(
|
||||
&announce_cache_dir,
|
||||
announce_cache_index.as_ref(),
|
||||
&pe.packet_hash,
|
||||
) {
|
||||
Ok(Some(cached)) => cached,
|
||||
@@ -229,16 +498,13 @@ impl TransportActor {
|
||||
});
|
||||
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],
|
||||
.or_insert_with(|| {
|
||||
recent_announce_from_cached_packet(
|
||||
pe.destination_hash,
|
||||
pe.hops,
|
||||
pe.timestamp,
|
||||
cached.raw_packet,
|
||||
)
|
||||
});
|
||||
pending += 1;
|
||||
}
|
||||
@@ -323,9 +589,121 @@ impl TransportActor {
|
||||
}
|
||||
self.load_python_blackhole_if_ready();
|
||||
|
||||
// tunnel_table — defer remap.
|
||||
// Python tunnels — canonical interop shape. Each path is only staged
|
||||
// when its cached announce packet is present, mirroring upstream's
|
||||
// dependency between tunnel paths and the announce cache.
|
||||
let python_tunnels_path = dir.join("tunnels");
|
||||
let loaded_python_tunnel_table = if python_tunnels_path.exists() {
|
||||
match crate::persistence::load_python_tunnel_table(&python_tunnels_path) {
|
||||
Ok(entries) => {
|
||||
let total = entries.len();
|
||||
let mut expired = 0usize;
|
||||
let mut missing_cache = 0usize;
|
||||
let mut legacy = 0usize;
|
||||
let mut pending = 0usize;
|
||||
let announce_cache_dir = dir.join("cache").join("announces");
|
||||
let announce_cache_index = python_announce_cache_index(&announce_cache_dir);
|
||||
for te in entries {
|
||||
if te.expires <= now_ts {
|
||||
expired += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut paths = Vec::new();
|
||||
let mut interface_name = None;
|
||||
let mut interface_hash =
|
||||
te.interface_hash.as_ref().map(|hash| hash.to_vec());
|
||||
|
||||
for tp in te.paths {
|
||||
if tp.expires <= now_ts {
|
||||
expired += 1;
|
||||
continue;
|
||||
}
|
||||
if interface_hash.is_none() {
|
||||
interface_hash =
|
||||
tp.interface_hash.as_ref().map(|hash| hash.to_vec());
|
||||
}
|
||||
let cached = match load_indexed_python_cached_announce(
|
||||
&announce_cache_dir,
|
||||
announce_cache_index.as_ref(),
|
||||
&tp.packet_hash,
|
||||
) {
|
||||
Ok(Some(cached)) => cached,
|
||||
Ok(None) | Err(_) => {
|
||||
missing_cache += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if interface_name.is_none() {
|
||||
interface_name = cached.interface_reference.clone();
|
||||
}
|
||||
let next_hop = if tp.received_from == tp.destination_hash {
|
||||
None
|
||||
} else {
|
||||
Some(tp.received_from.to_vec())
|
||||
};
|
||||
paths.push(crate::persistence::PersistedTunnelPath {
|
||||
destination_hash: tp.destination_hash.to_vec(),
|
||||
next_hop,
|
||||
hops: tp.hops,
|
||||
expires: tp.expires,
|
||||
timestamp: tp.timestamp,
|
||||
random_blobs: tp
|
||||
.random_blobs
|
||||
.iter()
|
||||
.map(|blob| blob.to_vec())
|
||||
.collect(),
|
||||
packet_hash: Some(tp.packet_hash.to_vec()),
|
||||
});
|
||||
self.recent_announces
|
||||
.entry(tp.destination_hash)
|
||||
.or_insert_with(|| {
|
||||
recent_announce_from_cached_packet(
|
||||
tp.destination_hash,
|
||||
tp.hops,
|
||||
tp.timestamp,
|
||||
cached.raw_packet,
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
if paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if interface_name.is_none() && interface_hash.is_none() {
|
||||
legacy += 1;
|
||||
continue;
|
||||
}
|
||||
self.pending_tunnel_entries.push(
|
||||
crate::persistence::PersistedTunnelEntry {
|
||||
tunnel_id: te.tunnel_id.to_vec(),
|
||||
interface_id: 0,
|
||||
expires: te.expires,
|
||||
paths,
|
||||
interface_name,
|
||||
interface_hash,
|
||||
},
|
||||
);
|
||||
pending += 1;
|
||||
}
|
||||
debug!(
|
||||
total,
|
||||
pending, expired, missing_cache, legacy, "staged Python tunnel entries"
|
||||
);
|
||||
pending > 0
|
||||
}
|
||||
Err(e) => {
|
||||
trace!("failed to load Python tunnels table: {}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
// tunnel_table — legacy Rust sidecar fallback, defer remap.
|
||||
let tunnel_path = dir.join("tunnel_table.msgpack");
|
||||
if tunnel_path.exists() {
|
||||
if !loaded_python_tunnel_table && tunnel_path.exists() {
|
||||
match crate::persistence::load_tunnel_table(&tunnel_path) {
|
||||
Ok(entries) => {
|
||||
let total = entries.len();
|
||||
@@ -340,7 +718,7 @@ impl TransportActor {
|
||||
expired += 1;
|
||||
continue;
|
||||
}
|
||||
if te.interface_name.is_none() {
|
||||
if te.interface_name.is_none() && te.interface_hash.is_none() {
|
||||
legacy += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -361,58 +739,98 @@ impl TransportActor {
|
||||
// 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,
|
||||
});
|
||||
let loaded = match crate::persistence::load_announce_cache(&announce_path) {
|
||||
Ok(entries) => Some(entries),
|
||||
Err(v6_err) => {
|
||||
// Pre-v6 caches carried raw announce bytes inline. Migrate
|
||||
// them into per-packet disk cache files once, then proceed
|
||||
// with the slim v6 metadata shape.
|
||||
match crate::persistence::load_announce_cache_legacy_v5(&announce_path) {
|
||||
Ok(legacy) => {
|
||||
let announce_cache_dir = dir.join("cache").join("announces");
|
||||
let migrated = crate::persistence::migrate_legacy_announce_entries(
|
||||
legacy,
|
||||
&announce_cache_dir,
|
||||
);
|
||||
debug!(
|
||||
count = migrated.len(),
|
||||
"migrated legacy announce cache to disk-backed v6"
|
||||
);
|
||||
Some(migrated)
|
||||
}
|
||||
Err(_) => {
|
||||
trace!("failed to load announce cache: {}", v6_err);
|
||||
None
|
||||
}
|
||||
}
|
||||
debug!("loaded {} announce cache entries from disk", count);
|
||||
}
|
||||
Err(e) => {
|
||||
trace!("failed to load announce cache: {}", e);
|
||||
};
|
||||
if let Some(entries) = loaded {
|
||||
let count = entries.len();
|
||||
let mut expired = 0usize;
|
||||
for ae in entries {
|
||||
if ae.destination_hash.len() == 16 {
|
||||
let mut hash = [0u8; 16];
|
||||
hash.copy_from_slice(&ae.destination_hash);
|
||||
let stale_pathless = !ae.retained
|
||||
&& !self.recent_announces.contains_key(&hash)
|
||||
&& now_ts - ae.timestamp > DESTINATION_TIMEOUT as f64;
|
||||
if stale_pathless {
|
||||
expired += 1;
|
||||
continue;
|
||||
}
|
||||
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]
|
||||
};
|
||||
let packet_hash = ae.packet_hash.and_then(|h| {
|
||||
if h.len() == 32 {
|
||||
let mut arr = [0u8; 32];
|
||||
arr.copy_from_slice(&h);
|
||||
Some(arr)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
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,
|
||||
packet_hash,
|
||||
is_path_response: ae.is_path_response,
|
||||
retained: ae.retained,
|
||||
last_used: ae.last_used,
|
||||
name_hash,
|
||||
});
|
||||
}
|
||||
}
|
||||
debug!(count, expired, "loaded announce cache entries from disk");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -535,7 +953,11 @@ impl TransportActor {
|
||||
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) {
|
||||
let name_matches = te.interface_name.as_deref() == Some(name);
|
||||
let hash_matches = te.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 te.tunnel_id.len() != 32 {
|
||||
@@ -548,13 +970,46 @@ impl TransportActor {
|
||||
if tp.destination_hash.len() == 16 {
|
||||
let mut dest = [0u8; 16];
|
||||
dest.copy_from_slice(&tp.destination_hash);
|
||||
let next_hop = tp.next_hop.as_ref().and_then(|next_hop| {
|
||||
if next_hop.len() == 16 {
|
||||
let mut arr = [0u8; 16];
|
||||
arr.copy_from_slice(next_hop);
|
||||
Some(arr)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let packet_hash = tp.packet_hash.as_ref().and_then(|packet_hash| {
|
||||
if packet_hash.len() == 32 {
|
||||
let mut arr = [0u8; 32];
|
||||
arr.copy_from_slice(packet_hash);
|
||||
Some(arr)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let random_blobs = tp
|
||||
.random_blobs
|
||||
.iter()
|
||||
.filter_map(|blob| {
|
||||
if blob.len() == 10 {
|
||||
let mut arr = [0u8; 10];
|
||||
arr.copy_from_slice(blob);
|
||||
Some(arr)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
tunnel_paths.insert(
|
||||
dest,
|
||||
crate::tunnel::TunnelPath {
|
||||
timestamp: tp.timestamp,
|
||||
next_hop,
|
||||
hops: tp.hops,
|
||||
expires: tp.expires,
|
||||
random_blobs: vec![],
|
||||
random_blobs,
|
||||
packet_hash,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -591,3 +1046,112 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod async_save_tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_storage() -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"rns-async-save-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn dirty_actor(dir: &std::path::Path) -> TransportActor {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
actor.storage_dir = Some(dir.to_path_buf());
|
||||
actor.path_table.insert(
|
||||
[0x11; 16],
|
||||
crate::path_table::PathEntry {
|
||||
timestamp: crate::now_f64(),
|
||||
next_hop: Some([0x22; 16]),
|
||||
hops: 1,
|
||||
expires: crate::now_f64() + 600.0,
|
||||
random_blobs: std::collections::VecDeque::new(),
|
||||
interface_id: 7,
|
||||
packet_hash: Some([0x33; 32]),
|
||||
},
|
||||
);
|
||||
actor.state_dirty = true;
|
||||
actor
|
||||
}
|
||||
|
||||
/// The periodic save must never run the fsync chain on the actor: the
|
||||
/// tick path schedules to the blocking pool and returns immediately,
|
||||
/// clearing the dirty flag; the files appear once the pool task runs.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn periodic_save_writes_off_actor_and_clears_dirty() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
|
||||
actor.save_routing_state_async();
|
||||
assert!(!actor.state_dirty, "dirty clears at scheduling time");
|
||||
|
||||
let path = dir.join("path_table.msgpack");
|
||||
// Generous: the blocking pool competes with the whole suite's fsync
|
||||
// traffic on first run; the loop exits as soon as the file lands.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
while !path.exists() && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(path.exists(), "blocking-pool save must land on disk");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A save already in flight must NOT be raced by a second scheduling —
|
||||
/// the tmp-file names are shared. The skipped attempt keeps state_dirty
|
||||
/// set so the next interval retries.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn in_flight_save_skips_and_keeps_dirty() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
actor
|
||||
.routing_save_in_flight
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
|
||||
actor.save_routing_state_async();
|
||||
assert!(
|
||||
actor.state_dirty,
|
||||
"skipped save must leave state_dirty for retry"
|
||||
);
|
||||
assert!(!dir.join("path_table.msgpack").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The synchronous path (shutdown / falling edge) waits for an in-flight
|
||||
/// async save before writing, then completes inline.
|
||||
#[test]
|
||||
fn sync_save_waits_for_in_flight_then_writes() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
|
||||
let flag = actor.routing_save_in_flight.clone();
|
||||
flag.store(true, std::sync::atomic::Ordering::Release);
|
||||
let release = std::thread::spawn({
|
||||
let flag = flag.clone();
|
||||
move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||
flag.store(false, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
});
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
actor.save_routing_state();
|
||||
release.join().unwrap();
|
||||
|
||||
assert!(
|
||||
started.elapsed() >= std::time::Duration::from_millis(140),
|
||||
"sync save must wait out the in-flight writer"
|
||||
);
|
||||
assert!(dir.join("path_table.msgpack").exists());
|
||||
assert!(!actor.state_dirty);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::now_f64;
|
||||
|
||||
impl TransportActor {
|
||||
pub(super) fn handle_query(
|
||||
@@ -10,7 +11,7 @@ impl TransportActor {
|
||||
TransportQuery::GetPathTable => {
|
||||
let entries: Vec<PathTableRpcEntry> = self
|
||||
.path_table
|
||||
.iter()
|
||||
.iter_live()
|
||||
.map(|(hash, entry)| {
|
||||
let iface_name = self
|
||||
.interfaces
|
||||
@@ -24,12 +25,24 @@ impl TransportActor {
|
||||
hops: entry.hops,
|
||||
expires: entry.expires,
|
||||
interface: iface_name,
|
||||
interface_id: entry.interface_id,
|
||||
interface_mode: self
|
||||
.interfaces
|
||||
.get(&entry.interface_id)
|
||||
.map(|e| e.mode)
|
||||
.unwrap_or(crate::constants::InterfaceMode::Full),
|
||||
interface_role: self
|
||||
.interfaces
|
||||
.get(&entry.interface_id)
|
||||
.map(|e| e.role)
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
TransportQueryResponse::PathTable(entries)
|
||||
}
|
||||
TransportQuery::GetInterfaceStats => {
|
||||
let now = now_f64();
|
||||
let stats: Vec<InterfaceStatRpcEntry> = self
|
||||
.interfaces
|
||||
.iter()
|
||||
@@ -66,7 +79,23 @@ impl TransportActor {
|
||||
incoming_announce_frequency: entry
|
||||
.ingress
|
||||
.incoming_announce_frequency(),
|
||||
outgoing_announce_frequency: 0.0,
|
||||
outgoing_announce_frequency: entry
|
||||
.ingress
|
||||
.outgoing_announce_frequency(),
|
||||
incoming_pr_frequency: entry.ingress.incoming_pr_frequency(),
|
||||
outgoing_pr_frequency: entry.ingress.outgoing_pr_frequency(),
|
||||
burst_active: entry.ingress.is_burst_active(),
|
||||
burst_activated: activation_epoch(
|
||||
now,
|
||||
entry.ingress.is_burst_active(),
|
||||
entry.ingress.burst_activated(),
|
||||
),
|
||||
pr_burst_active: entry.ingress.is_pr_burst_active(),
|
||||
pr_burst_activated: activation_epoch(
|
||||
now,
|
||||
entry.ingress.is_pr_burst_active(),
|
||||
entry.ingress.pr_burst_activated(),
|
||||
),
|
||||
clients: None,
|
||||
announce_rate_target: entry.announce_rate_target,
|
||||
announce_rate_grace: entry.announce_rate_grace,
|
||||
@@ -101,14 +130,19 @@ impl TransportActor {
|
||||
let mut entries: Vec<AnnounceRpcEntry> = self
|
||||
.recent_announces
|
||||
.values()
|
||||
.map(|a| AnnounceRpcEntry {
|
||||
dest_hash: a.dest_hash,
|
||||
hops: a.hops,
|
||||
app_data: a.app_data.clone(),
|
||||
timestamp: a.timestamp,
|
||||
public_key: a.public_key,
|
||||
ratchet: a.ratchet,
|
||||
retained: a.retained,
|
||||
.map(|a| {
|
||||
let is_path_response = a.is_path_response;
|
||||
AnnounceRpcEntry {
|
||||
dest_hash: a.dest_hash,
|
||||
hops: a.hops,
|
||||
app_data: a.app_data.clone(),
|
||||
timestamp: a.timestamp,
|
||||
public_key: a.public_key,
|
||||
ratchet: a.ratchet,
|
||||
name_hash: a.name_hash,
|
||||
is_path_response,
|
||||
retained: a.retained,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// HashMap iteration order is unspecified; sort newest-first
|
||||
@@ -122,13 +156,13 @@ impl TransportActor {
|
||||
TransportQueryResponse::Announces(entries)
|
||||
}
|
||||
TransportQuery::GetNextHop { dest } => {
|
||||
let next_hop = self.path_table.get(&dest).and_then(|e| e.next_hop);
|
||||
let next_hop = self.path_table.get_live(&dest).and_then(|e| e.next_hop);
|
||||
TransportQueryResponse::HashResult(next_hop)
|
||||
}
|
||||
TransportQuery::GetNextHopIfName { dest } => {
|
||||
let name = self
|
||||
.path_table
|
||||
.get(&dest)
|
||||
.get_live(&dest)
|
||||
.and_then(|e| self.interfaces.get(&e.interface_id).map(|i| i.name.clone()));
|
||||
TransportQueryResponse::StringResult(name)
|
||||
}
|
||||
@@ -157,12 +191,48 @@ impl TransportActor {
|
||||
self.state_dirty = true;
|
||||
TransportQueryResponse::Ok
|
||||
}
|
||||
TransportQuery::SuppressPathInterface {
|
||||
dest,
|
||||
interface_id,
|
||||
duration,
|
||||
} => TransportQueryResponse::BoolResult(self.suppress_path_interface(
|
||||
dest,
|
||||
interface_id,
|
||||
duration,
|
||||
)),
|
||||
TransportQuery::SuppressCurrentPathInterface { dest, duration } => {
|
||||
let interface_id = self
|
||||
.path_table
|
||||
.get_live(&dest)
|
||||
.map(|entry| entry.interface_id);
|
||||
TransportQueryResponse::BoolResult(interface_id.is_some_and(|interface_id| {
|
||||
self.suppress_path_interface(dest, interface_id, duration)
|
||||
}))
|
||||
}
|
||||
TransportQuery::DropAnnounceQueues => {
|
||||
for entry in self.interfaces.values_mut() {
|
||||
entry.announce_queue.clear();
|
||||
}
|
||||
TransportQueryResponse::Ok
|
||||
}
|
||||
TransportQuery::DropPathTable => {
|
||||
let cleared = self.path_table.len();
|
||||
self.path_table = crate::path_table::PathTable::new();
|
||||
self.pending_path_entries.clear();
|
||||
self.discovery_path_requests.clear();
|
||||
self.pending_local_path_requests.clear();
|
||||
self.pending_discovery_prs.clear();
|
||||
self.state_dirty = true;
|
||||
self.save_routing_state();
|
||||
TransportQueryResponse::IntResult(cleared as i64)
|
||||
}
|
||||
TransportQuery::DropRecentAnnounces => {
|
||||
let cleared = self.recent_announces.len();
|
||||
self.recent_announces.clear();
|
||||
self.state_dirty = true;
|
||||
self.save_routing_state();
|
||||
TransportQueryResponse::IntResult(cleared as i64)
|
||||
}
|
||||
TransportQuery::GetBlackholedIdentities => {
|
||||
// Snapshot of identity hashes we have a current announce for —
|
||||
// used to decorate each entry with `verified`.
|
||||
@@ -386,19 +456,22 @@ impl TransportActor {
|
||||
TransportQuery::GetNextHopBitrate { dest } => {
|
||||
let bitrate = self
|
||||
.path_table
|
||||
.get(&dest)
|
||||
.get_live(&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);
|
||||
let id = self
|
||||
.path_table
|
||||
.get_live(&dest)
|
||||
.map(|e| e.interface_id as i64);
|
||||
TransportQueryResponse::IntResult(id.unwrap_or(-1))
|
||||
}
|
||||
TransportQuery::FirstHopTimeout { dest } => {
|
||||
let timeout = self
|
||||
.path_table
|
||||
.get(&dest)
|
||||
.get_live(&dest)
|
||||
.and_then(|e| self.interfaces.get(&e.interface_id))
|
||||
.map(|iface| {
|
||||
let per_byte_latency = 8.0 / iface.bitrate as f64;
|
||||
@@ -521,3 +594,11 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn activation_epoch(now: f64, active: bool, activated: std::time::Instant) -> f64 {
|
||||
if active {
|
||||
now - activated.elapsed().as_secs_f64()
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ pub struct AnnounceEntry {
|
||||
pub received_from: [u8; 16],
|
||||
/// Hop count as observed on receipt.
|
||||
pub hops: u8,
|
||||
/// Outbound packet bytes with the hop count already incremented.
|
||||
/// Outbound packet bytes with the Python-parity inbound-adjusted hop count.
|
||||
pub packet_raw: Vec<u8>,
|
||||
/// Count of duplicate rebroadcasts heard from neighbours — used to suppress flooding.
|
||||
pub local_rebroadcasts: u32,
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//!
|
||||
//! Mirrors Python `Transport.await_path(destination_hash, timeout=None)`
|
||||
//! (RNS/Transport.py:2524). The helper sends an [`AwaitPath`] actor
|
||||
//! message and races the oneshot reply against a caller-supplied timeout.
|
||||
//! message and races the oneshot reply against a caller-supplied timeout. The
|
||||
//! actor emits the upstream-compatible path request before parking the waiter.
|
||||
//!
|
||||
//! [`AwaitPath`]: crate::messages::TransportMessage::AwaitPath
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rns_wire::types::IdentityHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -64,6 +63,7 @@ impl BlackholeEntry {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BlackholeTable {
|
||||
entries: HashMap<IdentityHash, BlackholeEntry>,
|
||||
}
|
||||
@@ -87,10 +87,7 @@ impl BlackholeTable {
|
||||
ttl: Option<f64>,
|
||||
reason: BlackholeReason,
|
||||
) {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
self.entries.insert(
|
||||
identity_hash.into(),
|
||||
@@ -111,10 +108,7 @@ impl BlackholeTable {
|
||||
reason: BlackholeReason,
|
||||
reason_label: Option<String>,
|
||||
) {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
self.entries.insert(
|
||||
identity_hash.into(),
|
||||
@@ -163,10 +157,7 @@ impl BlackholeTable {
|
||||
match self.entries.get(identity_hash) {
|
||||
Some(entry) => {
|
||||
if let Some(ttl) = entry.ttl {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
now - entry.created < ttl
|
||||
} else {
|
||||
true
|
||||
@@ -183,10 +174,7 @@ impl BlackholeTable {
|
||||
|
||||
/// Drop entries whose TTL has elapsed; returns the number removed.
|
||||
pub fn cull_expired(&mut self) -> usize {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
let before = self.entries.len();
|
||||
self.entries
|
||||
|
||||
@@ -53,6 +53,12 @@ pub const PATH_REQUEST_TIMEOUT: f64 = 15.0;
|
||||
/// Duplicate inbound path request tag retention (seconds).
|
||||
pub const PATH_REQUEST_GATE_TIMEOUT: f64 = 120.0;
|
||||
|
||||
/// Maximum queued automatic discovery path requests after failed link setup.
|
||||
pub const MAX_QUEUED_DISCOVERY_PRS: usize = 32;
|
||||
|
||||
/// Minimum spacing between queued discovery path-request transmissions.
|
||||
pub const DISCOVERY_PR_TX_THROTTLE: f64 = 0.5;
|
||||
|
||||
/// Grace before path response (seconds).
|
||||
pub const PATH_REQUEST_GRACE: f64 = 0.4;
|
||||
|
||||
@@ -76,7 +82,20 @@ pub const JOB_INTERVAL_BG_MS: u64 = 2000;
|
||||
/// Cadence at which `on_tick` flushes routing-state files (path_table,
|
||||
/// announce_cache, blackhole, tunnel_table) when dirty. Hashlist is excluded
|
||||
/// (multi-MB on busy hubs); it saves on shutdown + foreground→background.
|
||||
pub const STATE_SAVE_INTERVAL_SECS: f64 = 10.0;
|
||||
/// Matches Python `Reticulum.GRACIOUS_PERSIST_INTERVAL` (5 min). On a live
|
||||
/// announce feed the dirty bit is effectively always set, so this interval
|
||||
/// IS the flush rate — at 10s the full-state clone+serialize+fsync cycle
|
||||
/// dominated daemon RSS via allocator churn. Abrupt-exit safety comes from
|
||||
/// the falling-edge save and `on_shutdown`, not from this cadence.
|
||||
pub const STATE_SAVE_INTERVAL_SECS: f64 = 300.0;
|
||||
|
||||
/// Python `Transport.UNUSED_DESTINATION_LINGER`: never-used destinations
|
||||
/// without a path are dropped from the announce cache after this idle time.
|
||||
pub const UNUSED_DESTINATION_LINGER: f64 = 360.0;
|
||||
|
||||
/// Python `Transport.max_pr_tags`: hard count cap on the discovery
|
||||
/// path-request tag gate, on top of the time-based retain.
|
||||
pub const MAX_DISCOVERY_PR_TAGS: usize = 32_000;
|
||||
|
||||
/// Link table check interval.
|
||||
pub const LINKS_CHECK_INTERVAL: f64 = 1.0;
|
||||
@@ -116,41 +135,77 @@ pub const ANNOUNCE_CAP: f64 = 0.02;
|
||||
pub const MAX_HELD_ANNOUNCES: usize = 256;
|
||||
|
||||
/// Held announce release interval (seconds).
|
||||
/// Matches Python 1.2.4 `Interface.IC_HELD_RELEASE_INTERVAL = 2`.
|
||||
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
|
||||
/// Matches Python 1.2.5 `Interface.IC_HELD_RELEASE_INTERVAL = 5`.
|
||||
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
|
||||
|
||||
/// Incoming announce frequency window samples.
|
||||
/// Matches Python 1.2.4 `Interface.IA_FREQ_SAMPLES = 128`.
|
||||
pub const IA_FREQ_SAMPLES: usize = 128;
|
||||
/// Matches Python 1.2.5 `Interface.IA_FREQ_SAMPLES = 48`.
|
||||
pub const IA_FREQ_SAMPLES: usize = 48;
|
||||
|
||||
/// Outgoing announce frequency window samples.
|
||||
/// Matches Python 1.2.4 `Interface.OA_FREQ_SAMPLES = 128`.
|
||||
pub const OA_FREQ_SAMPLES: usize = 128;
|
||||
/// Matches Python 1.2.5 `Interface.OA_FREQ_SAMPLES = 48`.
|
||||
pub const OA_FREQ_SAMPLES: usize = 48;
|
||||
|
||||
/// Incoming path-request frequency window samples.
|
||||
/// Matches Python 1.2.5 `Interface.IP_FREQ_SAMPLES = 48`.
|
||||
pub const IP_FREQ_SAMPLES: usize = 48;
|
||||
|
||||
/// Outgoing path-request frequency window samples.
|
||||
/// Matches Python 1.2.5 `Interface.OP_FREQ_SAMPLES = 48`.
|
||||
pub const OP_FREQ_SAMPLES: usize = 48;
|
||||
|
||||
/// Minimum non-zero announce frequency represented by the decay window.
|
||||
pub const AR_MINFREQ_HZ: f64 = 0.1;
|
||||
|
||||
/// Minimum non-zero path-request frequency represented by the decay window.
|
||||
pub const PR_MINFREQ_HZ: f64 = 0.1;
|
||||
|
||||
/// Frequency decay window for announces (seconds).
|
||||
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
|
||||
|
||||
/// Frequency decay window for path requests (seconds).
|
||||
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
|
||||
|
||||
/// Minimum samples required before frequency is considered defined.
|
||||
/// Matches Python 1.2.4 `Interface.IC_DEQUE_MIN_SAMPLE = 32`.
|
||||
pub const IC_DEQUE_MIN_SAMPLE: usize = 32;
|
||||
/// Matches Python 1.2.5 `Interface.IC_DEQUE_MIN_SAMPLE = 2`.
|
||||
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
|
||||
|
||||
/// Minimum samples required for burst state clearing / egress PR limiting.
|
||||
/// Matches Python 1.2.5 `Interface.IC_BURST_MIN_SAMPLES = 6`.
|
||||
pub const IC_BURST_MIN_SAMPLES: usize = 6;
|
||||
|
||||
/// Duration interface is treated as "new" (seconds).
|
||||
/// Matches Python `Interface.IC_NEW_TIME = 2*60*60`.
|
||||
pub const IC_NEW_TIME: f64 = 7200.0;
|
||||
|
||||
/// Burst threshold for new interfaces (announces/sec).
|
||||
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ_NEW = 6`.
|
||||
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
|
||||
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ_NEW = 3`.
|
||||
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
|
||||
|
||||
/// Burst threshold for established interfaces (announces/sec).
|
||||
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ = 35`.
|
||||
pub const IC_BURST_FREQ: f64 = 35.0;
|
||||
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ = 10`.
|
||||
pub const IC_BURST_FREQ: f64 = 10.0;
|
||||
|
||||
/// Path-request burst threshold for new interfaces (requests/sec).
|
||||
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
|
||||
|
||||
/// Path-request burst threshold for established interfaces (requests/sec).
|
||||
pub const IC_PR_BURST_FREQ: f64 = 8.0;
|
||||
|
||||
/// Burst detection active duration (seconds).
|
||||
/// Matches Python `Interface.IC_BURST_HOLD = 1*60`.
|
||||
pub const IC_BURST_HOLD: f64 = 60.0;
|
||||
/// Matches Python 1.2.5 `Interface.IC_BURST_HOLD = 15`.
|
||||
pub const IC_BURST_HOLD: f64 = 15.0;
|
||||
|
||||
/// Burst penalty delay (seconds).
|
||||
/// Matches Python 1.2.4 `Interface.IC_BURST_PENALTY = 15`.
|
||||
/// Matches Python 1.2.5 `Interface.IC_BURST_PENALTY = 15`.
|
||||
pub const IC_BURST_PENALTY: f64 = 15.0;
|
||||
|
||||
/// Optional outgoing path-request limiter threshold (requests/sec).
|
||||
pub const EC_PR_FREQ: f64 = 5.0;
|
||||
|
||||
/// Whether outgoing path-request limiting is active by default.
|
||||
pub const EGRESS_CONTROL: bool = false;
|
||||
|
||||
/// Tunnel timeout (8 hours, in seconds).
|
||||
/// Matches Python 1.1.6 `Transport.TUNNEL_TIMEOUT = 60*60*8`.
|
||||
pub const TUNNEL_TIMEOUT: u64 = 28_800;
|
||||
|
||||
@@ -488,9 +488,6 @@ mod tests {
|
||||
}
|
||||
|
||||
fn now_seconds() -> f64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs_f64()
|
||||
crate::now_f64()
|
||||
}
|
||||
}
|
||||
@@ -203,10 +203,7 @@ pub fn spawn(config: ReceiverConfig) -> (JoinHandle<()>, mpsc::Sender<AnnounceHa
|
||||
}
|
||||
|
||||
fn now_unix() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
crate::now_f64() as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rmpv::Value;
|
||||
use thiserror::Error;
|
||||
@@ -231,10 +230,7 @@ pub fn classify(heard_delta_secs: u64) -> DiscoveryStatus {
|
||||
}
|
||||
|
||||
fn unix_now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
crate::now_f64() as u64
|
||||
}
|
||||
|
||||
// On-disk msgpack format mirrors Python's key schema for interop.
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::constants::HASHLIST_MAXSIZE;
|
||||
/// 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.
|
||||
#[derive(Clone)]
|
||||
pub struct PacketHashlist {
|
||||
current: HashSet<[u8; 32]>,
|
||||
previous: HashSet<[u8; 32]>,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Per-interface ingress control: announce flood protection.
|
||||
//! Per-interface ingress/egress control for announce and path-request floods.
|
||||
//!
|
||||
//! Each interface owns one `IngressController`. The inbound path consults it
|
||||
//! on every announce — when the incoming rate crosses the burst threshold the
|
||||
@@ -15,9 +15,10 @@ 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,
|
||||
AR_FREQ_DECAY, EC_PR_FREQ, EGRESS_CONTROL, IA_FREQ_SAMPLES, IC_BURST_FREQ, IC_BURST_FREQ_NEW,
|
||||
IC_BURST_HOLD, IC_BURST_MIN_SAMPLES, IC_BURST_PENALTY, IC_DEQUE_MIN_SAMPLE,
|
||||
IC_HELD_RELEASE_INTERVAL, IC_NEW_TIME, IC_PR_BURST_FREQ, IC_PR_BURST_FREQ_NEW, IP_FREQ_SAMPLES,
|
||||
MAX_HELD_ANNOUNCES, OA_FREQ_SAMPLES, OP_FREQ_SAMPLES, PR_FREQ_DECAY,
|
||||
};
|
||||
|
||||
/// Per-interface ingress overrides parsed from `[interface.<name>] ic_*` keys.
|
||||
@@ -27,11 +28,15 @@ pub struct IngressOverrides {
|
||||
pub enabled: Option<bool>,
|
||||
pub burst_freq_new: Option<f64>,
|
||||
pub burst_freq: Option<f64>,
|
||||
pub pr_burst_freq_new: Option<f64>,
|
||||
pub pr_burst_freq: Option<f64>,
|
||||
pub new_time: Option<f64>,
|
||||
pub burst_hold: Option<f64>,
|
||||
pub burst_penalty: Option<f64>,
|
||||
pub max_held: Option<usize>,
|
||||
pub held_release_interval: Option<f64>,
|
||||
pub ec_pr_freq: Option<f64>,
|
||||
pub egress_control: Option<bool>,
|
||||
}
|
||||
|
||||
impl IngressOverrides {
|
||||
@@ -39,11 +44,15 @@ impl IngressOverrides {
|
||||
self.enabled.is_none()
|
||||
&& self.burst_freq_new.is_none()
|
||||
&& self.burst_freq.is_none()
|
||||
&& self.pr_burst_freq_new.is_none()
|
||||
&& self.pr_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()
|
||||
&& self.ec_pr_freq.is_none()
|
||||
&& self.egress_control.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,19 +74,29 @@ pub struct IngressController {
|
||||
ia_freq_deque: VecDeque<Instant>,
|
||||
/// Outgoing announce timestamps; capped at `OA_FREQ_SAMPLES`.
|
||||
oa_freq_deque: VecDeque<Instant>,
|
||||
/// Incoming path-request timestamps; capped at `IP_FREQ_SAMPLES`.
|
||||
ip_freq_deque: VecDeque<Instant>,
|
||||
/// Outgoing path-request timestamps; capped at `OP_FREQ_SAMPLES`.
|
||||
op_freq_deque: VecDeque<Instant>,
|
||||
burst_active: bool,
|
||||
burst_activated: Instant,
|
||||
pr_burst_active: bool,
|
||||
pr_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,
|
||||
pr_burst_freq_new: f64,
|
||||
pr_burst_freq: f64,
|
||||
new_time: f64,
|
||||
burst_hold: f64,
|
||||
burst_penalty: f64,
|
||||
max_held: usize,
|
||||
held_release_interval: f64,
|
||||
ec_pr_freq: f64,
|
||||
egress_control: bool,
|
||||
}
|
||||
|
||||
impl IngressController {
|
||||
@@ -88,17 +107,25 @@ impl IngressController {
|
||||
enabled: true,
|
||||
ia_freq_deque: VecDeque::with_capacity(IA_FREQ_SAMPLES),
|
||||
oa_freq_deque: VecDeque::with_capacity(OA_FREQ_SAMPLES),
|
||||
ip_freq_deque: VecDeque::with_capacity(IP_FREQ_SAMPLES),
|
||||
op_freq_deque: VecDeque::with_capacity(OP_FREQ_SAMPLES),
|
||||
burst_active: false,
|
||||
burst_activated: now,
|
||||
pr_burst_active: false,
|
||||
pr_burst_activated: now,
|
||||
held_release: now,
|
||||
held_announces: HashMap::new(),
|
||||
burst_freq_new: IC_BURST_FREQ_NEW,
|
||||
burst_freq: IC_BURST_FREQ,
|
||||
pr_burst_freq_new: IC_PR_BURST_FREQ_NEW,
|
||||
pr_burst_freq: IC_PR_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,
|
||||
ec_pr_freq: EC_PR_FREQ,
|
||||
egress_control: EGRESS_CONTROL,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +152,12 @@ impl IngressController {
|
||||
if let Some(v) = overrides.burst_freq {
|
||||
ctrl.burst_freq = v;
|
||||
}
|
||||
if let Some(v) = overrides.pr_burst_freq_new {
|
||||
ctrl.pr_burst_freq_new = v;
|
||||
}
|
||||
if let Some(v) = overrides.pr_burst_freq {
|
||||
ctrl.pr_burst_freq = v;
|
||||
}
|
||||
if let Some(v) = overrides.new_time {
|
||||
ctrl.new_time = v;
|
||||
}
|
||||
@@ -140,6 +173,12 @@ impl IngressController {
|
||||
if let Some(v) = overrides.held_release_interval {
|
||||
ctrl.held_release_interval = v;
|
||||
}
|
||||
if let Some(v) = overrides.ec_pr_freq {
|
||||
ctrl.ec_pr_freq = v;
|
||||
}
|
||||
if let Some(v) = overrides.egress_control {
|
||||
ctrl.egress_control = v;
|
||||
}
|
||||
ctrl
|
||||
}
|
||||
|
||||
@@ -151,6 +190,22 @@ impl IngressController {
|
||||
self.burst_freq_new
|
||||
}
|
||||
|
||||
pub fn pr_burst_freq(&self) -> f64 {
|
||||
self.pr_burst_freq
|
||||
}
|
||||
|
||||
pub fn pr_burst_freq_new(&self) -> f64 {
|
||||
self.pr_burst_freq_new
|
||||
}
|
||||
|
||||
pub fn ec_pr_freq(&self) -> f64 {
|
||||
self.ec_pr_freq
|
||||
}
|
||||
|
||||
pub fn is_egress_control_enabled(&self) -> bool {
|
||||
self.egress_control
|
||||
}
|
||||
|
||||
pub fn held_release_interval(&self) -> f64 {
|
||||
self.held_release_interval
|
||||
}
|
||||
@@ -171,27 +226,51 @@ impl IngressController {
|
||||
}
|
||||
|
||||
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);
|
||||
push_sample(&mut self.ia_freq_deque, IA_FREQ_SAMPLES, Instant::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);
|
||||
push_sample(&mut self.oa_freq_deque, OA_FREQ_SAMPLES, Instant::now());
|
||||
}
|
||||
|
||||
pub fn received_path_request(&mut self) {
|
||||
push_sample(&mut self.ip_freq_deque, IP_FREQ_SAMPLES, Instant::now());
|
||||
}
|
||||
|
||||
pub fn sent_path_request(&mut self) {
|
||||
push_sample(&mut self.op_freq_deque, OP_FREQ_SAMPLES, Instant::now());
|
||||
}
|
||||
|
||||
pub fn incoming_announce_frequency(&self) -> f64 {
|
||||
frequency_from_deque(&self.ia_freq_deque)
|
||||
frequency_from_deque(
|
||||
&self.ia_freq_deque,
|
||||
IC_DEQUE_MIN_SAMPLE,
|
||||
Duration::from_secs_f64(AR_FREQ_DECAY),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn outgoing_announce_frequency(&self) -> f64 {
|
||||
frequency_from_deque(&self.oa_freq_deque)
|
||||
frequency_from_deque(
|
||||
&self.oa_freq_deque,
|
||||
1,
|
||||
Duration::from_secs_f64(AR_FREQ_DECAY),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn incoming_pr_frequency(&self) -> f64 {
|
||||
frequency_from_deque(
|
||||
&self.ip_freq_deque,
|
||||
IC_DEQUE_MIN_SAMPLE,
|
||||
Duration::from_secs_f64(PR_FREQ_DECAY),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn outgoing_pr_frequency(&self) -> f64 {
|
||||
frequency_from_deque(
|
||||
&self.op_freq_deque,
|
||||
1,
|
||||
Duration::from_secs_f64(PR_FREQ_DECAY),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether inbound announces should currently be held. Also updates the
|
||||
@@ -209,13 +288,18 @@ impl IngressController {
|
||||
self.burst_freq
|
||||
};
|
||||
|
||||
let ia_freq = self.incoming_announce_frequency();
|
||||
let ia_freq = frequency_from_deque_mut(
|
||||
&mut self.ia_freq_deque,
|
||||
IC_DEQUE_MIN_SAMPLE,
|
||||
Duration::from_secs_f64(AR_FREQ_DECAY),
|
||||
);
|
||||
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.ia_freq_deque.len() >= IC_BURST_MIN_SAMPLES
|
||||
{
|
||||
self.burst_active = false;
|
||||
}
|
||||
@@ -230,6 +314,58 @@ impl IngressController {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether unknown recursive path-request discovery should be suppressed
|
||||
/// on this ingress interface.
|
||||
pub fn should_ingress_limit_pr(&mut self) -> bool {
|
||||
if !self.enabled {
|
||||
return false;
|
||||
}
|
||||
|
||||
let freq_threshold = if self.age() < self.new_time {
|
||||
self.pr_burst_freq_new
|
||||
} else {
|
||||
self.pr_burst_freq
|
||||
};
|
||||
|
||||
let ip_freq = frequency_from_deque_mut(
|
||||
&mut self.ip_freq_deque,
|
||||
IC_DEQUE_MIN_SAMPLE,
|
||||
Duration::from_secs_f64(PR_FREQ_DECAY),
|
||||
);
|
||||
let now = Instant::now();
|
||||
|
||||
if self.pr_burst_active {
|
||||
if ip_freq < freq_threshold
|
||||
&& now.duration_since(self.pr_burst_activated)
|
||||
> Duration::from_secs_f64(self.burst_hold)
|
||||
{
|
||||
self.pr_burst_active = false;
|
||||
}
|
||||
true
|
||||
} else if ip_freq > freq_threshold {
|
||||
self.pr_burst_active = true;
|
||||
self.pr_burst_activated = now;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether outgoing path-request transmission should be skipped on this
|
||||
/// interface. This limiter is off by default in Reticulum 1.2.5.
|
||||
pub fn should_egress_limit_pr(&mut self) -> bool {
|
||||
if !self.egress_control {
|
||||
return false;
|
||||
}
|
||||
|
||||
let op_freq = frequency_from_deque_mut(
|
||||
&mut self.op_freq_deque,
|
||||
1,
|
||||
Duration::from_secs_f64(PR_FREQ_DECAY),
|
||||
);
|
||||
op_freq > self.ec_pr_freq && self.op_freq_deque.len() >= IC_BURST_MIN_SAMPLES
|
||||
}
|
||||
|
||||
pub fn hold_announce(&mut self, announce: HeldAnnounce) {
|
||||
if self.held_announces.contains_key(&announce.destination_hash)
|
||||
|| self.held_announces.len() < self.max_held
|
||||
@@ -240,11 +376,12 @@ impl IngressController {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// hop count, so short-path announces win priority. This intentionally
|
||||
/// does not consult `should_ingress_limit()`: upstream releases held
|
||||
/// announces based on release time and current announce frequency, even if
|
||||
/// the displayed burst state has not cleared yet.
|
||||
pub fn try_release_held(&mut self) -> Option<HeldAnnounce> {
|
||||
if self.should_ingress_limit() || self.held_announces.is_empty() {
|
||||
if self.held_announces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -259,7 +396,12 @@ impl IngressController {
|
||||
self.burst_freq
|
||||
};
|
||||
|
||||
if self.incoming_announce_frequency() >= freq_threshold {
|
||||
let ia_freq = frequency_from_deque_mut(
|
||||
&mut self.ia_freq_deque,
|
||||
IC_DEQUE_MIN_SAMPLE,
|
||||
Duration::from_secs_f64(AR_FREQ_DECAY),
|
||||
);
|
||||
if ia_freq >= freq_threshold {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -281,6 +423,18 @@ impl IngressController {
|
||||
pub fn is_burst_active(&self) -> bool {
|
||||
self.burst_active
|
||||
}
|
||||
|
||||
pub fn burst_activated(&self) -> Instant {
|
||||
self.burst_activated
|
||||
}
|
||||
|
||||
pub fn is_pr_burst_active(&self) -> bool {
|
||||
self.pr_burst_active
|
||||
}
|
||||
|
||||
pub fn pr_burst_activated(&self) -> Instant {
|
||||
self.pr_burst_activated
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for IngressController {
|
||||
@@ -289,32 +443,118 @@ impl Default for IngressController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Instant>) -> f64 {
|
||||
fn push_sample(deque: &mut VecDeque<Instant>, cap: usize, now: Instant) {
|
||||
if deque.len() >= cap {
|
||||
deque.pop_front();
|
||||
}
|
||||
deque.push_back(now);
|
||||
}
|
||||
|
||||
/// Snapshot frequency over a timestamp deque. Stale samples are ignored for
|
||||
/// observability without mutating the controller from read-only status paths.
|
||||
fn frequency_from_deque(deque: &VecDeque<Instant>, min_samples: usize, decay: Duration) -> f64 {
|
||||
let now = Instant::now();
|
||||
let oldest = deque
|
||||
.iter()
|
||||
.find(|sample| sample_age(now, **sample) <= decay);
|
||||
let Some(oldest) = oldest else {
|
||||
return 0.0;
|
||||
};
|
||||
let n = deque
|
||||
.iter()
|
||||
.filter(|sample| sample_age(now, **sample) <= decay)
|
||||
.count();
|
||||
frequency_from_parts(n, now, *oldest, min_samples)
|
||||
}
|
||||
|
||||
/// Mutable limiter frequency. Mirrors upstream's decay side effect by dropping
|
||||
/// one stale oldest sample when the observed window is older than the decay
|
||||
/// horizon, then calculating from the current sample count and oldest span.
|
||||
fn frequency_from_deque_mut(
|
||||
deque: &mut VecDeque<Instant>,
|
||||
min_samples: usize,
|
||||
decay: Duration,
|
||||
) -> f64 {
|
||||
let n = deque.len();
|
||||
if n <= IC_DEQUE_MIN_SAMPLE {
|
||||
if n <= min_samples {
|
||||
return 0.0;
|
||||
}
|
||||
let span = match deque.front() {
|
||||
Some(oldest) => oldest.elapsed().as_secs_f64(),
|
||||
None => return 0.0,
|
||||
let now = Instant::now();
|
||||
let Some(oldest) = deque.front().copied() else {
|
||||
return 0.0;
|
||||
};
|
||||
if sample_age(now, oldest) > decay {
|
||||
deque.pop_front();
|
||||
}
|
||||
frequency_from_parts(n, now, oldest, min_samples)
|
||||
}
|
||||
|
||||
fn frequency_from_parts(n: usize, now: Instant, oldest: Instant, min_samples: usize) -> f64 {
|
||||
if n <= min_samples {
|
||||
return 0.0;
|
||||
}
|
||||
let span = sample_age(now, oldest).as_secs_f64();
|
||||
if span <= 0.0 { 0.0 } else { n as f64 / span }
|
||||
}
|
||||
|
||||
fn sample_age(now: Instant, sample: Instant) -> Duration {
|
||||
now.checked_duration_since(sample)
|
||||
.unwrap_or_else(|| Duration::from_secs(0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn push_samples(
|
||||
deque: &mut VecDeque<Instant>,
|
||||
cap: usize,
|
||||
count: usize,
|
||||
oldest_age: f64,
|
||||
spacing: f64,
|
||||
) {
|
||||
let now = Instant::now();
|
||||
for i in 0..count {
|
||||
let age = oldest_age - (i as f64 * spacing);
|
||||
push_sample(deque, cap, now - Duration::from_secs_f64(age.max(0.0)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reticulum_125_control_constants_are_pinned() {
|
||||
assert_eq!(IA_FREQ_SAMPLES, 48);
|
||||
assert_eq!(OA_FREQ_SAMPLES, 48);
|
||||
assert_eq!(IP_FREQ_SAMPLES, 48);
|
||||
assert_eq!(OP_FREQ_SAMPLES, 48);
|
||||
assert_eq!(AR_FREQ_DECAY, 10.0);
|
||||
assert_eq!(PR_FREQ_DECAY, 10.0);
|
||||
assert_eq!(IC_DEQUE_MIN_SAMPLE, 2);
|
||||
assert_eq!(IC_BURST_MIN_SAMPLES, 6);
|
||||
assert_eq!(IC_BURST_FREQ_NEW, 3.0);
|
||||
assert_eq!(IC_BURST_FREQ, 10.0);
|
||||
assert_eq!(IC_PR_BURST_FREQ_NEW, 3.0);
|
||||
assert_eq!(IC_PR_BURST_FREQ, 8.0);
|
||||
assert_eq!(IC_BURST_HOLD, 15.0);
|
||||
assert_eq!(IC_BURST_PENALTY, 15.0);
|
||||
assert_eq!(IC_HELD_RELEASE_INTERVAL, 5.0);
|
||||
assert_eq!(EC_PR_FREQ, 5.0);
|
||||
const { assert!(!EGRESS_CONTROL) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ingress_controller_default_state() {
|
||||
let ctrl = IngressController::new();
|
||||
assert!(ctrl.is_enabled());
|
||||
assert!(!ctrl.is_burst_active());
|
||||
assert!(!ctrl.is_pr_burst_active());
|
||||
assert!(!ctrl.is_egress_control_enabled());
|
||||
assert_eq!(ctrl.pr_burst_freq_new(), IC_PR_BURST_FREQ_NEW);
|
||||
assert_eq!(ctrl.pr_burst_freq(), IC_PR_BURST_FREQ);
|
||||
assert_eq!(ctrl.ec_pr_freq(), EC_PR_FREQ);
|
||||
assert_eq!(ctrl.held_count(), 0);
|
||||
assert_eq!(ctrl.incoming_announce_frequency(), 0.0);
|
||||
assert_eq!(ctrl.incoming_pr_frequency(), 0.0);
|
||||
assert_eq!(ctrl.outgoing_pr_frequency(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -326,6 +566,179 @@ mod tests {
|
||||
assert!(!ctrl.should_ingress_limit());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_ingress_control_keeps_frequency_stats() {
|
||||
let mut ctrl = IngressController::disabled();
|
||||
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.2);
|
||||
push_samples(&mut ctrl.ip_freq_deque, IP_FREQ_SAMPLES, 4, 1.0, 0.2);
|
||||
|
||||
assert!(!ctrl.should_ingress_limit());
|
||||
assert!(!ctrl.should_ingress_limit_pr());
|
||||
assert!(ctrl.incoming_announce_frequency() > 0.0);
|
||||
assert!(ctrl.incoming_pr_frequency() > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announce_frequency_ignores_decayed_samples_for_stats() {
|
||||
let mut ctrl = IngressController::new();
|
||||
push_samples(
|
||||
&mut ctrl.ia_freq_deque,
|
||||
IA_FREQ_SAMPLES,
|
||||
IC_DEQUE_MIN_SAMPLE + 2,
|
||||
AR_FREQ_DECAY + 2.0,
|
||||
0.1,
|
||||
);
|
||||
|
||||
assert_eq!(ctrl.incoming_announce_frequency(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pr_frequency_ignores_decayed_samples_for_stats() {
|
||||
let mut ctrl = IngressController::new();
|
||||
push_samples(
|
||||
&mut ctrl.ip_freq_deque,
|
||||
IP_FREQ_SAMPLES,
|
||||
IC_DEQUE_MIN_SAMPLE + 2,
|
||||
PR_FREQ_DECAY + 2.0,
|
||||
0.1,
|
||||
);
|
||||
|
||||
assert_eq!(ctrl.incoming_pr_frequency(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announce_burst_clears_only_with_minimum_remaining_samples() {
|
||||
let mut ctrl = IngressController::new();
|
||||
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
|
||||
assert!(ctrl.should_ingress_limit());
|
||||
assert!(ctrl.is_burst_active());
|
||||
|
||||
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
|
||||
ctrl.ia_freq_deque.clear();
|
||||
push_samples(
|
||||
&mut ctrl.ia_freq_deque,
|
||||
IA_FREQ_SAMPLES,
|
||||
IC_BURST_MIN_SAMPLES,
|
||||
AR_FREQ_DECAY + 1.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(ctrl.should_ingress_limit());
|
||||
assert!(ctrl.is_burst_active());
|
||||
|
||||
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
|
||||
ctrl.ia_freq_deque.clear();
|
||||
push_samples(
|
||||
&mut ctrl.ia_freq_deque,
|
||||
IA_FREQ_SAMPLES,
|
||||
IC_BURST_MIN_SAMPLES + 1,
|
||||
AR_FREQ_DECAY + 1.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(ctrl.should_ingress_limit());
|
||||
assert!(!ctrl.is_burst_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_release_poll_does_not_activate_burst_when_nothing_is_held() {
|
||||
let mut ctrl = IngressController::new();
|
||||
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
|
||||
|
||||
assert!(ctrl.try_release_held().is_none());
|
||||
assert!(!ctrl.is_burst_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_announces_release_even_if_burst_state_is_waiting_for_clear_samples() {
|
||||
let mut ctrl = IngressController::new();
|
||||
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
|
||||
assert!(ctrl.should_ingress_limit());
|
||||
assert!(ctrl.is_burst_active());
|
||||
|
||||
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
|
||||
ctrl.ia_freq_deque.clear();
|
||||
push_samples(
|
||||
&mut ctrl.ia_freq_deque,
|
||||
IA_FREQ_SAMPLES,
|
||||
IC_BURST_MIN_SAMPLES,
|
||||
AR_FREQ_DECAY + 1.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(ctrl.should_ingress_limit());
|
||||
assert!(ctrl.is_burst_active());
|
||||
|
||||
ctrl.held_release = Instant::now() - Duration::from_secs(1);
|
||||
ctrl.hold_announce(HeldAnnounce {
|
||||
raw: Bytes::from_static(&[1, 2, 3]),
|
||||
destination_hash: [0xA5; 16],
|
||||
hops: 1,
|
||||
receiving_interface_id: 1,
|
||||
});
|
||||
|
||||
let released = ctrl.try_release_held();
|
||||
assert!(released.is_some());
|
||||
assert!(ctrl.is_burst_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pr_ingress_burst_activates_and_clears() {
|
||||
let mut ctrl = IngressController::new();
|
||||
push_samples(&mut ctrl.ip_freq_deque, IP_FREQ_SAMPLES, 4, 1.0, 0.1);
|
||||
|
||||
assert!(ctrl.should_ingress_limit_pr());
|
||||
assert!(ctrl.is_pr_burst_active());
|
||||
|
||||
ctrl.pr_burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
|
||||
ctrl.ip_freq_deque.clear();
|
||||
push_samples(
|
||||
&mut ctrl.ip_freq_deque,
|
||||
IP_FREQ_SAMPLES,
|
||||
IC_DEQUE_MIN_SAMPLE + 1,
|
||||
PR_FREQ_DECAY + 1.0,
|
||||
0.1,
|
||||
);
|
||||
|
||||
assert!(ctrl.should_ingress_limit_pr());
|
||||
assert!(!ctrl.is_pr_burst_active());
|
||||
assert!(!ctrl.should_ingress_limit_pr());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pr_egress_limiting_is_optional_and_requires_six_samples() {
|
||||
let mut disabled = IngressController::new();
|
||||
push_samples(
|
||||
&mut disabled.op_freq_deque,
|
||||
OP_FREQ_SAMPLES,
|
||||
IC_BURST_MIN_SAMPLES + 2,
|
||||
1.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(!disabled.should_egress_limit_pr());
|
||||
|
||||
let mut ctrl = IngressController::with_overrides(&IngressOverrides {
|
||||
egress_control: Some(true),
|
||||
ec_pr_freq: Some(EC_PR_FREQ),
|
||||
..Default::default()
|
||||
});
|
||||
push_samples(
|
||||
&mut ctrl.op_freq_deque,
|
||||
OP_FREQ_SAMPLES,
|
||||
IC_BURST_MIN_SAMPLES - 1,
|
||||
1.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(!ctrl.should_egress_limit_pr());
|
||||
|
||||
ctrl.op_freq_deque.clear();
|
||||
push_samples(
|
||||
&mut ctrl.op_freq_deque,
|
||||
OP_FREQ_SAMPLES,
|
||||
IC_BURST_MIN_SAMPLES,
|
||||
1.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(ctrl.should_egress_limit_pr());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hold_announce_dedups_by_destination() {
|
||||
let mut ctrl = IngressController::new();
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user