mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
Compare commits
80
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
936f19a200 | ||
|
|
b9522bfab1 | ||
|
|
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 | ||
|
|
b89e434a00 |
No files matched your search
+1
-1
@@ -6,4 +6,4 @@ __pycache__/
|
||||
/interop_artifacts/
|
||||
/rust_artifacts/
|
||||
proptest-regressions/
|
||||
/tools/
|
||||
/tools/*
|
||||
Generated
+266
-42
@@ -69,6 +69,12 @@ version = "1.0.102"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
|
||||
|
||||
[[package]]
|
||||
name = "arrayvec"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.89"
|
||||
@@ -98,6 +104,17 @@ version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bip39"
|
||||
version = "2.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
|
||||
dependencies = [
|
||||
"bitcoin_hashes",
|
||||
"serde",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
@@ -113,6 +130,15 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitcoin_hashes"
|
||||
version = "0.14.100"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9901a56e133a1fc86eeb1113e2591f45f4682451ca893bff494d2f88918e3f"
|
||||
dependencies = [
|
||||
"hex-conservative",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -252,21 +278,11 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
||||
|
||||
[[package]]
|
||||
name = "bzip2"
|
||||
version = "0.5.2"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
|
||||
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
|
||||
dependencies = [
|
||||
"bzip2-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bzip2-sys"
|
||||
version = "0.1.13+1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"libbz2-rs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -278,16 +294,6 @@ dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cesu8"
|
||||
version = "1.1.0"
|
||||
@@ -570,9 +576,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"der_derive",
|
||||
"flagset",
|
||||
"pem-rfc7468",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "des"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -580,6 +609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
@@ -655,10 +685,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
name = "flagset"
|
||||
version = "0.4.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
@@ -839,6 +869,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hex-conservative"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.12.4"
|
||||
@@ -1004,6 +1043,9 @@ name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
@@ -1011,6 +1053,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "libbz2-rs-sys"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.183"
|
||||
@@ -1026,6 +1074,12 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
@@ -1062,6 +1116,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.0"
|
||||
@@ -1111,6 +1175,22 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint-dig"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"libm",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-traits",
|
||||
"rand 0.8.5",
|
||||
"smallvec",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.4.2"
|
||||
@@ -1122,6 +1202,26 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -1129,6 +1229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1230,6 +1331,15 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project"
|
||||
version = "1.1.11"
|
||||
@@ -1256,6 +1366,17 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs1"
|
||||
version = "0.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
|
||||
dependencies = [
|
||||
"der",
|
||||
"pkcs8",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
@@ -1461,7 +1582,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -1482,7 +1603,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1499,7 +1620,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bluer",
|
||||
"btleplug",
|
||||
@@ -1529,7 +1650,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1545,7 +1666,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1562,27 +1683,38 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-ratkey"
|
||||
version = "0.9.4"
|
||||
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.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
"hmac",
|
||||
"md-5",
|
||||
"nix 0.29.0",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
@@ -1603,7 +1735,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-tools"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
@@ -1630,7 +1762,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1650,7 +1782,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"rns-crypto",
|
||||
@@ -1658,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"
|
||||
@@ -1811,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"
|
||||
@@ -1831,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"
|
||||
@@ -1853,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",
|
||||
]
|
||||
|
||||
@@ -1888,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"
|
||||
@@ -2022,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"
|
||||
@@ -2200,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"
|
||||
@@ -2753,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"
|
||||
|
||||
+13
-11
@@ -14,7 +14,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.9.4"
|
||||
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,7 +48,7 @@ serde_json = "1"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
# Compression
|
||||
bzip2 = "0.5"
|
||||
bzip2 = "0.6"
|
||||
|
||||
# Serial
|
||||
serialport = { version = "4", default-features = false }
|
||||
@@ -77,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" }
|
||||
@@ -145,7 +145,7 @@ intentional.
|
||||
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
|
||||
dump/backup, and trusted-key storage.
|
||||
|
||||
`rnid-rs` tracks the Reticulum 1.2.4 identity utility surface for normal
|
||||
`rnid-rs` tracks the Reticulum 1.2.5 identity utility surface for normal
|
||||
software identities: public/private import and export, destination hashing,
|
||||
`.pub` public identity files, and signed `.rsg` signature files. The
|
||||
hardware-backed `rnid-rs hw` path is a Rust extension behind the `hardware`
|
||||
@@ -169,7 +169,7 @@ rnid-rs -i ~/.rsReticulum/identities/mgmt -X -w mgmt.rid
|
||||
rnid-rs -m <public_identity_data> -w peer.pub
|
||||
rnid-rs -M <private_identity_data> -X -w restored_identity
|
||||
|
||||
# Sign and validate. New signatures are Reticulum 1.2.4 .rsg envelopes.
|
||||
# Sign and validate. New signatures are Reticulum 1.2.5 .rsg envelopes.
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -s message.txt
|
||||
rnid-rs -V message.txt.rsg
|
||||
rnid-rs -i <signer_hash> -N -V message.txt.rsg
|
||||
@@ -181,7 +181,7 @@ rnid-rs -i ~/.rsReticulum/identities/mgmt -d message.txt.rfe
|
||||
|
||||
Use `--raw -s <file>` only when a workflow intentionally needs the legacy raw
|
||||
64-byte signature form. Normal `rnid-rs -s <file>` produces a `.rsg` file that
|
||||
embeds the signer metadata needed for 1.2.4 validation.
|
||||
embeds the signer metadata needed for 1.2.5 validation.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -256,8 +256,8 @@ Most daemon and utility flows are implemented for the public `*-rs` tools:
|
||||
`rnsd-rs`, `rnstatus-rs`, `rnpath-rs`, `rnid-rs`, `rnprobe-rs`, `rncp-rs`,
|
||||
`rnsh-rs`, and `rnodeconf-rs`.
|
||||
|
||||
The current compatibility target is Reticulum 1.2.4 where the matching Rust
|
||||
surface is implemented and tested. `rnid-rs` has explicit 1.2.4 coverage for
|
||||
The current compatibility target is Reticulum 1.2.5 where the matching Rust
|
||||
surface is implemented and tested. `rnid-rs` has explicit 1.2.5 coverage for
|
||||
the normal identity utility flow.
|
||||
|
||||
Known gaps and intentional limits:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -49,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"
|
||||
|
||||
@@ -103,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 {
|
||||
@@ -117,6 +123,9 @@ impl AndroidUsbConfig {
|
||||
coding_rate: 6,
|
||||
tx_power: 17,
|
||||
mode: InterfaceMode::Full,
|
||||
flow_control: false,
|
||||
st_alock: None,
|
||||
lt_alock: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -615,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(
|
||||
|
||||
@@ -1081,10 +1081,10 @@ pub async fn spawn_auto_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,
|
||||
@@ -1199,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;
|
||||
@@ -1220,20 +1225,21 @@ pub async fn spawn_auto_interface(
|
||||
.map(|(name, _, _)| name.clone())
|
||||
};
|
||||
let is_self = self_iface.is_some();
|
||||
let received_hash = hex32(&buf[..32]);
|
||||
let expected = make_beacon(&auth_group_id, &peer_ip);
|
||||
let expected_hex = hex32(&expected);
|
||||
let match_ok = expected[..] == buf[..32];
|
||||
tracing::debug!(
|
||||
src = %src_v6,
|
||||
scope_id = src_v6.scope_id(),
|
||||
n,
|
||||
is_self,
|
||||
recv_hash = %received_hash,
|
||||
expected_hash = %expected_hex,
|
||||
match_ok,
|
||||
"auto-instr mcast RX"
|
||||
);
|
||||
// Hash hex strings only materialize when debug is on.
|
||||
if tracing::enabled!(tracing::Level::DEBUG) {
|
||||
tracing::debug!(
|
||||
src = %src_v6,
|
||||
scope_id = src_v6.scope_id(),
|
||||
n,
|
||||
is_self,
|
||||
recv_hash = %hex32(&buf[..32]),
|
||||
expected_hash = %hex32(&expected),
|
||||
match_ok,
|
||||
"auto-instr mcast RX"
|
||||
);
|
||||
}
|
||||
if let Some(ifname) = self_iface {
|
||||
// Self-echo: carrier confirmed; record for jobs task.
|
||||
let mut echoes = disc_echoes.lock().await;
|
||||
@@ -1267,8 +1273,12 @@ pub async fn spawn_auto_interface(
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "auto discovery recv error");
|
||||
break;
|
||||
consecutive_errors += 1;
|
||||
tracing::warn!(error = %e, consecutive_errors, "auto discovery recv error");
|
||||
if consecutive_errors >= 50 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1300,12 +1310,14 @@ pub async fn spawn_auto_interface(
|
||||
let urecv_link_locals = unicast_link_locals.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 256];
|
||||
let mut consecutive_errors = 0u32;
|
||||
loop {
|
||||
if !urecv_online.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
match urecv_sock.recv_from(&mut buf).await {
|
||||
Ok((n, src)) => {
|
||||
consecutive_errors = 0;
|
||||
if n < 32 {
|
||||
continue;
|
||||
}
|
||||
@@ -1341,8 +1353,16 @@ pub async fn spawn_auto_interface(
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!(error = %e, "auto unicast discovery recv error");
|
||||
break;
|
||||
consecutive_errors += 1;
|
||||
tracing::debug!(
|
||||
error = %e,
|
||||
consecutive_errors,
|
||||
"auto unicast discovery recv error"
|
||||
);
|
||||
if consecutive_errors >= 50 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1381,39 +1401,52 @@ pub async fn spawn_auto_interface(
|
||||
}
|
||||
let snapshot = { rev_link_locals.lock().await.clone() };
|
||||
let now = Instant::now();
|
||||
let mut table = rev_peers.lock().await;
|
||||
for (_key, peer) in table.iter_mut() {
|
||||
if now.duration_since(peer.last_reverse).as_secs_f64()
|
||||
>= REVERSE_PEERING_INTERVAL
|
||||
{
|
||||
let mut targets: Vec<_> = snapshot
|
||||
.iter()
|
||||
.filter(|(_, _, scope_id)| {
|
||||
peer.scope_id == 0 || *scope_id == peer.scope_id
|
||||
})
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
targets = snapshot.iter().collect();
|
||||
// Snapshot due peers under a short lock; sends happen lock-free
|
||||
// so discovery/data tasks aren't stalled by the fan-out.
|
||||
let due: Vec<(PeerKey, Peer)> = {
|
||||
let table = rev_peers.lock().await;
|
||||
table
|
||||
.iter()
|
||||
.filter(|(_, peer)| {
|
||||
now.duration_since(peer.last_reverse).as_secs_f64()
|
||||
>= REVERSE_PEERING_INTERVAL
|
||||
})
|
||||
.map(|(key, peer)| (*key, peer.clone()))
|
||||
.collect()
|
||||
};
|
||||
for (_, peer) in &due {
|
||||
let mut targets: Vec<_> = snapshot
|
||||
.iter()
|
||||
.filter(|(_, _, scope_id)| peer.scope_id == 0 || *scope_id == peer.scope_id)
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
targets = snapshot.iter().collect();
|
||||
}
|
||||
for (_name, ll_addr, scope_id) in targets {
|
||||
let beacon = make_beacon(&rev_group_id, ll_addr);
|
||||
let dest =
|
||||
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
|
||||
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
|
||||
tracing::debug!(
|
||||
peer = %peer.ip,
|
||||
peer_ifname = %peer.ifname,
|
||||
peer_scope_id = peer.scope_id,
|
||||
local_iface = %_name,
|
||||
local_scope_id = scope_id,
|
||||
dst = %dest,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"auto: reverse peering TX failed"
|
||||
);
|
||||
}
|
||||
for (_name, ll_addr, scope_id) in targets {
|
||||
let beacon = make_beacon(&rev_group_id, ll_addr);
|
||||
let dest =
|
||||
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
|
||||
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
|
||||
tracing::debug!(
|
||||
peer = %peer.ip,
|
||||
peer_ifname = %peer.ifname,
|
||||
peer_scope_id = peer.scope_id,
|
||||
local_iface = %_name,
|
||||
local_scope_id = scope_id,
|
||||
dst = %dest,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
"auto: reverse peering TX failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !due.is_empty() {
|
||||
let mut table = rev_peers.lock().await;
|
||||
for (key, _) in &due {
|
||||
if let Some(peer) = table.get_mut(key) {
|
||||
peer.last_reverse = now;
|
||||
}
|
||||
peer.last_reverse = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1572,32 +1605,46 @@ pub async fn spawn_auto_interface(
|
||||
tokio::spawn(async move {
|
||||
while let Some(data) = rx.recv().await {
|
||||
let len = data.len();
|
||||
let prefix = hex_prefix(&data, 16);
|
||||
let table = peers_write.lock().await;
|
||||
let peer_count = table.len();
|
||||
if peer_count == 0 {
|
||||
// Hex prefix only materializes when debug logging is active; the
|
||||
// error path below recomputes it (errors are rare).
|
||||
let debug_enabled = tracing::enabled!(tracing::Level::DEBUG);
|
||||
let prefix = if debug_enabled {
|
||||
hex_prefix(&data, 16)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
// Snapshot under a short lock so the discovery/jobs tasks are not
|
||||
// blocked while we await per-peer sends.
|
||||
let targets: Vec<Peer> = {
|
||||
let table = peers_write.lock().await;
|
||||
table.values().cloned().collect()
|
||||
};
|
||||
let peer_count = targets.len();
|
||||
if peer_count == 0 && debug_enabled {
|
||||
tracing::debug!(
|
||||
len,
|
||||
prefix = %prefix,
|
||||
"auto-instr data TX skipped: no discovered peers"
|
||||
);
|
||||
}
|
||||
for (_key, peer) in table.iter() {
|
||||
for peer in &targets {
|
||||
let res = data_sock_w.send_to(&data, peer.addr).await;
|
||||
match res {
|
||||
Ok(n) => {
|
||||
tracing::debug!(
|
||||
peer = %peer.ip,
|
||||
ifname = %peer.ifname,
|
||||
scope_id = peer.scope_id,
|
||||
scope_source = ?peer.scope_source,
|
||||
dst = %peer.addr,
|
||||
len,
|
||||
sent_bytes = n,
|
||||
prefix = %prefix,
|
||||
peer_count,
|
||||
"auto-instr data TX"
|
||||
);
|
||||
if debug_enabled {
|
||||
tracing::debug!(
|
||||
peer = %peer.ip,
|
||||
ifname = %peer.ifname,
|
||||
scope_id = peer.scope_id,
|
||||
scope_source = ?peer.scope_source,
|
||||
dst = %peer.addr,
|
||||
len,
|
||||
sent_bytes = n,
|
||||
prefix = %prefix,
|
||||
peer_count,
|
||||
"auto-instr data TX"
|
||||
);
|
||||
}
|
||||
task_txb.fetch_add(len as u64, Ordering::Relaxed);
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -1608,7 +1655,7 @@ pub async fn spawn_auto_interface(
|
||||
scope_source = ?peer.scope_source,
|
||||
dst = %peer.addr,
|
||||
len,
|
||||
prefix = %prefix,
|
||||
prefix = %hex_prefix(&data, 16),
|
||||
peer_count,
|
||||
error = %e,
|
||||
raw_os_error = ?e.raw_os_error(),
|
||||
@@ -1625,9 +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;
|
||||
}
|
||||
@@ -1658,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+1265
-494
File diff suppressed because it is too large.
Load diff
@@ -379,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 {
|
||||
@@ -392,13 +396,60 @@ impl BleRNodeConfig {
|
||||
coding_rate: 5,
|
||||
tx_power: 14,
|
||||
mode: InterfaceMode::Full,
|
||||
flow_control: true,
|
||||
// Python RNodeInterface defaults flow_control off.
|
||||
flow_control: false,
|
||||
st_alock: None,
|
||||
lt_alock: None,
|
||||
id_interval: None,
|
||||
id_callsign: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Station-ID beacon parameters, disabled for oversized callsigns
|
||||
/// (Python RNodeInterface.py:333-343).
|
||||
fn beacon_from_config(config: &BleRNodeConfig) -> Option<(Duration, Bytes)> {
|
||||
config
|
||||
.id_interval
|
||||
.zip(config.id_callsign.clone())
|
||||
.filter(|(_, callsign)| {
|
||||
let ok = callsign.len() <= rnode::CALLSIGN_MAX_LEN;
|
||||
if !ok {
|
||||
tracing::error!(
|
||||
name = %config.name,
|
||||
len = callsign.len(),
|
||||
"id_callsign exceeds {} bytes, beaconing disabled",
|
||||
rnode::CALLSIGN_MAX_LEN
|
||||
);
|
||||
}
|
||||
ok
|
||||
})
|
||||
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)))
|
||||
}
|
||||
|
||||
fn rnode_config_from_ble_config(config: &BleRNodeConfig) -> rnode::RNodeConfig {
|
||||
rnode::RNodeConfig {
|
||||
name: config.name.clone(),
|
||||
port: config.ble_uri.clone(),
|
||||
baud_rate: 0,
|
||||
frequency: config.frequency,
|
||||
bandwidth: config.bandwidth,
|
||||
spreading_factor: config.spreading_factor,
|
||||
coding_rate: config.coding_rate,
|
||||
tx_power: config.tx_power,
|
||||
mode: config.mode,
|
||||
flow_control: config.flow_control,
|
||||
st_alock: config.st_alock,
|
||||
lt_alock: config.lt_alock,
|
||||
id_interval: config.id_interval,
|
||||
id_callsign: config.id_callsign.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_ble_rnode_init_sequence(config: &BleRNodeConfig) -> Vec<u8> {
|
||||
rnode::build_init_sequence(&rnode_config_from_ble_config(config))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_adapter() -> Result<Adapter, InterfaceError> {
|
||||
// btleplug's Android global_adapter() panics without init; under
|
||||
// panic=abort that kills the app. Fail loudly so the UI can prompt.
|
||||
@@ -713,12 +764,17 @@ 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). Linux used explicit BlueZ
|
||||
// pairing before `connect()`, above.
|
||||
#[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?;
|
||||
|
||||
ble_diag("[ble] subscribe TX start");
|
||||
@@ -758,7 +814,21 @@ async fn connect_rnode(
|
||||
/// pairing flow when the characteristic requires authentication). Linux
|
||||
/// uses `linux_trigger_pairing` instead — BlueZ requires an explicit
|
||||
/// `Device::pair()` plus a registered Agent for the passkey callback.
|
||||
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))]
|
||||
///
|
||||
/// Android behaves like Windows: a GATT op on an auth-required char makes
|
||||
/// the platform start bonding (system passkey dialog) and retry the op
|
||||
/// internally once bonded. Without this read-first step the subscribe()
|
||||
/// CCCD write fails instantly with insufficient-auth while the bond is
|
||||
/// still running — first add fails, second connect works. If the stack
|
||||
/// errors instead of blocking, the error maps to "BLE pairing in
|
||||
/// progress" and the reconnect loop retries on a 1s cadence until the
|
||||
/// bond lands.
|
||||
#[cfg(any(
|
||||
target_os = "ios",
|
||||
target_os = "macos",
|
||||
target_os = "windows",
|
||||
target_os = "android"
|
||||
))]
|
||||
async fn desktop_trigger_pairing(
|
||||
peripheral: &Peripheral,
|
||||
tx_char: &btleplug::api::Characteristic,
|
||||
@@ -1151,24 +1221,12 @@ pub async fn spawn_ble_rnode_interface(
|
||||
config.bandwidth,
|
||||
);
|
||||
|
||||
let rnode_cfg = rnode::RNodeConfig {
|
||||
name: config.name.clone(),
|
||||
port: config.ble_uri.clone(),
|
||||
baud_rate: 0,
|
||||
frequency: config.frequency,
|
||||
bandwidth: config.bandwidth,
|
||||
spreading_factor: config.spreading_factor,
|
||||
coding_rate: config.coding_rate,
|
||||
tx_power: config.tx_power,
|
||||
mode: config.mode,
|
||||
flow_control: config.flow_control,
|
||||
st_alock: config.st_alock,
|
||||
lt_alock: config.lt_alock,
|
||||
};
|
||||
let init_seq_template = build_ble_rnode_init_sequence(&config);
|
||||
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let flow_control = config.flow_control;
|
||||
let beacon = beacon_from_config(&config);
|
||||
let ble_uri = config.ble_uri.clone();
|
||||
let log_name = name.clone();
|
||||
let running_task = running.clone();
|
||||
@@ -1254,9 +1312,8 @@ pub async fn spawn_ble_rnode_interface(
|
||||
}
|
||||
ble_diag("[ble] detect sent ok");
|
||||
|
||||
ble_diag("[ble] sending init + airtime sequence");
|
||||
let mut init_seq = rnode::build_init_sequence(&rnode_cfg);
|
||||
init_seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg));
|
||||
ble_diag("[ble] sending init sequence");
|
||||
let init_seq = init_seq_template.clone();
|
||||
if let Err(e) =
|
||||
ble_write(&conn.peripheral, &conn.rx_char, &init_seq, conn.write_mtu).await
|
||||
{
|
||||
@@ -1293,8 +1350,37 @@ pub async fn spawn_ble_rnode_interface(
|
||||
let online_w = online_handle.clone();
|
||||
let ready_w = ready.clone();
|
||||
let txb_w = task_txb.clone();
|
||||
let beacon_w = beacon.clone();
|
||||
let write_handle = tokio::spawn(async move {
|
||||
while let Some(data) = conn_rx.recv().await {
|
||||
// Python first_tx semantics: armed by data TX, cleared when
|
||||
// the callsign beacon goes out (RNodeInterface.py:712-718).
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let data = if let Some((interval, ref callsign)) = beacon_w {
|
||||
match tokio::time::timeout(Duration::from_secs(1), conn_rx.recv()).await {
|
||||
Ok(Some(data)) => data,
|
||||
Ok(None) => break,
|
||||
Err(_) => {
|
||||
if first_tx.is_none_or(|t| t.elapsed() < interval) {
|
||||
continue;
|
||||
}
|
||||
tracing::debug!("BLE RNode transmitting station-ID beacon");
|
||||
callsign.clone()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match conn_rx.recv().await {
|
||||
Some(data) => data,
|
||||
None => break,
|
||||
}
|
||||
};
|
||||
if let Some((_, ref callsign)) = beacon_w {
|
||||
if data == *callsign {
|
||||
first_tx = None;
|
||||
} else if first_tx.is_none() {
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
}
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
if flow_control {
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
@@ -1483,24 +1569,12 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
config.bandwidth,
|
||||
);
|
||||
|
||||
let rnode_cfg = rnode::RNodeConfig {
|
||||
name: config.name.clone(),
|
||||
port: config.ble_uri.clone(),
|
||||
baud_rate: 0,
|
||||
frequency: config.frequency,
|
||||
bandwidth: config.bandwidth,
|
||||
spreading_factor: config.spreading_factor,
|
||||
coding_rate: config.coding_rate,
|
||||
tx_power: config.tx_power,
|
||||
mode: config.mode,
|
||||
flow_control: config.flow_control,
|
||||
st_alock: config.st_alock,
|
||||
lt_alock: config.lt_alock,
|
||||
};
|
||||
let init_seq_template = build_ble_rnode_init_sequence(&config);
|
||||
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let flow_control = config.flow_control;
|
||||
let beacon = beacon_from_config(&config);
|
||||
let ble_uri = config.ble_uri.clone();
|
||||
let log_name = name.clone();
|
||||
let running = register_running(id);
|
||||
@@ -1565,8 +1639,7 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut init_seq = rnode::build_init_sequence(&rnode_cfg);
|
||||
init_seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg));
|
||||
let init_seq = init_seq_template.clone();
|
||||
if let Err(e) = tcp_write.write_all(&init_seq).await {
|
||||
tracing::warn!(error = %e, "BLE RNode native init write failed");
|
||||
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
|
||||
@@ -1595,10 +1668,39 @@ pub async fn spawn_ble_rnode_interface_native(
|
||||
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(msg) = conn_rx.recv().await {
|
||||
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) {
|
||||
@@ -1772,7 +1874,10 @@ mod tests {
|
||||
assert_eq!(cfg.spreading_factor, 7);
|
||||
assert_eq!(cfg.coding_rate, 5);
|
||||
assert_eq!(cfg.tx_power, 14);
|
||||
assert!(cfg.flow_control);
|
||||
assert!(
|
||||
!cfg.flow_control,
|
||||
"flow_control defaults off (Python parity)"
|
||||
);
|
||||
assert!(cfg.st_alock.is_none());
|
||||
assert!(cfg.lt_alock.is_none());
|
||||
}
|
||||
@@ -2062,28 +2167,29 @@ mod tests {
|
||||
|
||||
// ── Init sequence tests ──
|
||||
|
||||
fn frame_command_count(frames: &[(u8, Vec<u8>)], command: u8) -> usize {
|
||||
frames.iter().filter(|(cmd, _)| *cmd == command).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ble_init_sequence_uses_rnode_helpers() {
|
||||
let ble_cfg = BleRNodeConfig::new("ble0", "ble://RNode 1234");
|
||||
let rnode_cfg = rnode::RNodeConfig {
|
||||
name: ble_cfg.name.clone(),
|
||||
port: ble_cfg.ble_uri.clone(),
|
||||
baud_rate: 0,
|
||||
frequency: ble_cfg.frequency,
|
||||
bandwidth: ble_cfg.bandwidth,
|
||||
spreading_factor: ble_cfg.spreading_factor,
|
||||
coding_rate: ble_cfg.coding_rate,
|
||||
tx_power: ble_cfg.tx_power,
|
||||
mode: ble_cfg.mode,
|
||||
flow_control: ble_cfg.flow_control,
|
||||
st_alock: ble_cfg.st_alock,
|
||||
lt_alock: ble_cfg.lt_alock,
|
||||
};
|
||||
let seq = rnode::build_init_sequence(&rnode_cfg);
|
||||
let rnode_cfg = rnode_config_from_ble_config(&ble_cfg);
|
||||
let seq = build_ble_rnode_init_sequence(&ble_cfg);
|
||||
assert!(!seq.is_empty());
|
||||
assert_eq!(seq, rnode::build_init_sequence(&rnode_cfg));
|
||||
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames = deframer.feed(&seq);
|
||||
assert_eq!(frames.len(), 6);
|
||||
assert_eq!(frames.len(), 7);
|
||||
assert_eq!(
|
||||
frames[0],
|
||||
(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_OFF])
|
||||
);
|
||||
assert_eq!(
|
||||
frames.last().unwrap(),
|
||||
&(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2096,15 +2202,36 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_ble_full_init_with_airtime() {
|
||||
let mut rnode_cfg = rnode::RNodeConfig::new("test", "ble://");
|
||||
rnode_cfg.st_alock = Some(25.0);
|
||||
rnode_cfg.lt_alock = Some(50.0);
|
||||
let mut seq = rnode::build_init_sequence(&rnode_cfg);
|
||||
seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg));
|
||||
let mut cfg = BleRNodeConfig::new("test", "ble://");
|
||||
cfg.st_alock = Some(25.0);
|
||||
cfg.lt_alock = Some(50.0);
|
||||
// Airtime locks are part of the init sequence, before RADIO_STATE_ON.
|
||||
let seq = build_ble_rnode_init_sequence(&cfg);
|
||||
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames = deframer.feed(&seq);
|
||||
assert_eq!(frames.len(), 8); // 6 init + 2 airtime
|
||||
assert_eq!(frames.len(), 9);
|
||||
assert_eq!(
|
||||
frames[0],
|
||||
(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_OFF])
|
||||
);
|
||||
assert_eq!(
|
||||
frames.last().unwrap(),
|
||||
&(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON])
|
||||
);
|
||||
assert_eq!(frame_command_count(&frames, rnode::CMD_ST_ALOCK), 1);
|
||||
assert_eq!(frame_command_count(&frames, rnode::CMD_LT_ALOCK), 1);
|
||||
let radio_on = frames.len() - 1;
|
||||
let st = frames
|
||||
.iter()
|
||||
.position(|(cmd, _)| *cmd == rnode::CMD_ST_ALOCK)
|
||||
.expect("CMD_ST_ALOCK present");
|
||||
let lt = frames
|
||||
.iter()
|
||||
.position(|(cmd, _)| *cmd == rnode::CMD_LT_ALOCK)
|
||||
.expect("CMD_LT_ALOCK present");
|
||||
assert!(st < radio_on);
|
||||
assert!(lt < radio_on);
|
||||
}
|
||||
|
||||
// ── process_rnode_response tests ──
|
||||
@@ -2145,7 +2272,7 @@ mod tests {
|
||||
fn test_response_rssi_updates() {
|
||||
let mut rssi = None;
|
||||
let mut snr = None;
|
||||
rnode::process_rnode_response(rnode::CMD_STAT_RSSI, &[0xBF], 1, &mut rssi, &mut snr);
|
||||
rnode::process_rnode_response(rnode::CMD_STAT_RSSI, &[92], 1, &mut rssi, &mut snr);
|
||||
assert_eq!(rssi, Some(-65.0));
|
||||
}
|
||||
|
||||
|
||||
+125
-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,20 +549,19 @@ pub async fn spawn_i2p_client(
|
||||
write_handle.abort();
|
||||
let _ = write_handle.await;
|
||||
|
||||
if let Some(max) = config.max_reconnect_tries {
|
||||
tries += 1;
|
||||
if tries >= max {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
return;
|
||||
}
|
||||
if pacer.give_up() {
|
||||
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::DeregisterInterface { id })
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
tracing::info!(
|
||||
name = %config.name,
|
||||
delay = backoff,
|
||||
delay = pacer.backoff,
|
||||
"I2P client: reconnecting"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
|
||||
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
|
||||
pacer.wait().await;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -866,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1000,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;
|
||||
}
|
||||
@@ -262,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
-198
@@ -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,50 +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,
|
||||
parent_id: Some(0),
|
||||
name: client_name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
tx: c_tx,
|
||||
read_task: read_handle,
|
||||
};
|
||||
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;
|
||||
@@ -296,28 +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,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: false,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(server_rxb),
|
||||
txb: Some(server_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
Ok(server_listener_handle(name, online, tx, read_task))
|
||||
}
|
||||
|
||||
pub async fn spawn_local_client_impl(
|
||||
@@ -328,42 +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,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
config.name.clone(),
|
||||
None,
|
||||
reader,
|
||||
writer,
|
||||
transport_tx,
|
||||
false,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,50 +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,
|
||||
parent_id: Some(0),
|
||||
name: client_name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
tx: c_tx,
|
||||
read_task: read_handle,
|
||||
};
|
||||
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;
|
||||
@@ -465,28 +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,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: false,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(server_rxb),
|
||||
txb: Some(server_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
Ok(server_listener_handle(name, online, tx, read_task))
|
||||
}
|
||||
|
||||
pub async fn spawn_local_client_impl(
|
||||
@@ -498,42 +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,
|
||||
parent_id: None,
|
||||
name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
config.name.clone(),
|
||||
None,
|
||||
reader,
|
||||
writer,
|
||||
transport_tx,
|
||||
false,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +103,6 @@ pub const REQUIRED_FW_VER_MIN: u8 = 52;
|
||||
pub const RSSI_OFFSET: i32 = 157;
|
||||
|
||||
pub const RECONNECT_WAIT: u64 = 5;
|
||||
pub const MAX_RECONNECT_TRIES: usize = 3;
|
||||
|
||||
pub const RADIO_STATE_ON: u8 = 0x01;
|
||||
pub const RADIO_STATE_OFF: u8 = 0x00;
|
||||
@@ -355,14 +354,14 @@ impl RNodeStream {
|
||||
// Mirror the serial timeout so the read loop doesn't block forever.
|
||||
stream.set_read_timeout(Some(Duration::from_millis(RNODE_READ_TIMEOUT_MS)))?;
|
||||
stream.set_nodelay(true)?;
|
||||
crate::socket_tuning::set_keepalive_tuned_std(
|
||||
crate::socket_tuning::set_keepalive_tuned(
|
||||
&stream,
|
||||
Duration::from_secs(RNODE_TCP_KEEPIDLE_SECS),
|
||||
Duration::from_secs(RNODE_TCP_KEEPINTVL_SECS),
|
||||
RNODE_TCP_KEEPCNT,
|
||||
Duration::from_secs(RNODE_TCP_USER_TIMEOUT_SECS),
|
||||
);
|
||||
crate::socket_tuning::set_socket_buffers_std(&stream, RNODE_TCP_BUFFER_BYTES);
|
||||
crate::socket_tuning::set_socket_buffers(&stream, RNODE_TCP_BUFFER_BYTES);
|
||||
Ok(Self::Tcp(stream))
|
||||
}
|
||||
|
||||
@@ -513,8 +512,7 @@ async fn open_configured_rnode_stream(
|
||||
let mut init_port = port.try_clone().map_err(|e| {
|
||||
crate::traits::InterfaceError::SendFailed(format!("rnode clone: {}", e))
|
||||
})?;
|
||||
let mut init_seq = build_init_sequence(config);
|
||||
init_seq.extend_from_slice(&build_airtime_sequence(config));
|
||||
let init_seq = build_init_sequence(config);
|
||||
use std::io::Write;
|
||||
init_port.write_all(&init_seq).map_err(|e| {
|
||||
crate::traits::InterfaceError::SendFailed(format!("rnode init write: {}", e))
|
||||
@@ -559,8 +557,15 @@ pub struct RNodeConfig {
|
||||
pub st_alock: Option<f32>,
|
||||
/// Long-term airtime cap, percent (0.0..100.0). `None` = unlimited.
|
||||
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>>,
|
||||
}
|
||||
|
||||
/// Python `RNodeInterface.CALLSIGN_MAX_LEN`.
|
||||
pub const CALLSIGN_MAX_LEN: usize = 32;
|
||||
|
||||
impl RNodeConfig {
|
||||
pub fn new(name: &str, port: &str) -> Self {
|
||||
Self {
|
||||
@@ -573,9 +578,12 @@ impl RNodeConfig {
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -631,14 +639,18 @@ fn u32_to_bytes(val: u32) -> [u8; 4] {
|
||||
val.to_be_bytes()
|
||||
}
|
||||
|
||||
/// KISS init sequence. Order matters: RADIO_STATE=ON must be last.
|
||||
/// KISS init sequence. Order matters: turn the radio off first so persisted
|
||||
/// TNC startup profiles cannot keep old parameters active, airtime locks
|
||||
/// precede RADIO_STATE=ON, and RADIO_STATE=ON must be last.
|
||||
pub fn build_init_sequence(config: &RNodeConfig) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(48);
|
||||
let mut out = Vec::with_capacity(64);
|
||||
kiss::frame_with_command_into(CMD_RADIO_STATE, &[RADIO_STATE_OFF], &mut out);
|
||||
kiss::frame_with_command_into(CMD_FREQUENCY, &u32_to_bytes(config.frequency), &mut out);
|
||||
kiss::frame_with_command_into(CMD_BANDWIDTH, &u32_to_bytes(config.bandwidth), &mut out);
|
||||
kiss::frame_with_command_into(CMD_SF, &[config.spreading_factor], &mut out);
|
||||
kiss::frame_with_command_into(CMD_CR, &[config.coding_rate], &mut out);
|
||||
kiss::frame_with_command_into(CMD_TXPOWER, &[config.tx_power], &mut out);
|
||||
out.extend_from_slice(&build_airtime_sequence(config));
|
||||
kiss::frame_with_command_into(CMD_RADIO_STATE, &[RADIO_STATE_ON], &mut out);
|
||||
out
|
||||
}
|
||||
@@ -668,6 +680,16 @@ pub enum RNodeResponse {
|
||||
None,
|
||||
}
|
||||
|
||||
/// Python: raw unsigned RSSI byte minus `RSSI_OFFSET` (157) → dBm.
|
||||
pub fn decode_rssi_byte(byte: u8) -> f32 {
|
||||
byte as f32 - RSSI_OFFSET as f32
|
||||
}
|
||||
|
||||
/// Python: signed SNR byte × 0.25 → dB.
|
||||
pub fn decode_snr_byte(byte: u8) -> f32 {
|
||||
byte as i8 as f32 / 4.0
|
||||
}
|
||||
|
||||
/// Dispatch decoded KISS frame; shared by serial and BLE transports.
|
||||
pub fn process_rnode_response(
|
||||
cmd: u8,
|
||||
@@ -695,13 +717,13 @@ pub fn process_rnode_response(
|
||||
}
|
||||
CMD_STAT_RSSI => {
|
||||
if !frame.is_empty() {
|
||||
*last_rssi = Some(frame[0] as i8 as f32);
|
||||
*last_rssi = Some(decode_rssi_byte(frame[0]));
|
||||
}
|
||||
RNodeResponse::None
|
||||
}
|
||||
CMD_STAT_SNR => {
|
||||
if !frame.is_empty() {
|
||||
*last_snr = Some(frame[0] as i8 as f32 / 4.0);
|
||||
*last_snr = Some(decode_snr_byte(frame[0]));
|
||||
}
|
||||
RNodeResponse::None
|
||||
}
|
||||
@@ -833,6 +855,22 @@ pub async fn spawn_rnode_interface(
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let flow_control = config.flow_control;
|
||||
// Python RNodeInterface.py:333-343: oversized callsigns disable beaconing.
|
||||
let beacon: Option<(Duration, Bytes)> = config
|
||||
.id_interval
|
||||
.zip(config.id_callsign.clone())
|
||||
.filter(|(_, callsign)| {
|
||||
let ok = callsign.len() <= CALLSIGN_MAX_LEN;
|
||||
if !ok {
|
||||
tracing::error!(
|
||||
name = %config.name,
|
||||
len = callsign.len(),
|
||||
"id_callsign exceeds {CALLSIGN_MAX_LEN} bytes, beaconing disabled"
|
||||
);
|
||||
}
|
||||
ok
|
||||
})
|
||||
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)));
|
||||
|
||||
let online_r = online.clone();
|
||||
let rxb_r = shared_rxb.clone();
|
||||
@@ -896,11 +934,52 @@ pub async fn spawn_rnode_interface(
|
||||
let online_w = online_r.clone();
|
||||
let ready_w = ready.clone();
|
||||
let txb_w = txb_r.clone();
|
||||
let beacon_w = beacon.clone();
|
||||
let write_handle = tokio::spawn(async move {
|
||||
let mut port_w = port_write;
|
||||
while let Some(request) = conn_rx.recv().await {
|
||||
// Python first_tx semantics: armed by data TX, cleared when
|
||||
// the callsign beacon goes out (RNodeInterface.py:712-718, 1142-1146).
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let request = if let Some((interval, ref callsign)) = beacon_w {
|
||||
match tokio::time::timeout(Duration::from_secs(1), conn_rx.recv()).await {
|
||||
Ok(Some(request)) => request,
|
||||
Ok(None) => break,
|
||||
Err(_) => {
|
||||
if first_tx.is_none_or(|t| t.elapsed() < interval) {
|
||||
continue;
|
||||
}
|
||||
tracing::debug!("RNode transmitting station-ID beacon");
|
||||
RNodeWriteRequest::Packet(callsign.clone())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match conn_rx.recv().await {
|
||||
Some(request) => request,
|
||||
None => break,
|
||||
}
|
||||
};
|
||||
let (framed, is_packet, done_tx) = match request {
|
||||
RNodeWriteRequest::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());
|
||||
}
|
||||
}
|
||||
if let Ok((header, _)) = rns_wire::header::PacketHeader::unpack(&data) {
|
||||
tracing::debug!(
|
||||
id,
|
||||
raw_len = data.len(),
|
||||
packet_type = ?header.flags.packet_type,
|
||||
context = ?header.context,
|
||||
dest = %hex::encode(header.destination_hash),
|
||||
"RNode queued packet"
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(id, raw_len = data.len(), "RNode queued packet");
|
||||
}
|
||||
txb_w
|
||||
.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
(kiss::frame(&data), true, None)
|
||||
@@ -915,29 +994,21 @@ pub async fn spawn_rnode_interface(
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
let framed_len = framed.len();
|
||||
let result = crate::serial_io::blocking_write_all(port_w, framed).await;
|
||||
if let Some(done_tx) = done_tx {
|
||||
let _ = done_tx.send(());
|
||||
}
|
||||
match result {
|
||||
Ok(Ok(p)) => {
|
||||
Ok(p) => {
|
||||
if is_packet {
|
||||
tracing::debug!(id, framed_len, "RNode packet write complete");
|
||||
}
|
||||
port_w = p;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(error = %e, "RNode write error");
|
||||
online_ref.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "RNode write task panicked");
|
||||
online_ref.store(false, Ordering::SeqCst);
|
||||
tracing::warn!(error = %e, "RNode write error");
|
||||
online_w.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1072,11 +1143,31 @@ mod tests {
|
||||
assert_eq!(cfg.baud_rate, 115200);
|
||||
assert_eq!(cfg.frequency, 868_000_000);
|
||||
assert_eq!(cfg.spreading_factor, 7);
|
||||
assert!(cfg.flow_control);
|
||||
assert!(
|
||||
!cfg.flow_control,
|
||||
"flow_control defaults off (Python parity)"
|
||||
);
|
||||
assert!(cfg.st_alock.is_none());
|
||||
assert!(cfg.lt_alock.is_none());
|
||||
}
|
||||
|
||||
/// Python parity (RNodeInterface.py:878,880): RSSI = raw byte − 157,
|
||||
/// SNR = signed byte × 0.25.
|
||||
#[test]
|
||||
fn test_rssi_snr_decode_matches_python() {
|
||||
assert_eq!(decode_rssi_byte(67), -90.0);
|
||||
assert_eq!(decode_rssi_byte(157), 0.0);
|
||||
assert_eq!(decode_rssi_byte(0), -157.0);
|
||||
assert_eq!(decode_snr_byte(20), 5.0);
|
||||
assert_eq!(decode_snr_byte(0xF6), -2.5); // -10 as i8
|
||||
|
||||
let mut rssi = None;
|
||||
let mut snr = None;
|
||||
let resp = process_rnode_response(CMD_STAT_RSSI, &[67], 0, &mut rssi, &mut snr);
|
||||
assert!(matches!(resp, RNodeResponse::None));
|
||||
assert_eq!(rssi, Some(-90.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_init_sequence_parseable() {
|
||||
let cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0");
|
||||
@@ -1086,7 +1177,77 @@ mod tests {
|
||||
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames = deframer.feed(&seq);
|
||||
assert_eq!(frames.len(), 6);
|
||||
assert_eq!(frames.len(), 7);
|
||||
assert_eq!(frames[0], (CMD_RADIO_STATE, vec![RADIO_STATE_OFF]));
|
||||
assert_eq!(frames[6], (CMD_RADIO_STATE, vec![RADIO_STATE_ON]));
|
||||
}
|
||||
|
||||
/// Byte-exact vs Python `setSTALock`/`setLTALock` (RNodeInterface.py:612-630):
|
||||
/// `at = int(pct * 100)` big-endian u16, KISS-escaped, framed per command.
|
||||
#[test]
|
||||
fn test_airtime_sequence_matches_python_encoding() {
|
||||
let mut cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0");
|
||||
cfg.st_alock = Some(33.0);
|
||||
cfg.lt_alock = Some(3.3);
|
||||
let seq = build_airtime_sequence(&cfg);
|
||||
|
||||
// st: 3300 = 0x0CE4, lt: 330 = 0x014A — no KISS-special bytes, framed verbatim.
|
||||
let expected = [
|
||||
kiss::FEND,
|
||||
CMD_ST_ALOCK,
|
||||
0x0C,
|
||||
0xE4,
|
||||
kiss::FEND,
|
||||
kiss::FEND,
|
||||
CMD_LT_ALOCK,
|
||||
0x01,
|
||||
0x4A,
|
||||
kiss::FEND,
|
||||
];
|
||||
assert_eq!(seq, expected);
|
||||
|
||||
cfg.st_alock = None;
|
||||
cfg.lt_alock = None;
|
||||
assert!(build_airtime_sequence(&cfg).is_empty());
|
||||
}
|
||||
|
||||
/// Airtime frames are part of the radio init sequence when configured.
|
||||
#[test]
|
||||
fn test_init_sequence_includes_airtime_commands() {
|
||||
let mut cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0");
|
||||
cfg.st_alock = Some(10.0);
|
||||
cfg.lt_alock = Some(1.0);
|
||||
let seq = build_init_sequence(&cfg);
|
||||
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames = deframer.feed(&seq);
|
||||
let cmds: Vec<u8> = frames.iter().map(|(c, _)| *c).collect();
|
||||
assert_eq!(frames[0], (CMD_RADIO_STATE, vec![RADIO_STATE_OFF]));
|
||||
assert_eq!(
|
||||
frames.last().unwrap(),
|
||||
&(CMD_RADIO_STATE, vec![RADIO_STATE_ON])
|
||||
);
|
||||
assert_eq!(
|
||||
cmds.iter().filter(|&&cmd| cmd == CMD_ST_ALOCK).count(),
|
||||
1,
|
||||
"init must send CMD_ST_ALOCK exactly once"
|
||||
);
|
||||
assert_eq!(
|
||||
cmds.iter().filter(|&&cmd| cmd == CMD_LT_ALOCK).count(),
|
||||
1,
|
||||
"init must send CMD_LT_ALOCK exactly once"
|
||||
);
|
||||
let radio_on = cmds.len() - 1;
|
||||
let st = cmds
|
||||
.iter()
|
||||
.position(|&cmd| cmd == CMD_ST_ALOCK)
|
||||
.expect("CMD_ST_ALOCK present");
|
||||
let lt = cmds
|
||||
.iter()
|
||||
.position(|&cmd| cmd == CMD_LT_ALOCK)
|
||||
.expect("CMD_LT_ALOCK present");
|
||||
assert!(st < radio_on, "CMD_ST_ALOCK must precede RADIO_STATE_ON");
|
||||
assert!(lt < radio_on, "CMD_LT_ALOCK must precede RADIO_STATE_ON");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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;
|
||||
@@ -434,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,
|
||||
@@ -449,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.
|
||||
@@ -472,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();
|
||||
|
||||
@@ -528,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 {
|
||||
@@ -573,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 {
|
||||
@@ -597,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()
|
||||
{
|
||||
@@ -607,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()
|
||||
{
|
||||
@@ -802,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;
|
||||
}
|
||||
}
|
||||
@@ -849,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;
|
||||
}
|
||||
}
|
||||
@@ -894,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;
|
||||
}
|
||||
|
||||
@@ -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,109 +1,77 @@
|
||||
//! Shared TCP socket tuning for [`crate::tcp`] and [`crate::backbone`].
|
||||
//! Shared TCP socket tuning for [`crate::tcp`], [`crate::backbone`],
|
||||
//! [`crate::i2p`], and [`crate::rnode`] (TCP transport).
|
||||
//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux
|
||||
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT.
|
||||
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT. All helpers are generic over
|
||||
//! the raw-fd/raw-socket borrow, so they accept tokio and std streams alike.
|
||||
//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key.
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
|
||||
/// Borrow the raw fd/socket as a `socket2::Socket` without taking ownership
|
||||
/// (`ManuallyDrop` keeps the destructor from closing it).
|
||||
#[cfg(unix)]
|
||||
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_ref().as_raw_fd();
|
||||
fn with_socket2<S: std::os::fd::AsRawFd, R>(
|
||||
stream: &S,
|
||||
f: impl FnOnce(&socket2::Socket) -> R,
|
||||
) -> R {
|
||||
use std::os::fd::FromRawFd;
|
||||
// SAFETY: we borrow the fd without taking ownership (ManuallyDrop ensures
|
||||
// the socket2::Socket destructor does not close the fd).
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
sock.set_keepalive(true)?;
|
||||
Ok(())
|
||||
let sock =
|
||||
std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(stream.as_raw_fd()) });
|
||||
f(&sock)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_ref().as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
sock.set_keepalive(true)?;
|
||||
Ok(())
|
||||
fn with_socket2<S: std::os::windows::io::AsRawSocket, R>(
|
||||
stream: &S,
|
||||
f: impl FnOnce(&socket2::Socket) -> R,
|
||||
) -> R {
|
||||
use std::os::windows::io::FromRawSocket;
|
||||
// SAFETY: same borrow-without-ownership contract as the unix variant.
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe {
|
||||
socket2::Socket::from_raw_socket(stream.as_raw_socket())
|
||||
});
|
||||
f(&sock)
|
||||
}
|
||||
|
||||
/// Enable portable `SO_KEEPALIVE` on a blocking std TCP stream.
|
||||
/// Platform bound for streams the tuning helpers accept: anything exposing
|
||||
/// the raw socket handle (tokio `TcpStream`, std `TcpStream`, …).
|
||||
#[cfg(unix)]
|
||||
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_raw_fd();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
sock.set_keepalive(true)?;
|
||||
Ok(())
|
||||
}
|
||||
pub trait RawStream: std::os::fd::AsRawFd {}
|
||||
#[cfg(unix)]
|
||||
impl<T: std::os::fd::AsRawFd> RawStream for T {}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
sock.set_keepalive(true)?;
|
||||
Ok(())
|
||||
pub trait RawStream: std::os::windows::io::AsRawSocket {}
|
||||
#[cfg(windows)]
|
||||
impl<T: std::os::windows::io::AsRawSocket> RawStream for T {}
|
||||
|
||||
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
|
||||
pub fn set_keepalive<S: RawStream>(stream: &S) -> std::io::Result<()> {
|
||||
with_socket2(stream, |sock| sock.set_keepalive(true))
|
||||
}
|
||||
|
||||
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
|
||||
#[cfg(unix)]
|
||||
pub fn set_keepalive_tuned(
|
||||
stream: &TcpStream,
|
||||
pub fn set_keepalive_tuned<S: RawStream>(
|
||||
stream: &S,
|
||||
idle: Duration,
|
||||
intvl: Duration,
|
||||
retries: u32,
|
||||
user_timeout: Duration,
|
||||
) {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_ref().as_raw_fd();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
|
||||
with_socket2(stream, |sock| {
|
||||
apply_tuned_keepalive(sock, idle, intvl, retries, user_timeout)
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_keepalive_tuned(
|
||||
stream: &TcpStream,
|
||||
idle: Duration,
|
||||
intvl: Duration,
|
||||
retries: u32,
|
||||
user_timeout: Duration,
|
||||
) {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_ref().as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
|
||||
}
|
||||
|
||||
/// Tuned keepalive for blocking std TCP streams. Best-effort.
|
||||
#[cfg(unix)]
|
||||
pub fn set_keepalive_tuned_std(
|
||||
stream: &std::net::TcpStream,
|
||||
idle: Duration,
|
||||
intvl: Duration,
|
||||
retries: u32,
|
||||
user_timeout: Duration,
|
||||
) {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_raw_fd();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_keepalive_tuned_std(
|
||||
stream: &std::net::TcpStream,
|
||||
idle: Duration,
|
||||
intvl: Duration,
|
||||
retries: u32,
|
||||
user_timeout: Duration,
|
||||
) {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
|
||||
/// Raise TCP send/recv buffers; best-effort.
|
||||
pub fn set_socket_buffers<S: RawStream>(stream: &S, size: usize) {
|
||||
with_socket2(stream, |sock| {
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
});
|
||||
}
|
||||
|
||||
fn apply_tuned_keepalive(
|
||||
@@ -136,42 +104,24 @@ fn apply_tuned_keepalive(
|
||||
let _ = user_timeout;
|
||||
}
|
||||
|
||||
/// Raise TCP send/recv buffers; best-effort.
|
||||
#[cfg(unix)]
|
||||
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_ref().as_raw_fd();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_ref().as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
}
|
||||
|
||||
/// Raise TCP send/recv buffers on a blocking std TCP stream; best-effort.
|
||||
#[cfg(unix)]
|
||||
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
let raw_fd = stream.as_raw_fd();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
|
||||
use std::os::windows::io::{AsRawSocket, FromRawSocket};
|
||||
let raw = stream.as_raw_socket();
|
||||
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
|
||||
let _ = sock.set_recv_buffer_size(size);
|
||||
let _ = sock.set_send_buffer_size(size);
|
||||
/// Resolve interface name to its IPv4 broadcast address; `None` if the
|
||||
/// interface is missing or has no broadcast-capable IPv4. Python UDP
|
||||
/// `device =` semantics (`get_broadcast_for_if`).
|
||||
pub fn iface_broadcast_for(name: &str) -> Option<std::net::Ipv4Addr> {
|
||||
let ifaces = match if_addrs::get_if_addrs() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
ifaces.into_iter().filter(|i| i.name == name).find_map(|i| {
|
||||
if let if_addrs::IfAddr::V4(v4) = i.addr {
|
||||
v4.broadcast
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
|
||||
@@ -210,7 +160,7 @@ pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
#[tokio::test]
|
||||
async fn keepalive_and_buffers_apply_without_panic() {
|
||||
@@ -244,6 +194,7 @@ mod tests {
|
||||
set_socket_buffers(&client, 131_072);
|
||||
}
|
||||
|
||||
/// The same generic helpers must accept blocking std streams.
|
||||
#[test]
|
||||
fn std_keepalive_and_buffers_apply_without_panic() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
@@ -252,17 +203,17 @@ mod tests {
|
||||
let client = std::net::TcpStream::connect(addr).unwrap();
|
||||
let server = accept.join().unwrap();
|
||||
|
||||
set_keepalive_std(&server).expect("server set_keepalive_std");
|
||||
set_keepalive_std(&client).expect("client set_keepalive_std");
|
||||
set_keepalive(&server).expect("server set_keepalive");
|
||||
set_keepalive(&client).expect("client set_keepalive");
|
||||
|
||||
set_keepalive_tuned_std(
|
||||
set_keepalive_tuned(
|
||||
&server,
|
||||
Duration::from_secs(5),
|
||||
Duration::from_secs(2),
|
||||
12,
|
||||
Duration::from_secs(24),
|
||||
);
|
||||
set_keepalive_tuned_std(
|
||||
set_keepalive_tuned(
|
||||
&client,
|
||||
Duration::from_secs(5),
|
||||
Duration::from_secs(2),
|
||||
@@ -270,8 +221,8 @@ mod tests {
|
||||
Duration::from_secs(24),
|
||||
);
|
||||
|
||||
set_socket_buffers_std(&server, 131_072);
|
||||
set_socket_buffers_std(&client, 131_072);
|
||||
set_socket_buffers(&server, 131_072);
|
||||
set_socket_buffers(&client, 131_072);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+161
-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);
|
||||
@@ -401,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),
|
||||
@@ -435,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);
|
||||
|
||||
@@ -489,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");
|
||||
@@ -575,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";
|
||||
@@ -634,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
|
||||
@@ -718,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)
|
||||
@@ -761,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
|
||||
|
||||
@@ -82,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 {
|
||||
|
||||
@@ -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() {
|
||||
@@ -185,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");
|
||||
|
||||
+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],
|
||||
@@ -2115,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() {
|
||||
@@ -2761,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
|
||||
@@ -4083,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.
@@ -24,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"] }
|
||||
|
||||
@@ -62,7 +62,20 @@ pub struct KissSerialConfig {
|
||||
pub name: String,
|
||||
pub port: String,
|
||||
pub baud_rate: u32,
|
||||
pub data_bits: u8,
|
||||
pub parity: String,
|
||||
pub stop_bits: u8,
|
||||
pub mode: InterfaceMode,
|
||||
/// TNC timing, config units are milliseconds (Python defaults 350/20/64/20;
|
||||
/// persistence is a raw 0-255 CSMA p-value, not ms).
|
||||
pub preamble_ms: u32,
|
||||
pub txtail_ms: u32,
|
||||
pub persistence: u8,
|
||||
pub slottime_ms: u32,
|
||||
pub flow_control: bool,
|
||||
/// Station-ID beacon: seconds between IDs, sent only after data TX.
|
||||
pub id_interval: Option<u64>,
|
||||
pub id_callsign: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -90,6 +103,15 @@ pub struct RNodeInterfaceConfig {
|
||||
pub coding_rate: u8,
|
||||
pub tx_power: i8,
|
||||
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>,
|
||||
/// Station-ID beacon: seconds between IDs, sent only after data TX.
|
||||
pub id_interval: Option<u64>,
|
||||
pub id_callsign: Option<String>,
|
||||
}
|
||||
|
||||
/// LoRa RNode reached over Bluetooth LE.
|
||||
@@ -105,6 +127,15 @@ pub struct BleRNodeInterfaceConfig {
|
||||
pub coding_rate: u8,
|
||||
pub tx_power: i8,
|
||||
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>,
|
||||
/// Station-ID beacon: seconds between IDs, sent only after data TX.
|
||||
pub id_interval: Option<u64>,
|
||||
pub id_callsign: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -145,6 +176,9 @@ pub struct RNodeMultiInterfaceConfig {
|
||||
pub flow_control: bool,
|
||||
pub subinterfaces: Vec<RNodeSubInterfaceConfig>,
|
||||
pub mode: InterfaceMode,
|
||||
/// Parent-level station-ID beacon (sent on all subinterfaces when due).
|
||||
pub id_interval: Option<u64>,
|
||||
pub id_callsign: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
@@ -173,6 +207,9 @@ pub struct AX25KISSInterfaceConfig {
|
||||
pub name: String,
|
||||
pub port: String,
|
||||
pub baud_rate: u32,
|
||||
pub data_bits: u8,
|
||||
pub parity: String,
|
||||
pub stop_bits: u8,
|
||||
pub callsign: String,
|
||||
pub ssid: u8,
|
||||
pub preamble: u32,
|
||||
@@ -214,6 +251,27 @@ fn parse_interface_mode(s: &str) -> Option<InterfaceMode> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Config ports arrive as u64; values over 65535 are config errors, not
|
||||
/// silent `as u16` wraps (70000 would otherwise become 4464).
|
||||
fn parse_port(name: &str, field: &str, value: u64) -> Result<u16, InterfaceFactoryError> {
|
||||
u16::try_from(value).map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("{value} is not a valid port (0-65535)"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Optional port field: validate only when present.
|
||||
fn parse_port_opt(
|
||||
name: &str,
|
||||
field: &str,
|
||||
section: &ConfigSection,
|
||||
) -> Result<Option<u16>, InterfaceFactoryError> {
|
||||
section
|
||||
.get_uint(field)
|
||||
.map(|v| parse_port(name, field, v))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn synthesize_interface(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -228,6 +286,17 @@ pub fn synthesize_interface(
|
||||
return Err(InterfaceFactoryError::Disabled(name.to_string()));
|
||||
}
|
||||
|
||||
// IFAC sizes outside 1..=64 would panic deep in the transport actor on
|
||||
// first egress (`ifac_sign` asserts); reject at config parse instead.
|
||||
if let Some(size) = section.get_uint("ifac_size") {
|
||||
if !(1..=64).contains(&size) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.ifac_size"),
|
||||
message: format!("{size} is out of range (1-64 bytes)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let iface_type = section.get("type").ok_or_else(|| {
|
||||
warn!(interface = %name, "interface missing 'type' field");
|
||||
InterfaceFactoryError::MissingField {
|
||||
@@ -323,13 +392,16 @@ fn synthesize_tcp_client(
|
||||
field: "target_host".to_string(),
|
||||
})?;
|
||||
|
||||
let port =
|
||||
let port = parse_port(
|
||||
name,
|
||||
"target_port",
|
||||
section
|
||||
.get_uint("target_port")
|
||||
.ok_or_else(|| InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: "target_port".to_string(),
|
||||
})? as u16;
|
||||
})?,
|
||||
)?;
|
||||
|
||||
let mut config = TcpClientConfig::new(name, host, port);
|
||||
config.mode = mode;
|
||||
@@ -340,6 +412,16 @@ fn synthesize_tcp_client(
|
||||
if let Some(timeout) = section.get_uint("connect_timeout") {
|
||||
config.connect_timeout_secs = timeout;
|
||||
}
|
||||
if let Some(mtu) = section.get_uint("fixed_mtu") {
|
||||
// Python TCPInterface.py:112 — fixed MTU below protocol MTU is invalid.
|
||||
if (mtu as usize) < rns_wire::constants::MTU {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.fixed_mtu"),
|
||||
message: format!("{mtu} is below the protocol MTU of 500"),
|
||||
});
|
||||
}
|
||||
config.fixed_mtu = Some(mtu as u32);
|
||||
}
|
||||
if let Some(retries) = section.get_uint("max_reconnect_tries") {
|
||||
config.max_reconnect_tries = Some(retries as usize);
|
||||
}
|
||||
@@ -354,13 +436,16 @@ fn synthesize_tcp_server(
|
||||
) -> Result<InterfaceConfig, InterfaceFactoryError> {
|
||||
let ip = section.get("listen_ip").unwrap_or("0.0.0.0");
|
||||
|
||||
let port =
|
||||
let port = parse_port(
|
||||
name,
|
||||
"listen_port",
|
||||
section
|
||||
.get_uint("listen_port")
|
||||
.ok_or_else(|| InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: "listen_port".to_string(),
|
||||
})? as u16;
|
||||
})?,
|
||||
)?;
|
||||
|
||||
let mut config = TcpServerConfig::new(name, ip, port);
|
||||
config.mode = mode;
|
||||
@@ -371,6 +456,9 @@ fn synthesize_tcp_server(
|
||||
if let Some(ipv6) = section.get_bool("prefer_ipv6") {
|
||||
config.prefer_ipv6 = ipv6;
|
||||
}
|
||||
if let Some(device) = section.get("device") {
|
||||
config.device = Some(device.to_string());
|
||||
}
|
||||
|
||||
Ok(InterfaceConfig::TcpServer(config))
|
||||
}
|
||||
@@ -386,15 +474,11 @@ fn synthesize_udp(
|
||||
if let Some(ip) = section.get("listen_ip") {
|
||||
config.listen_ip = Some(ip.to_string());
|
||||
}
|
||||
if let Some(port) = section.get_uint("listen_port") {
|
||||
config.listen_port = Some(port as u16);
|
||||
}
|
||||
config.listen_port = parse_port_opt(name, "listen_port", section)?;
|
||||
if let Some(ip) = section.get("forward_ip") {
|
||||
config.forward_ip = Some(ip.to_string());
|
||||
}
|
||||
if let Some(port) = section.get_uint("forward_port") {
|
||||
config.forward_port = Some(port as u16);
|
||||
}
|
||||
config.forward_port = parse_port_opt(name, "forward_port", section)?;
|
||||
if let Some(device) = section.get("device") {
|
||||
config.device = Some(device.to_string());
|
||||
}
|
||||
@@ -463,11 +547,23 @@ fn synthesize_kiss_serial(
|
||||
.or_else(|| section.get_uint("baud_rate"))
|
||||
.unwrap_or(9600) as u32;
|
||||
|
||||
// Python KISSInterface.py:86-97 — TNC timing defaults 350/20/64/20,
|
||||
// serial 8N1, flow_control off, optional station-ID beacon.
|
||||
Ok(InterfaceConfig::KissSerial(KissSerialConfig {
|
||||
name: name.to_string(),
|
||||
port,
|
||||
baud_rate,
|
||||
data_bits: section.get_uint("databits").unwrap_or(8) as u8,
|
||||
parity: section.get("parity").unwrap_or("N").to_string(),
|
||||
stop_bits: section.get_uint("stopbits").unwrap_or(1) as u8,
|
||||
mode,
|
||||
preamble_ms: section.get_uint("preamble").unwrap_or(350) as u32,
|
||||
txtail_ms: section.get_uint("txtail").unwrap_or(20) as u32,
|
||||
persistence: section.get_uint("persistence").unwrap_or(64) as u8,
|
||||
slottime_ms: section.get_uint("slottime").unwrap_or(20) as u32,
|
||||
flow_control: section.get_bool("flow_control").unwrap_or(false),
|
||||
id_interval: section.get_uint("id_interval"),
|
||||
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -490,8 +586,8 @@ fn synthesize_auto(
|
||||
None => rns_interface::auto::DiscoveryScope::Link,
|
||||
};
|
||||
|
||||
let discovery_port = section.get_uint("discovery_port").unwrap_or(29716) as u16;
|
||||
let data_port = section.get_uint("data_port").unwrap_or(42671) as u16;
|
||||
let discovery_port = parse_port_opt(name, "discovery_port", section)?.unwrap_or(29716);
|
||||
let data_port = parse_port_opt(name, "data_port", section)?.unwrap_or(42671);
|
||||
|
||||
let multicast_address_type = match section.get("multicast_address_type") {
|
||||
Some(s) => rns_interface::auto::McastAddrType::from_str(s).map_err(|message| {
|
||||
@@ -552,30 +648,10 @@ fn synthesize_rnode(
|
||||
})?
|
||||
.to_string();
|
||||
|
||||
let frequency =
|
||||
section
|
||||
.get_uint("frequency")
|
||||
.ok_or_else(|| InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: "frequency".to_string(),
|
||||
})? as u32;
|
||||
let (frequency, bandwidth, spreading_factor, coding_rate, tx_power) =
|
||||
require_rnode_radio_params(name, section)?;
|
||||
|
||||
let bandwidth = section.get_uint("bandwidth").unwrap_or(125000) as u32;
|
||||
|
||||
let spreading_factor = section
|
||||
.get_uint("spreadingfactor")
|
||||
.or_else(|| section.get_uint("spreading_factor"))
|
||||
.unwrap_or(7) as u8;
|
||||
|
||||
let coding_rate = section
|
||||
.get_uint("codingrate")
|
||||
.or_else(|| section.get_uint("coding_rate"))
|
||||
.unwrap_or(5) as u8;
|
||||
|
||||
let tx_power = section
|
||||
.get_int("txpower")
|
||||
.or_else(|| section.get_int("tx_power"))
|
||||
.unwrap_or(17) as i8;
|
||||
let (flow_control, st_alock, lt_alock) = parse_rnode_airtime(name, section)?;
|
||||
|
||||
Ok(InterfaceConfig::RNode(RNodeInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
@@ -586,9 +662,90 @@ fn synthesize_rnode(
|
||||
coding_rate,
|
||||
tx_power,
|
||||
mode,
|
||||
flow_control,
|
||||
st_alock,
|
||||
lt_alock,
|
||||
id_interval: section.get_uint("id_interval"),
|
||||
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Radio parameters are deliberately required: Python errors when they are
|
||||
/// absent (RNodeInterface validation fails on the 0 fallbacks), and silently
|
||||
/// inventing RF parameters — especially TX power — risks misconfigured
|
||||
/// transmissions. Documented in fix-registry (final sweep decision items).
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
fn require_rnode_radio_params(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
) -> Result<(u32, u32, u8, u8, i8), InterfaceFactoryError> {
|
||||
let missing = |field: &str| InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: field.to_string(),
|
||||
};
|
||||
let frequency = section
|
||||
.get_uint("frequency")
|
||||
.ok_or_else(|| missing("frequency"))? as u32;
|
||||
let bandwidth = section
|
||||
.get_uint("bandwidth")
|
||||
.ok_or_else(|| missing("bandwidth"))? as u32;
|
||||
let spreading_factor = section
|
||||
.get_uint("spreadingfactor")
|
||||
.or_else(|| section.get_uint("spreading_factor"))
|
||||
.ok_or_else(|| missing("spreadingfactor"))? as u8;
|
||||
let coding_rate = section
|
||||
.get_uint("codingrate")
|
||||
.or_else(|| section.get_uint("coding_rate"))
|
||||
.ok_or_else(|| missing("codingrate"))? as u8;
|
||||
let tx_power = section
|
||||
.get_int("txpower")
|
||||
.or_else(|| section.get_int("tx_power"))
|
||||
.ok_or_else(|| missing("txpower"))? as i8;
|
||||
Ok((
|
||||
frequency,
|
||||
bandwidth,
|
||||
spreading_factor,
|
||||
coding_rate,
|
||||
tx_power,
|
||||
))
|
||||
}
|
||||
|
||||
/// Shared RNode airtime/flow-control parsing. Python `RNodeInterface.py:156-160`:
|
||||
/// `flow_control` defaults off, `airtime_limit_short`/`airtime_limit_long` are
|
||||
/// duty-cycle percentages validated to 0..=100.
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
fn parse_rnode_airtime(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
) -> Result<(bool, Option<f32>, Option<f32>), InterfaceFactoryError> {
|
||||
let flow_control = section.get_bool("flow_control").unwrap_or(false);
|
||||
let st_alock = section
|
||||
.get_float("airtime_limit_short")
|
||||
.or_else(|| section.get_float("st_alock"))
|
||||
.map(|v| v as f32);
|
||||
let lt_alock = section
|
||||
.get_float("airtime_limit_long")
|
||||
.or_else(|| section.get_float("lt_alock"))
|
||||
.map(|v| v as f32);
|
||||
if let Some(v) = st_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_short"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if let Some(v) = lt_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_long"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
Ok((flow_control, st_alock, lt_alock))
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
fn synthesize_ble_rnode(
|
||||
name: &str,
|
||||
@@ -603,30 +760,10 @@ fn synthesize_ble_rnode(
|
||||
})?
|
||||
.to_string();
|
||||
|
||||
let frequency =
|
||||
section
|
||||
.get_uint("frequency")
|
||||
.ok_or_else(|| InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: "frequency".to_string(),
|
||||
})? as u32;
|
||||
let (frequency, bandwidth, spreading_factor, coding_rate, tx_power) =
|
||||
require_rnode_radio_params(name, section)?;
|
||||
|
||||
let bandwidth = section.get_uint("bandwidth").unwrap_or(125000) as u32;
|
||||
|
||||
let spreading_factor = section
|
||||
.get_uint("spreadingfactor")
|
||||
.or_else(|| section.get_uint("spreading_factor"))
|
||||
.unwrap_or(7) as u8;
|
||||
|
||||
let coding_rate = section
|
||||
.get_uint("codingrate")
|
||||
.or_else(|| section.get_uint("coding_rate"))
|
||||
.unwrap_or(5) as u8;
|
||||
|
||||
let tx_power = section
|
||||
.get_int("txpower")
|
||||
.or_else(|| section.get_int("tx_power"))
|
||||
.unwrap_or(17) as i8;
|
||||
let (flow_control, st_alock, lt_alock) = parse_rnode_airtime(name, section)?;
|
||||
|
||||
Ok(InterfaceConfig::BleRNode(BleRNodeInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
@@ -637,6 +774,11 @@ fn synthesize_ble_rnode(
|
||||
coding_rate,
|
||||
tx_power,
|
||||
mode,
|
||||
flow_control,
|
||||
st_alock,
|
||||
lt_alock,
|
||||
id_interval: section.get_uint("id_interval"),
|
||||
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -645,9 +787,8 @@ fn synthesize_local(
|
||||
section: &ConfigSection,
|
||||
mode: InterfaceMode,
|
||||
) -> Result<InterfaceConfig, InterfaceFactoryError> {
|
||||
let port = section
|
||||
.get_uint("port")
|
||||
.unwrap_or(crate::constants::LOCAL_INTERFACE_PORT as u64) as u16;
|
||||
let port =
|
||||
parse_port_opt(name, "port", section)?.unwrap_or(crate::constants::LOCAL_INTERFACE_PORT);
|
||||
|
||||
Ok(InterfaceConfig::Local(LocalInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
@@ -675,7 +816,7 @@ fn synthesize_i2p(
|
||||
.get("i2p_sam_host")
|
||||
.unwrap_or("127.0.0.1")
|
||||
.to_string();
|
||||
let i2p_sam_port = section.get_uint("i2p_sam_port").unwrap_or(7656) as u16;
|
||||
let i2p_sam_port = parse_port_opt(name, "i2p_sam_port", section)?.unwrap_or(7656);
|
||||
|
||||
Ok(InterfaceConfig::I2P(I2PInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
@@ -765,25 +906,10 @@ fn synthesize_rnode_multi(
|
||||
});
|
||||
}
|
||||
|
||||
let frequency = sub_section.get_uint("frequency").ok_or_else(|| {
|
||||
InterfaceFactoryError::MissingField {
|
||||
name: format!("{name}/{sub_name}"),
|
||||
field: "frequency".to_string(),
|
||||
}
|
||||
})? as u32;
|
||||
let bandwidth = sub_section.get_uint("bandwidth").unwrap_or(125000) as u32;
|
||||
let spreading_factor = sub_section
|
||||
.get_uint("spreadingfactor")
|
||||
.or_else(|| sub_section.get_uint("spreading_factor"))
|
||||
.unwrap_or(7) as u8;
|
||||
let coding_rate = sub_section
|
||||
.get_uint("codingrate")
|
||||
.or_else(|| sub_section.get_uint("coding_rate"))
|
||||
.unwrap_or(5) as u8;
|
||||
let tx_power = sub_section
|
||||
.get_uint("txpower")
|
||||
.or_else(|| sub_section.get_uint("tx_power"))
|
||||
.unwrap_or(14) as u8;
|
||||
let sub_full_name = format!("{name}/{sub_name}");
|
||||
let (frequency, bandwidth, spreading_factor, coding_rate, tx_power) =
|
||||
require_rnode_radio_params(&sub_full_name, sub_section)?;
|
||||
let tx_power = tx_power as u8;
|
||||
let flow_control = sub_section
|
||||
.get_bool("flow_control")
|
||||
.unwrap_or(parent_flow_control);
|
||||
@@ -847,6 +973,8 @@ fn synthesize_rnode_multi(
|
||||
flow_control: parent_flow_control,
|
||||
subinterfaces,
|
||||
mode,
|
||||
id_interval: section.get_uint("id_interval"),
|
||||
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -933,10 +1061,26 @@ fn synthesize_ax25kiss(
|
||||
.or_else(|| section.get_uint("baud_rate"))
|
||||
.unwrap_or(9600) as u32;
|
||||
|
||||
let ssid = section.get_uint("ssid").unwrap_or(0) as u8;
|
||||
let preamble = section.get_uint("preamble").unwrap_or(150) as u32;
|
||||
let txtail = section.get_uint("txtail").unwrap_or(10) as u32;
|
||||
let persistence = section.get_uint("persistence").unwrap_or(200) as u32;
|
||||
// Python AX25KISSInterface requires an explicit 0..=15 SSID
|
||||
// (default -1 fails validation, AX25KISSInterface.py:138-139).
|
||||
let ssid_raw = section
|
||||
.get_int("ssid")
|
||||
.ok_or_else(|| InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: "ssid".to_string(),
|
||||
})?;
|
||||
if !(0..=15).contains(&ssid_raw) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.ssid"),
|
||||
message: format!("{ssid_raw} is outside 0..=15"),
|
||||
});
|
||||
}
|
||||
let ssid = ssid_raw as u8;
|
||||
|
||||
// Python defaults: 350/20/64/20 (AX25KISSInterface.py:141-144).
|
||||
let preamble = section.get_uint("preamble").unwrap_or(350) as u32;
|
||||
let txtail = section.get_uint("txtail").unwrap_or(20) as u32;
|
||||
let persistence = section.get_uint("persistence").unwrap_or(64) as u32;
|
||||
let slottime = section.get_uint("slottime").unwrap_or(20) as u32;
|
||||
let flow_control = section.get_bool("flow_control").unwrap_or(false);
|
||||
|
||||
@@ -944,6 +1088,9 @@ fn synthesize_ax25kiss(
|
||||
name: name.to_string(),
|
||||
port,
|
||||
baud_rate,
|
||||
data_bits: section.get_uint("databits").unwrap_or(8) as u8,
|
||||
parity: section.get("parity").unwrap_or("N").to_string(),
|
||||
stop_bits: section.get_uint("stopbits").unwrap_or(1) as u8,
|
||||
callsign,
|
||||
ssid,
|
||||
preamble,
|
||||
@@ -966,11 +1113,19 @@ fn synthesize_backbone(
|
||||
.get("target_host")
|
||||
.or_else(|| section.get("remote"))
|
||||
.map(|s| s.to_string());
|
||||
let port = section
|
||||
.get_uint("port")
|
||||
.or_else(|| section.get_uint("listen_port"))
|
||||
.or_else(|| section.get_uint("target_port"))
|
||||
.unwrap_or(4242) as u16;
|
||||
// Python BackboneInterface.py:133-134 errors without an explicit port.
|
||||
let port = parse_port(
|
||||
name,
|
||||
"port",
|
||||
section
|
||||
.get_uint("port")
|
||||
.or_else(|| section.get_uint("listen_port"))
|
||||
.or_else(|| section.get_uint("target_port"))
|
||||
.ok_or_else(|| InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: "port".to_string(),
|
||||
})?,
|
||||
)?;
|
||||
let device = section.get("device").map(|s| s.to_string());
|
||||
let prefer_ipv6 = section.get_bool("prefer_ipv6").unwrap_or(false);
|
||||
let connect_timeout = section.get_uint("connect_timeout").unwrap_or(5);
|
||||
@@ -1177,6 +1332,70 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// T1-11: ports over 65535 are config errors, never silent u16 wraps.
|
||||
#[test]
|
||||
fn test_out_of_range_port_rejected() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "TCPClientInterface");
|
||||
section.set("target_host", "127.0.0.1");
|
||||
section.set("target_port", "70000");
|
||||
match synthesize_interface("tcp_badport", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, message }) => {
|
||||
assert_eq!(field, "tcp_badport.target_port");
|
||||
assert!(message.contains("70000"));
|
||||
}
|
||||
other => panic!("expected InvalidValue, got {other:?}"),
|
||||
}
|
||||
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "UDPInterface");
|
||||
section.set("listen_ip", "0.0.0.0");
|
||||
section.set("listen_port", "65536");
|
||||
match synthesize_interface("udp_badport", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) => {
|
||||
assert_eq!(field, "udp_badport.listen_port");
|
||||
}
|
||||
other => panic!("expected InvalidValue, got {other:?}"),
|
||||
}
|
||||
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "AutoInterface");
|
||||
section.set("discovery_port", "99999");
|
||||
match synthesize_interface("auto_badport", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) => {
|
||||
assert_eq!(field, "auto_badport.discovery_port");
|
||||
}
|
||||
other => panic!("expected InvalidValue, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// T1-11: ifac_size outside 1..=64 used to panic the transport actor on
|
||||
/// first egress; it must be a parse-time config error.
|
||||
#[test]
|
||||
fn test_ifac_size_out_of_range_rejected() {
|
||||
for bad in ["0", "65", "4096"] {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "TCPClientInterface");
|
||||
section.set("target_host", "127.0.0.1");
|
||||
section.set("target_port", "4242");
|
||||
section.set("ifac_size", bad);
|
||||
match synthesize_interface("tcp_ifac", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) => {
|
||||
assert_eq!(field, "tcp_ifac.ifac_size");
|
||||
}
|
||||
other => panic!("expected InvalidValue for ifac_size={bad}, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// In-range sizes still parse.
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "TCPClientInterface");
|
||||
section.set("target_host", "127.0.0.1");
|
||||
section.set("target_port", "4242");
|
||||
section.set("ifac_size", "64");
|
||||
assert!(synthesize_interface("tcp_ifac_ok", §ion).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_missing_type() {
|
||||
let section = ConfigSection::new();
|
||||
@@ -1265,6 +1484,202 @@ mod tests {
|
||||
assert_eq!(pi.announce_rate_penalty, Some(0));
|
||||
}
|
||||
|
||||
/// Python KISSInterface.py:86-97 defaults: 350/20/64/20, 8N1, no beacon.
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_kiss_defaults_match_python() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "KISSInterface");
|
||||
section.set("port", "/dev/ttyUSB1");
|
||||
|
||||
match synthesize_interface("kiss_defaults", §ion).unwrap() {
|
||||
InterfaceConfig::KissSerial(c) => {
|
||||
assert_eq!(c.preamble_ms, 350);
|
||||
assert_eq!(c.txtail_ms, 20);
|
||||
assert_eq!(c.persistence, 64);
|
||||
assert_eq!(c.slottime_ms, 20);
|
||||
assert_eq!((c.data_bits, c.parity.as_str(), c.stop_bits), (8, "N", 1));
|
||||
assert!(!c.flow_control);
|
||||
assert!(c.id_interval.is_none() && c.id_callsign.is_none());
|
||||
}
|
||||
_ => panic!("expected KissSerial"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_kiss_full_params_and_beacon() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "KISSInterface");
|
||||
section.set("port", "/dev/ttyUSB1");
|
||||
section.set("preamble", "150");
|
||||
section.set("txtail", "10");
|
||||
section.set("persistence", "200");
|
||||
section.set("slottime", "30");
|
||||
section.set("flow_control", "true");
|
||||
section.set("id_interval", "600");
|
||||
section.set("id_callsign", "MYCALL-0");
|
||||
|
||||
match synthesize_interface("kiss_full", §ion).unwrap() {
|
||||
InterfaceConfig::KissSerial(c) => {
|
||||
assert_eq!(c.preamble_ms, 150);
|
||||
assert_eq!(c.txtail_ms, 10);
|
||||
assert_eq!(c.persistence, 200);
|
||||
assert_eq!(c.slottime_ms, 30);
|
||||
assert!(c.flow_control);
|
||||
assert_eq!(c.id_interval, Some(600));
|
||||
assert_eq!(c.id_callsign.as_deref(), Some("MYCALL-0"));
|
||||
}
|
||||
_ => panic!("expected KissSerial"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python AX25KISSInterface.py:141-144 defaults + 0..=15 SSID requirement.
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_ax25kiss_defaults_and_ssid() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "AX25KISSInterface");
|
||||
section.set("port", "/dev/ttyUSB2");
|
||||
section.set("callsign", "NO1CLL");
|
||||
section.set("ssid", "0");
|
||||
|
||||
match synthesize_interface("ax25_defaults", §ion).unwrap() {
|
||||
InterfaceConfig::AX25KISS(c) => {
|
||||
assert_eq!(c.preamble, 350);
|
||||
assert_eq!(c.txtail, 20);
|
||||
assert_eq!(c.persistence, 64);
|
||||
assert_eq!(c.slottime, 20);
|
||||
}
|
||||
_ => panic!("expected AX25KISS"),
|
||||
}
|
||||
|
||||
let mut no_ssid = ConfigSection::new();
|
||||
no_ssid.set("type", "AX25KISSInterface");
|
||||
no_ssid.set("port", "/dev/ttyUSB2");
|
||||
no_ssid.set("callsign", "NO1CLL");
|
||||
assert!(matches!(
|
||||
synthesize_interface("ax25_no_ssid", &no_ssid),
|
||||
Err(InterfaceFactoryError::MissingField { field, .. }) if field == "ssid"
|
||||
));
|
||||
|
||||
section.set("ssid", "16");
|
||||
assert!(matches!(
|
||||
synthesize_interface("ax25_bad_ssid", §ion),
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) if field.ends_with("ssid")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_tcp_fixed_mtu_and_device() {
|
||||
let mut client = ConfigSection::new();
|
||||
client.set("type", "TCPClientInterface");
|
||||
client.set("target_host", "example.com");
|
||||
client.set("target_port", "4242");
|
||||
client.set("fixed_mtu", "1064");
|
||||
match synthesize_interface("tcp_fixed", &client).unwrap() {
|
||||
InterfaceConfig::TcpClient(c) => assert_eq!(c.fixed_mtu, Some(1064)),
|
||||
_ => panic!("expected TcpClient"),
|
||||
}
|
||||
|
||||
client.set("fixed_mtu", "400");
|
||||
assert!(matches!(
|
||||
synthesize_interface("tcp_small_mtu", &client),
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) if field.ends_with("fixed_mtu")
|
||||
));
|
||||
|
||||
let mut server = ConfigSection::new();
|
||||
server.set("type", "TCPServerInterface");
|
||||
server.set("listen_port", "4242");
|
||||
server.set("device", "eth0");
|
||||
match synthesize_interface("tcp_dev", &server).unwrap() {
|
||||
InterfaceConfig::TcpServer(c) => assert_eq!(c.device.as_deref(), Some("eth0")),
|
||||
_ => panic!("expected TcpServer"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_beacon_keys() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "/dev/ttyACM0");
|
||||
section.set("frequency", "868000000");
|
||||
set_rnode_radio_params(&mut section);
|
||||
section.set("id_interval", "600");
|
||||
section.set("id_callsign", "MYCALL-0");
|
||||
|
||||
match synthesize_interface("rnode_beacon", §ion).unwrap() {
|
||||
InterfaceConfig::RNode(c) => {
|
||||
assert_eq!(c.id_interval, Some(600));
|
||||
assert_eq!(c.id_callsign.as_deref(), Some("MYCALL-0"));
|
||||
}
|
||||
_ => panic!("expected RNode"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_airtime_and_flow_control() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "/dev/ttyACM0");
|
||||
section.set("frequency", "868000000");
|
||||
set_rnode_radio_params(&mut section);
|
||||
section.set("flow_control", "true");
|
||||
section.set("airtime_limit_short", "33");
|
||||
section.set("airtime_limit_long", "3.3");
|
||||
|
||||
let config = synthesize_interface("rnode_airtime", §ion).unwrap();
|
||||
match config {
|
||||
InterfaceConfig::RNode(c) => {
|
||||
assert!(c.flow_control);
|
||||
assert_eq!(c.st_alock, Some(33.0));
|
||||
assert_eq!(c.lt_alock, Some(3.3));
|
||||
}
|
||||
_ => panic!("expected RNode"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python parity: flow_control defaults off, airtime limits unset.
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_airtime_defaults() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "/dev/ttyACM0");
|
||||
section.set("frequency", "868000000");
|
||||
set_rnode_radio_params(&mut section);
|
||||
|
||||
let config = synthesize_interface("rnode_defaults", §ion).unwrap();
|
||||
match config {
|
||||
InterfaceConfig::RNode(c) => {
|
||||
assert!(!c.flow_control);
|
||||
assert!(c.st_alock.is_none());
|
||||
assert!(c.lt_alock.is_none());
|
||||
}
|
||||
_ => panic!("expected RNode"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_airtime_out_of_range() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "/dev/ttyACM0");
|
||||
section.set("frequency", "868000000");
|
||||
set_rnode_radio_params(&mut section);
|
||||
section.set("airtime_limit_long", "101");
|
||||
|
||||
match synthesize_interface("rnode_bad_alock", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) => {
|
||||
assert!(field.ends_with("airtime_limit_long"));
|
||||
}
|
||||
other => panic!("expected InvalidValue, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_serial() {
|
||||
@@ -1438,6 +1853,7 @@ mod tests {
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "/dev/ttyACM0");
|
||||
section.set("frequency", "868000000");
|
||||
set_rnode_radio_params(&mut section);
|
||||
section.set("bandwidth", "125000");
|
||||
section.set("spreadingfactor", "7");
|
||||
section.set("codingrate", "5");
|
||||
@@ -1460,15 +1876,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn set_rnode_radio_params(section: &mut ConfigSection) {
|
||||
section.set("bandwidth", "125000");
|
||||
section.set("spreadingfactor", "7");
|
||||
section.set("codingrate", "5");
|
||||
section.set("txpower", "17");
|
||||
}
|
||||
|
||||
/// Python parity: all radio params required — no invented defaults.
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_defaults() {
|
||||
fn test_synthesize_rnode_requires_radio_params() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "/dev/ttyACM0");
|
||||
section.set("frequency", "915000000");
|
||||
|
||||
let config = synthesize_interface("rnode_defaults", §ion).unwrap();
|
||||
assert!(matches!(
|
||||
synthesize_interface("rnode_missing", §ion),
|
||||
Err(InterfaceFactoryError::MissingField { field, .. }) if field == "bandwidth"
|
||||
));
|
||||
|
||||
set_rnode_radio_params(&mut section);
|
||||
let config = synthesize_interface("rnode_full", §ion).unwrap();
|
||||
match config {
|
||||
InterfaceConfig::RNode(c) => {
|
||||
assert_eq!(c.bandwidth, 125000);
|
||||
@@ -1487,6 +1918,7 @@ mod tests {
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "tcp://rnode.local");
|
||||
section.set("frequency", "915000000");
|
||||
set_rnode_radio_params(&mut section);
|
||||
|
||||
let config = synthesize_interface("rnode_tcp", §ion).unwrap();
|
||||
match config {
|
||||
@@ -1579,7 +2011,17 @@ mod tests {
|
||||
name: "k".to_string(),
|
||||
port: "/dev/ttyS0".to_string(),
|
||||
baud_rate: 9600,
|
||||
data_bits: 8,
|
||||
parity: "N".to_string(),
|
||||
stop_bits: 1,
|
||||
mode: InterfaceMode::Full,
|
||||
preamble_ms: 350,
|
||||
txtail_ms: 20,
|
||||
persistence: 64,
|
||||
slottime_ms: 20,
|
||||
flow_control: false,
|
||||
id_interval: None,
|
||||
id_callsign: None,
|
||||
});
|
||||
let _auto = InterfaceConfig::Auto(AutoInterfaceConfig {
|
||||
name: "a".to_string(),
|
||||
@@ -1602,6 +2044,11 @@ mod tests {
|
||||
coding_rate: 5,
|
||||
tx_power: 17,
|
||||
mode: InterfaceMode::Full,
|
||||
flow_control: false,
|
||||
st_alock: None,
|
||||
lt_alock: None,
|
||||
id_interval: None,
|
||||
id_callsign: None,
|
||||
});
|
||||
let _local = InterfaceConfig::Local(LocalInterfaceConfig {
|
||||
name: "l".to_string(),
|
||||
@@ -1809,6 +2256,13 @@ mod tests {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
|
||||
// Python BackboneInterface errors without an explicit port.
|
||||
assert!(matches!(
|
||||
synthesize_interface("backbone_no_port", §ion),
|
||||
Err(InterfaceFactoryError::MissingField { field, .. }) if field == "port"
|
||||
));
|
||||
|
||||
section.set("port", "4242");
|
||||
let config = synthesize_interface("backbone_defaults", §ion).unwrap();
|
||||
match config {
|
||||
InterfaceConfig::Backbone(c) => {
|
||||
@@ -1830,6 +2284,7 @@ mod tests {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("target_host", "host.example");
|
||||
section.set("target_port", "4242");
|
||||
section.set("connect_timeout", "12");
|
||||
|
||||
let config = synthesize_interface("bb_to", §ion).unwrap();
|
||||
@@ -1844,6 +2299,7 @@ mod tests {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("target_host", "host.example");
|
||||
section.set("target_port", "4242");
|
||||
section.set("max_reconnect_tries", "7");
|
||||
|
||||
let config = synthesize_interface("bb_retries", §ion).unwrap();
|
||||
@@ -1858,6 +2314,7 @@ mod tests {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("target_host", "host.example");
|
||||
section.set("target_port", "4242");
|
||||
section.set("i2p_tunneled", "yes");
|
||||
|
||||
let config = synthesize_interface("bb_i2p", §ion).unwrap();
|
||||
@@ -2035,6 +2492,10 @@ mod tests {
|
||||
let mut sub = ConfigSection::new();
|
||||
sub.set("vport", "0");
|
||||
sub.set("frequency", "865600000");
|
||||
sub.set("bandwidth", "125000");
|
||||
sub.set("spreadingfactor", "7");
|
||||
sub.set("codingrate", "5");
|
||||
sub.set("txpower", "14");
|
||||
section.subsections.insert(name.to_string(), sub);
|
||||
}
|
||||
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -198,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>,
|
||||
@@ -280,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)
|
||||
{
|
||||
@@ -298,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,
|
||||
@@ -559,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,
|
||||
@@ -587,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;
|
||||
|
||||
@@ -1703,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());
|
||||
@@ -1719,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,
|
||||
@@ -1751,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"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2537,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 {
|
||||
@@ -2568,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 {
|
||||
@@ -2590,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);
|
||||
@@ -2796,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);
|
||||
@@ -2804,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);
|
||||
@@ -2818,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 {
|
||||
@@ -3006,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);
|
||||
@@ -3140,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();
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -139,6 +139,8 @@ impl ReticulumHandle {
|
||||
|
||||
/// Query this process' transport actor directly.
|
||||
pub async fn query_transport(&self, query: TransportQuery) -> Option<TransportQueryResponse> {
|
||||
let variant = format!("{query:?}");
|
||||
let started = std::time::Instant::now();
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
if self
|
||||
.transport_tx
|
||||
@@ -149,12 +151,25 @@ impl ReticulumHandle {
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(query = %variant, "transport query channel closed");
|
||||
return None;
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(5), rx)
|
||||
let send_elapsed = started.elapsed();
|
||||
let result = tokio::time::timeout(Duration::from_secs(5), rx)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.ok())
|
||||
.and_then(|r| r.ok());
|
||||
let total = started.elapsed();
|
||||
if result.is_none() || total > Duration::from_millis(1000) {
|
||||
tracing::warn!(
|
||||
query = %variant,
|
||||
send_ms = send_elapsed.as_millis() as u64,
|
||||
total_ms = total.as_millis() as u64,
|
||||
timed_out = result.is_none(),
|
||||
"transport query slow or failed"
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Query the authoritative control plane.
|
||||
@@ -1019,20 +1034,13 @@ pub async fn init(
|
||||
.await
|
||||
{
|
||||
Ok(client_handle) => {
|
||||
let client_iface_id = client_handle.id;
|
||||
register_interface_handle_with_role(
|
||||
&transport_tx,
|
||||
adopt_shared_instance_client(
|
||||
client_handle,
|
||||
rns_transport::messages::InterfaceRole::SharedInstancePeer,
|
||||
&transport_tx,
|
||||
&interface_controls,
|
||||
&shutdown,
|
||||
)
|
||||
.await;
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::SharedConnectionRestored {
|
||||
interface_id: client_iface_id,
|
||||
})
|
||||
.await;
|
||||
InstanceMode::Client
|
||||
.await
|
||||
}
|
||||
Err(_) => InstanceMode::Standalone,
|
||||
}
|
||||
@@ -1075,20 +1083,13 @@ pub async fn init(
|
||||
.await
|
||||
{
|
||||
Ok(client_handle) => {
|
||||
let client_iface_id = client_handle.id;
|
||||
register_interface_handle_with_role(
|
||||
&transport_tx,
|
||||
adopt_shared_instance_client(
|
||||
client_handle,
|
||||
rns_transport::messages::InterfaceRole::SharedInstancePeer,
|
||||
&transport_tx,
|
||||
&interface_controls,
|
||||
&shutdown,
|
||||
)
|
||||
.await;
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::SharedConnectionRestored {
|
||||
interface_id: client_iface_id,
|
||||
})
|
||||
.await;
|
||||
InstanceMode::Client
|
||||
.await
|
||||
}
|
||||
Err(_) => InstanceMode::Standalone,
|
||||
}
|
||||
@@ -1142,20 +1143,13 @@ pub async fn init(
|
||||
.await
|
||||
{
|
||||
Ok(client_handle) => {
|
||||
let client_iface_id = client_handle.id;
|
||||
register_interface_handle_with_role(
|
||||
&transport_tx,
|
||||
adopt_shared_instance_client(
|
||||
client_handle,
|
||||
rns_transport::messages::InterfaceRole::SharedInstancePeer,
|
||||
&transport_tx,
|
||||
&interface_controls,
|
||||
&shutdown,
|
||||
)
|
||||
.await;
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::SharedConnectionRestored {
|
||||
interface_id: client_iface_id,
|
||||
})
|
||||
.await;
|
||||
InstanceMode::Client
|
||||
.await
|
||||
}
|
||||
Err(_) => InstanceMode::Standalone,
|
||||
}
|
||||
@@ -1196,20 +1190,13 @@ pub async fn init(
|
||||
.await
|
||||
{
|
||||
Ok(client_handle) => {
|
||||
let client_iface_id = client_handle.id;
|
||||
register_interface_handle_with_role(
|
||||
&transport_tx,
|
||||
adopt_shared_instance_client(
|
||||
client_handle,
|
||||
rns_transport::messages::InterfaceRole::SharedInstancePeer,
|
||||
&transport_tx,
|
||||
&interface_controls,
|
||||
&shutdown,
|
||||
)
|
||||
.await;
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::SharedConnectionRestored {
|
||||
interface_id: client_iface_id,
|
||||
})
|
||||
.await;
|
||||
InstanceMode::Client
|
||||
.await
|
||||
}
|
||||
Err(_) => InstanceMode::Standalone,
|
||||
}
|
||||
@@ -1251,7 +1238,7 @@ pub async fn init(
|
||||
tracing::info!("transport node mode enabled");
|
||||
}
|
||||
|
||||
let interfaces = match synthesize_interfaces(&config, rc.panic_on_interface_error) {
|
||||
let mut interfaces = match synthesize_interfaces(&config, rc.panic_on_interface_error) {
|
||||
Ok(interfaces) => interfaces,
|
||||
Err(e) => {
|
||||
let _ = transport_tx.send(TransportMessage::Shutdown).await;
|
||||
@@ -1261,6 +1248,10 @@ pub async fn init(
|
||||
if !interfaces.is_empty() {
|
||||
tracing::info!("synthesized {} interfaces from config", interfaces.len());
|
||||
}
|
||||
for iface_config in &mut interfaces {
|
||||
apply_discovery_mode_autocorrect(&config, iface_config);
|
||||
}
|
||||
let interfaces = interfaces;
|
||||
|
||||
let discovery_runtime = Arc::new(DiscoveryRuntime::default());
|
||||
if let Ok(store) = DiscoveryStore::open(&paths.storage_dir) {
|
||||
@@ -1552,6 +1543,64 @@ fn next_id(id_gen: &Arc<AtomicU64>) -> u64 {
|
||||
id_gen.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Register a freshly connected shared-instance client (TCP or local socket)
|
||||
/// as the SharedInstancePeer and start its reconnect monitor.
|
||||
async fn adopt_shared_instance_client(
|
||||
client_handle: rns_interface::traits::InterfaceHandle,
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
interface_controls: &InterfaceControlMap,
|
||||
shutdown: &ShutdownSignal,
|
||||
) -> InstanceMode {
|
||||
let client_iface_id = client_handle.id;
|
||||
let client_online = client_handle.online.clone();
|
||||
register_interface_handle_with_role(
|
||||
transport_tx,
|
||||
client_handle,
|
||||
rns_transport::messages::InterfaceRole::SharedInstancePeer,
|
||||
interface_controls,
|
||||
)
|
||||
.await;
|
||||
spawn_shared_peer_monitor(
|
||||
transport_tx.clone(),
|
||||
client_iface_id,
|
||||
client_online,
|
||||
shutdown.clone(),
|
||||
);
|
||||
InstanceMode::Client
|
||||
}
|
||||
|
||||
fn spawn_shared_peer_monitor(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
interface_id: u64,
|
||||
online: Arc<AtomicBool>,
|
||||
shutdown: ShutdownSignal,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
let mut was_online = false;
|
||||
let mut interval = tokio::time::interval(Duration::from_millis(100));
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.wait() => break,
|
||||
_ = interval.tick() => {
|
||||
let is_online = online.load(std::sync::atomic::Ordering::SeqCst);
|
||||
if is_online == was_online {
|
||||
continue;
|
||||
}
|
||||
was_online = is_online;
|
||||
let message = if is_online {
|
||||
TransportMessage::SharedConnectionRestored { interface_id }
|
||||
} else {
|
||||
TransportMessage::SharedConnectionLost
|
||||
};
|
||||
if transport_tx.send(message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn ingress_for_role(
|
||||
role: rns_transport::messages::InterfaceRole,
|
||||
ingress_overrides: &rns_transport::ingress::IngressOverrides,
|
||||
@@ -1762,6 +1811,52 @@ fn derive_ifac_key_from_post_init(
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RuntimeInterfaceIfacConfig {
|
||||
pub network_name: Option<String>,
|
||||
pub passphrase: Option<String>,
|
||||
pub ifac_size: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RuntimeBackboneClientConfig<'a> {
|
||||
pub name: &'a str,
|
||||
pub host: &'a str,
|
||||
pub port: u16,
|
||||
pub prefer_ipv6: bool,
|
||||
pub connect_timeout: Option<u64>,
|
||||
pub max_reconnect_tries: Option<usize>,
|
||||
pub ifac: Option<RuntimeInterfaceIfacConfig>,
|
||||
}
|
||||
|
||||
fn runtime_ifac_post_init(
|
||||
ifac: Option<RuntimeInterfaceIfacConfig>,
|
||||
default_ifac_size: usize,
|
||||
) -> Result<Option<interface_factory::InterfacePostInit>, String> {
|
||||
let Some(ifac) = ifac else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
if let Some(size) = ifac.ifac_size
|
||||
&& !(1..=64).contains(&size)
|
||||
{
|
||||
return Err(format!("Invalid IFAC size {size}; expected 1..=64 bytes"));
|
||||
}
|
||||
|
||||
let network_name = ifac.network_name.filter(|s| !s.is_empty());
|
||||
let passphrase = ifac.passphrase.filter(|s| !s.is_empty());
|
||||
if network_name.is_none() && passphrase.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut post_init = interface_factory::InterfacePostInit::from_section(&ConfigSection::new())
|
||||
.with_default_ifac_size(default_ifac_size);
|
||||
post_init.ifac_network_name = network_name;
|
||||
post_init.ifac_passphrase = passphrase;
|
||||
post_init.ifac_size = ifac.ifac_size;
|
||||
Ok(Some(post_init))
|
||||
}
|
||||
|
||||
fn get_post_init_for_config(
|
||||
config: &Config,
|
||||
iface_config: &interface_factory::InterfaceConfig,
|
||||
@@ -1855,6 +1950,94 @@ fn interface_section<'a>(
|
||||
config.subsection("interfaces", name)
|
||||
}
|
||||
|
||||
fn interface_config_mode_mut(
|
||||
iface_config: &mut interface_factory::InterfaceConfig,
|
||||
) -> &mut rns_interface::traits::InterfaceMode {
|
||||
match iface_config {
|
||||
interface_factory::InterfaceConfig::TcpClient(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::TcpServer(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::Udp(c) => &mut c.mode,
|
||||
#[cfg(feature = "serial")]
|
||||
interface_factory::InterfaceConfig::Serial(c) => &mut c.mode,
|
||||
#[cfg(feature = "serial")]
|
||||
interface_factory::InterfaceConfig::KissSerial(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::Auto(c) => &mut c.mode,
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
interface_factory::InterfaceConfig::RNode(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::Local(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::I2P(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::Pipe(c) => &mut c.mode,
|
||||
#[cfg(feature = "serial")]
|
||||
interface_factory::InterfaceConfig::RNodeMulti(c) => &mut c.mode,
|
||||
#[cfg(feature = "serial")]
|
||||
interface_factory::InterfaceConfig::AX25KISS(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::Backbone(c) => &mut c.mode,
|
||||
#[cfg(feature = "ble")]
|
||||
interface_factory::InterfaceConfig::BleRNode(c) => &mut c.mode,
|
||||
}
|
||||
}
|
||||
|
||||
/// Python Reticulum.py:841-848: a `discoverable` interface must run in
|
||||
/// Gateway or Access Point mode for discovery to be useful, so the mode is
|
||||
/// auto-corrected (AP for RNode radios, Gateway otherwise) with a notice.
|
||||
/// `ignore_config_warnings = yes` opts out and keeps the configured mode.
|
||||
fn apply_discovery_mode_autocorrect(
|
||||
config: &Config,
|
||||
iface_config: &mut interface_factory::InterfaceConfig,
|
||||
) {
|
||||
use rns_interface::traits::InterfaceMode;
|
||||
|
||||
let Some(section) = interface_section(config, iface_config) else {
|
||||
return;
|
||||
};
|
||||
if !section.get_bool("discoverable").unwrap_or(false)
|
||||
|| section.get_bool("ignore_config_warnings").unwrap_or(false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let is_rnode = {
|
||||
#[allow(unused_mut)]
|
||||
let mut rnode = false;
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
{
|
||||
rnode |= matches!(iface_config, interface_factory::InterfaceConfig::RNode(_));
|
||||
}
|
||||
#[cfg(feature = "serial")]
|
||||
{
|
||||
rnode |= matches!(
|
||||
iface_config,
|
||||
interface_factory::InterfaceConfig::RNodeMulti(_)
|
||||
);
|
||||
}
|
||||
#[cfg(feature = "ble")]
|
||||
{
|
||||
rnode |= matches!(
|
||||
iface_config,
|
||||
interface_factory::InterfaceConfig::BleRNode(_)
|
||||
);
|
||||
}
|
||||
rnode
|
||||
};
|
||||
|
||||
let name = interface_config_name(iface_config).to_string();
|
||||
let mode = interface_config_mode_mut(iface_config);
|
||||
if matches!(*mode, InterfaceMode::Gateway | InterfaceMode::AccessPoint) {
|
||||
return;
|
||||
}
|
||||
*mode = if is_rnode {
|
||||
InterfaceMode::AccessPoint
|
||||
} else {
|
||||
InterfaceMode::Gateway
|
||||
};
|
||||
tracing::warn!(
|
||||
interface = %name,
|
||||
mode = ?*mode,
|
||||
"discovery enabled without gateway or AP mode — auto-configured; \
|
||||
set ignore_config_warnings to keep the configured mode"
|
||||
);
|
||||
}
|
||||
|
||||
fn interface_bootstrap_only(
|
||||
config: &Config,
|
||||
iface_config: &interface_factory::InterfaceConfig,
|
||||
@@ -2387,7 +2570,7 @@ async fn start_blackhole_publisher(handle: &ReticulumHandle) -> Result<[u8; 16],
|
||||
event_rx,
|
||||
&identity,
|
||||
app_name,
|
||||
signing_key,
|
||||
Some(signing_key),
|
||||
);
|
||||
|
||||
let list_hash = rns_crypto::sha::truncated_hash(b"/list");
|
||||
@@ -2513,8 +2696,12 @@ async fn start_blackhole_subscriber(handle: ReticulumHandle) {
|
||||
}
|
||||
|
||||
fn clone_identity(identity: &Identity) -> Option<Identity> {
|
||||
let private_key = identity.get_private_key()?;
|
||||
Identity::from_private_key(&*private_key).ok()
|
||||
// Preserve a hardware backend (shared Arc); software identities copy key material.
|
||||
if identity.has_private_key() || identity.has_backend() {
|
||||
Some(identity.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn send_announce_try(
|
||||
@@ -2563,22 +2750,46 @@ pub async fn spawn_tcp_client_runtime(
|
||||
name: &str,
|
||||
host: &str,
|
||||
port: u16,
|
||||
) -> Result<u64, String> {
|
||||
spawn_tcp_client_runtime_with_ifac(handle, name, host, port, None).await
|
||||
}
|
||||
|
||||
/// Spawn a TCP client interface at runtime with optional IFAC settings.
|
||||
pub async fn spawn_tcp_client_runtime_with_ifac(
|
||||
handle: &ReticulumHandle,
|
||||
name: &str,
|
||||
host: &str,
|
||||
port: u16,
|
||||
ifac: Option<RuntimeInterfaceIfacConfig>,
|
||||
) -> Result<u64, String> {
|
||||
let id = handle
|
||||
.id_gen
|
||||
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let post_init = runtime_ifac_post_init(ifac, 16)?;
|
||||
let config = rns_interface::tcp::TcpClientConfig::new(name, host, port);
|
||||
let iface_handle =
|
||||
rns_interface::tcp::spawn_tcp_client(config, id, handle.transport_tx.clone(), None)
|
||||
.await
|
||||
.map_err(|e| format!("TCP client spawn failed: {e}"))?;
|
||||
|
||||
register_interface_handle(
|
||||
&handle.transport_tx,
|
||||
iface_handle,
|
||||
&handle.interface_controls,
|
||||
)
|
||||
.await;
|
||||
if let Some(post_init) = post_init {
|
||||
let ifac_key = derive_ifac_key_from_post_init(&post_init);
|
||||
register_interface_with_post_init(
|
||||
&handle.transport_tx,
|
||||
iface_handle,
|
||||
&post_init,
|
||||
ifac_key,
|
||||
&handle.interface_controls,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
register_interface_handle(
|
||||
&handle.transport_tx,
|
||||
iface_handle,
|
||||
&handle.interface_controls,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
tracing::info!(name = %name, id, "runtime TCP client interface spawned");
|
||||
Ok(id)
|
||||
}
|
||||
@@ -2621,29 +2832,66 @@ pub async fn spawn_backbone_client_runtime(
|
||||
prefer_ipv6: bool,
|
||||
connect_timeout: Option<u64>,
|
||||
max_reconnect_tries: Option<usize>,
|
||||
) -> Result<u64, String> {
|
||||
spawn_backbone_client_runtime_with_ifac(
|
||||
handle,
|
||||
RuntimeBackboneClientConfig {
|
||||
name,
|
||||
host,
|
||||
port,
|
||||
prefer_ipv6,
|
||||
connect_timeout,
|
||||
max_reconnect_tries,
|
||||
ifac: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Spawn a Backbone (HDLC-over-TCP) client interface at runtime with optional IFAC settings.
|
||||
pub async fn spawn_backbone_client_runtime_with_ifac(
|
||||
handle: &ReticulumHandle,
|
||||
runtime_config: RuntimeBackboneClientConfig<'_>,
|
||||
) -> Result<u64, String> {
|
||||
let id = handle
|
||||
.id_gen
|
||||
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let mut config = rns_interface::backbone::BackboneClientConfig::new(name, host, port);
|
||||
config.prefer_ipv6 = prefer_ipv6;
|
||||
if let Some(t) = connect_timeout {
|
||||
let post_init = runtime_ifac_post_init(runtime_config.ifac, 16)?;
|
||||
let mut config = rns_interface::backbone::BackboneClientConfig::new(
|
||||
runtime_config.name,
|
||||
runtime_config.host,
|
||||
runtime_config.port,
|
||||
);
|
||||
config.prefer_ipv6 = runtime_config.prefer_ipv6;
|
||||
if let Some(t) = runtime_config.connect_timeout {
|
||||
config.connect_timeout_secs = t;
|
||||
}
|
||||
config.max_reconnect_tries = max_reconnect_tries;
|
||||
config.max_reconnect_tries = runtime_config.max_reconnect_tries;
|
||||
|
||||
let iface_handle =
|
||||
rns_interface::backbone::spawn_backbone_client(config, id, handle.transport_tx.clone())
|
||||
.await
|
||||
.map_err(|e| format!("Backbone client spawn failed: {e}"))?;
|
||||
|
||||
register_interface_handle(
|
||||
&handle.transport_tx,
|
||||
iface_handle,
|
||||
&handle.interface_controls,
|
||||
)
|
||||
.await;
|
||||
tracing::info!(name = %name, id, "runtime Backbone client interface spawned");
|
||||
if let Some(post_init) = post_init {
|
||||
let ifac_key = derive_ifac_key_from_post_init(&post_init);
|
||||
register_interface_with_post_init(
|
||||
&handle.transport_tx,
|
||||
iface_handle,
|
||||
&post_init,
|
||||
ifac_key,
|
||||
&handle.interface_controls,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
register_interface_handle(
|
||||
&handle.transport_tx,
|
||||
iface_handle,
|
||||
&handle.interface_controls,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
tracing::info!(name = %runtime_config.name, id, "runtime Backbone client interface spawned");
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -2698,6 +2946,14 @@ pub struct BleRnodeRuntimeArgs<'a> {
|
||||
pub coding_rate: u8,
|
||||
/// Transmit power in dBm.
|
||||
pub tx_power: i8,
|
||||
/// Reticulum interface routing/announce propagation mode.
|
||||
pub mode: rns_interface::traits::InterfaceMode,
|
||||
/// Short-term airtime limit in percent (0.0..=100.0), None = no limit.
|
||||
pub st_alock: Option<f32>,
|
||||
/// Long-term airtime limit in percent (0.0..=100.0), None = no limit.
|
||||
pub lt_alock: Option<f32>,
|
||||
/// Enable KISS flow control.
|
||||
pub flow_control: bool,
|
||||
}
|
||||
|
||||
/// Returns `(interface_id, online_flag)`; `online_flag` flips to `true`
|
||||
@@ -2715,6 +2971,10 @@ pub async fn spawn_ble_rnode_runtime(
|
||||
spreading_factor,
|
||||
coding_rate,
|
||||
tx_power,
|
||||
mode,
|
||||
st_alock,
|
||||
lt_alock,
|
||||
flow_control,
|
||||
} = args;
|
||||
|
||||
let id = handle
|
||||
@@ -2726,6 +2986,10 @@ pub async fn spawn_ble_rnode_runtime(
|
||||
config.spreading_factor = spreading_factor;
|
||||
config.coding_rate = coding_rate;
|
||||
config.tx_power = tx_power as u8;
|
||||
config.mode = mode;
|
||||
config.st_alock = st_alock;
|
||||
config.lt_alock = lt_alock;
|
||||
config.flow_control = flow_control;
|
||||
|
||||
let iface_handle = rns_interface::ble_rnode::spawn_ble_rnode_interface(
|
||||
config,
|
||||
@@ -2763,6 +3027,14 @@ pub struct RnodeRuntimeArgs<'a> {
|
||||
pub coding_rate: u8,
|
||||
/// Transmit power in dBm.
|
||||
pub tx_power: i8,
|
||||
/// Reticulum interface routing/announce propagation mode.
|
||||
pub mode: rns_interface::traits::InterfaceMode,
|
||||
/// Short-term airtime limit in percent (0.0..=100.0), None = no limit.
|
||||
pub st_alock: Option<f32>,
|
||||
/// Long-term airtime limit in percent (0.0..=100.0), None = no limit.
|
||||
pub lt_alock: Option<f32>,
|
||||
/// Enable KISS flow control.
|
||||
pub flow_control: bool,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
@@ -2778,6 +3050,10 @@ pub async fn spawn_rnode_runtime(
|
||||
spreading_factor,
|
||||
coding_rate,
|
||||
tx_power,
|
||||
mode,
|
||||
st_alock,
|
||||
lt_alock,
|
||||
flow_control,
|
||||
} = args;
|
||||
|
||||
let id = handle
|
||||
@@ -2789,6 +3065,10 @@ pub async fn spawn_rnode_runtime(
|
||||
config.spreading_factor = spreading_factor;
|
||||
config.coding_rate = coding_rate;
|
||||
config.tx_power = tx_power as u8;
|
||||
config.mode = mode;
|
||||
config.st_alock = st_alock;
|
||||
config.lt_alock = lt_alock;
|
||||
config.flow_control = flow_control;
|
||||
|
||||
let iface_handle =
|
||||
rns_interface::rnode::spawn_rnode_interface(config, id, handle.transport_tx.clone())
|
||||
@@ -2821,6 +3101,10 @@ pub async fn spawn_ble_rnode_runtime_native(
|
||||
spreading_factor,
|
||||
coding_rate,
|
||||
tx_power,
|
||||
mode,
|
||||
st_alock,
|
||||
lt_alock,
|
||||
flow_control,
|
||||
} = args;
|
||||
|
||||
let id = handle
|
||||
@@ -2832,6 +3116,10 @@ pub async fn spawn_ble_rnode_runtime_native(
|
||||
config.spreading_factor = spreading_factor;
|
||||
config.coding_rate = coding_rate;
|
||||
config.tx_power = tx_power as u8;
|
||||
config.mode = mode;
|
||||
config.st_alock = st_alock;
|
||||
config.lt_alock = lt_alock;
|
||||
config.flow_control = flow_control;
|
||||
|
||||
let iface_handle = rns_interface::ble_rnode::spawn_ble_rnode_interface_native(
|
||||
config,
|
||||
@@ -2908,7 +3196,7 @@ pub async fn spawn_ble_peer_runtime(
|
||||
identity_hash: Vec<u8>,
|
||||
event_tx: Option<tokio::sync::mpsc::Sender<rns_interface::ble_peer::BlePeerEvent>>,
|
||||
foreground_wake: std::sync::Arc<tokio::sync::Notify>,
|
||||
seed_identities: Vec<String>,
|
||||
seed_addresses: Vec<String>,
|
||||
) -> Result<u64, String> {
|
||||
let id = handle
|
||||
.id_gen
|
||||
@@ -2926,7 +3214,7 @@ pub async fn spawn_ble_peer_runtime(
|
||||
handle.transport_tx.clone(),
|
||||
handle.is_foreground.clone(),
|
||||
foreground_wake,
|
||||
seed_identities,
|
||||
seed_addresses,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
@@ -2985,6 +3273,10 @@ pub async fn spawn_android_usb_rnode_runtime(
|
||||
spreading_factor: u8,
|
||||
coding_rate: u8,
|
||||
tx_power: i8,
|
||||
mode: rns_interface::traits::InterfaceMode,
|
||||
st_alock: Option<f32>,
|
||||
lt_alock: Option<f32>,
|
||||
flow_control: bool,
|
||||
) -> Result<u64, String> {
|
||||
let id = handle
|
||||
.id_gen
|
||||
@@ -2995,6 +3287,10 @@ pub async fn spawn_android_usb_rnode_runtime(
|
||||
config.spreading_factor = spreading_factor;
|
||||
config.coding_rate = coding_rate;
|
||||
config.tx_power = tx_power as u8;
|
||||
config.mode = mode;
|
||||
config.st_alock = st_alock;
|
||||
config.lt_alock = lt_alock;
|
||||
config.flow_control = flow_control;
|
||||
|
||||
let iface_handle = rns_interface::android_usb::spawn_android_usb_rnode_interface(
|
||||
config,
|
||||
@@ -3079,6 +3375,11 @@ async fn spawn_interface(
|
||||
let mut serial_config = rns_interface::serial::SerialConfig::new(&c.name, &c.port);
|
||||
serial_config.baud_rate = c.baud_rate;
|
||||
serial_config.mode = c.mode;
|
||||
let (data, parity, stop) =
|
||||
rns_interface::serial::serial_params_from(c.data_bits, &c.parity, c.stop_bits);
|
||||
serial_config.data_bits = data;
|
||||
serial_config.parity = parity;
|
||||
serial_config.stop_bits = stop;
|
||||
rns_interface::serial::spawn_serial_interface(serial_config, id, transport_tx)
|
||||
.await
|
||||
.map(|h| vec![h])
|
||||
@@ -3089,6 +3390,21 @@ async fn spawn_interface(
|
||||
let mut kiss_config =
|
||||
rns_interface::kiss_iface::KissInterfaceConfig::new(&c.name, &c.port, c.baud_rate);
|
||||
kiss_config.mode = c.mode;
|
||||
let (data, parity, stop) =
|
||||
rns_interface::serial::serial_params_from(c.data_bits, &c.parity, c.stop_bits);
|
||||
kiss_config.data_bits = data;
|
||||
kiss_config.parity = parity;
|
||||
kiss_config.stop_bits = stop;
|
||||
// Wire units are 10 ms steps for the timing commands; persistence
|
||||
// is the raw 0-255 CSMA p-value (Python setPreamble etc.).
|
||||
let to_wire = |ms: u32| ((ms / 10).min(255)) as u8;
|
||||
kiss_config.txdelay = Some(to_wire(c.preamble_ms));
|
||||
kiss_config.txtail = Some(to_wire(c.txtail_ms));
|
||||
kiss_config.slottime = Some(to_wire(c.slottime_ms));
|
||||
kiss_config.persistence = Some(c.persistence);
|
||||
kiss_config.flow_control = c.flow_control;
|
||||
kiss_config.id_interval = c.id_interval;
|
||||
kiss_config.id_callsign = c.id_callsign.as_ref().map(|s| s.as_bytes().to_vec());
|
||||
rns_interface::kiss_iface::spawn_kiss_interface(kiss_config, id, transport_tx)
|
||||
.await
|
||||
.map(|h| vec![h])
|
||||
@@ -3121,6 +3437,11 @@ async fn spawn_interface(
|
||||
rnode_config.coding_rate = c.coding_rate;
|
||||
rnode_config.tx_power = c.tx_power as u8;
|
||||
rnode_config.mode = c.mode;
|
||||
rnode_config.flow_control = c.flow_control;
|
||||
rnode_config.st_alock = c.st_alock;
|
||||
rnode_config.lt_alock = c.lt_alock;
|
||||
rnode_config.id_interval = c.id_interval;
|
||||
rnode_config.id_callsign = c.id_callsign.as_ref().map(|s| s.as_bytes().to_vec());
|
||||
rns_interface::rnode::spawn_rnode_interface(rnode_config, id, transport_tx)
|
||||
.await
|
||||
.map(|h| vec![h])
|
||||
@@ -3183,6 +3504,8 @@ async fn spawn_interface(
|
||||
rns_interface::rnode_multi::RNodeMultiConfig::new(&c.name, &c.port);
|
||||
multi_config.baud_rate = c.baud_rate;
|
||||
multi_config.flow_control = c.flow_control;
|
||||
multi_config.id_interval = c.id_interval;
|
||||
multi_config.id_callsign = c.id_callsign.as_ref().map(|s| s.as_bytes().to_vec());
|
||||
for sub in &c.subinterfaces {
|
||||
let mut sub_config = rns_interface::rnode_multi::SubInterfaceConfig::new(
|
||||
&sub.name,
|
||||
@@ -3225,6 +3548,9 @@ async fn spawn_interface(
|
||||
rns_interface::ax25kiss::AX25KISSConfig::new(&c.name, &c.port, &c.callsign, c.ssid);
|
||||
let mut ax25_config = ax25_config;
|
||||
ax25_config.baud_rate = c.baud_rate;
|
||||
ax25_config.data_bits = c.data_bits;
|
||||
ax25_config.parity = c.parity.clone();
|
||||
ax25_config.stop_bits = c.stop_bits;
|
||||
ax25_config.preamble = c.preamble as u16;
|
||||
ax25_config.txtail = c.txtail as u16;
|
||||
ax25_config.persistence = c.persistence as u8;
|
||||
@@ -3245,6 +3571,11 @@ async fn spawn_interface(
|
||||
config.coding_rate = c.coding_rate;
|
||||
config.tx_power = c.tx_power as u8;
|
||||
config.mode = c.mode;
|
||||
config.flow_control = c.flow_control;
|
||||
config.st_alock = c.st_alock;
|
||||
config.lt_alock = c.lt_alock;
|
||||
config.id_interval = c.id_interval;
|
||||
config.id_callsign = c.id_callsign.as_ref().map(|s| s.as_bytes().to_vec());
|
||||
rns_interface::ble_rnode::spawn_ble_rnode_interface(config, id, transport_tx)
|
||||
.await
|
||||
.map(|h| vec![h])
|
||||
@@ -3468,6 +3799,95 @@ mod tests {
|
||||
bytes::Bytes::from(raw)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_ifac_post_init_ignores_blank_fields() {
|
||||
let post_init = runtime_ifac_post_init(
|
||||
Some(RuntimeInterfaceIfacConfig {
|
||||
network_name: Some(String::new()),
|
||||
passphrase: Some(String::new()),
|
||||
ifac_size: None,
|
||||
}),
|
||||
16,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(post_init.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_ifac_post_init_uses_tcp_default_size() {
|
||||
let post_init = runtime_ifac_post_init(
|
||||
Some(RuntimeInterfaceIfacConfig {
|
||||
network_name: Some("testnet".to_string()),
|
||||
passphrase: Some("secret".to_string()),
|
||||
ifac_size: None,
|
||||
}),
|
||||
16,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(post_init.ifac_network_name.as_deref(), Some("testnet"));
|
||||
assert_eq!(post_init.ifac_passphrase.as_deref(), Some("secret"));
|
||||
assert_eq!(post_init.ifac_size, None);
|
||||
assert_eq!(post_init.default_ifac_size, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_ifac_post_init_rejects_invalid_size() {
|
||||
let result = runtime_ifac_post_init(
|
||||
Some(RuntimeInterfaceIfacConfig {
|
||||
network_name: Some("testnet".to_string()),
|
||||
passphrase: None,
|
||||
ifac_size: Some(0),
|
||||
}),
|
||||
16,
|
||||
);
|
||||
|
||||
match result {
|
||||
Ok(_) => panic!("expected invalid IFAC size to be rejected"),
|
||||
Err(err) => assert!(err.contains("Invalid IFAC size")),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_peer_monitor_emits_connection_lifecycle_events() {
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let online = Arc::new(AtomicBool::new(false));
|
||||
let shutdown = ShutdownSignal::new();
|
||||
|
||||
spawn_shared_peer_monitor(tx, 7, online.clone(), shutdown.clone());
|
||||
tokio::time::sleep(std::time::Duration::from_millis(120)).await;
|
||||
assert!(
|
||||
rx.try_recv().is_err(),
|
||||
"offline initial state should not emit a lost event"
|
||||
);
|
||||
|
||||
online.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let restored = tokio::time::timeout(std::time::Duration::from_millis(300), rx.recv())
|
||||
.await
|
||||
.expect("restored event timed out")
|
||||
.expect("monitor channel closed");
|
||||
match restored {
|
||||
TransportMessage::SharedConnectionRestored { interface_id } => {
|
||||
assert_eq!(interface_id, 7)
|
||||
}
|
||||
other => panic!("expected SharedConnectionRestored, got {other:?}"),
|
||||
}
|
||||
|
||||
online.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
let lost = tokio::time::timeout(std::time::Duration::from_millis(300), rx.recv())
|
||||
.await
|
||||
.expect("lost event timed out")
|
||||
.expect("monitor channel closed");
|
||||
match lost {
|
||||
TransportMessage::SharedConnectionLost => {}
|
||||
other => panic!("expected SharedConnectionLost, got {other:?}"),
|
||||
}
|
||||
|
||||
shutdown.trigger();
|
||||
}
|
||||
|
||||
fn write_stale_python_destination_table(storage_dir: &Path, entries: usize) {
|
||||
std::fs::create_dir_all(storage_dir).unwrap();
|
||||
|
||||
@@ -3805,6 +4225,46 @@ loglevel = 7
|
||||
assert_eq!(rc.ingress_overrides.held_release_interval, Some(3.5));
|
||||
}
|
||||
|
||||
/// Python Reticulum.py:841-848 parity: discoverable interfaces are
|
||||
/// auto-corrected to Gateway/AP mode unless ignore_config_warnings.
|
||||
#[test]
|
||||
fn discovery_mode_autocorrect_matches_python() {
|
||||
use rns_interface::traits::InterfaceMode;
|
||||
|
||||
let input = "[interfaces]\n\
|
||||
[[upstream]]\n\
|
||||
type = TCPServerInterface\n\
|
||||
listen_ip = 0.0.0.0\n\
|
||||
listen_port = 4242\n\
|
||||
discoverable = yes\n";
|
||||
let config = Config::parse(input).unwrap();
|
||||
let mut interfaces = synthesize_interfaces(&config, false).unwrap();
|
||||
apply_discovery_mode_autocorrect(&config, &mut interfaces[0]);
|
||||
match &interfaces[0] {
|
||||
interface_factory::InterfaceConfig::TcpServer(c) => {
|
||||
assert_eq!(c.mode, InterfaceMode::Gateway);
|
||||
}
|
||||
_ => panic!("expected TcpServer"),
|
||||
}
|
||||
|
||||
let opted_out = "[interfaces]\n\
|
||||
[[upstream]]\n\
|
||||
type = TCPServerInterface\n\
|
||||
listen_ip = 0.0.0.0\n\
|
||||
listen_port = 4242\n\
|
||||
discoverable = yes\n\
|
||||
ignore_config_warnings = yes\n";
|
||||
let config = Config::parse(opted_out).unwrap();
|
||||
let mut interfaces = synthesize_interfaces(&config, false).unwrap();
|
||||
apply_discovery_mode_autocorrect(&config, &mut interfaces[0]);
|
||||
match &interfaces[0] {
|
||||
interface_factory::InterfaceConfig::TcpServer(c) => {
|
||||
assert_eq!(c.mode, InterfaceMode::Full, "opt-out keeps configured mode");
|
||||
}
|
||||
_ => panic!("expected TcpServer"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ingress_control_precedence_global_then_interface() {
|
||||
let input = r#"
|
||||
@@ -4314,31 +4774,66 @@ enabled = yes
|
||||
.unwrap();
|
||||
assert_eq!(handle_c.instance_mode, InstanceMode::Client);
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
|
||||
let (stats_tx, stats_rx) = tokio::sync::oneshot::channel();
|
||||
handle_a
|
||||
.transport_tx
|
||||
.send(TransportMessage::Rpc {
|
||||
query: rns_transport::messages::TransportQuery::GetInterfaceStats,
|
||||
response_tx: stats_tx,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let server_stats = stats_rx.await.unwrap();
|
||||
let roles: Vec<String> = match server_stats {
|
||||
rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => {
|
||||
entries.into_iter().map(|entry| entry.role).collect()
|
||||
let server_entries = {
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3);
|
||||
loop {
|
||||
let (stats_tx, stats_rx) = tokio::sync::oneshot::channel();
|
||||
handle_a
|
||||
.transport_tx
|
||||
.send(TransportMessage::Rpc {
|
||||
query: rns_transport::messages::TransportQuery::GetInterfaceStats,
|
||||
response_tx: stats_tx,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let server_stats = stats_rx.await.unwrap();
|
||||
let entries = match server_stats {
|
||||
rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => {
|
||||
entries
|
||||
}
|
||||
other => panic!("unexpected stats response: {other:?}"),
|
||||
};
|
||||
let local_clients: Vec<_> = entries
|
||||
.iter()
|
||||
.filter(|entry| entry.role == "local_client")
|
||||
.collect();
|
||||
if entries.iter().any(|entry| entry.role == "shared_server")
|
||||
&& local_clients.len() == 2
|
||||
&& local_clients.iter().all(|entry| entry.online)
|
||||
&& local_clients.iter().all(|entry| entry.tx_drops == 0)
|
||||
{
|
||||
break entries;
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
break entries;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
other => panic!("unexpected stats response: {other:?}"),
|
||||
};
|
||||
let roles: Vec<String> = server_entries
|
||||
.iter()
|
||||
.map(|entry| entry.role.clone())
|
||||
.collect();
|
||||
assert!(
|
||||
roles.iter().any(|role| role == "shared_server"),
|
||||
"shared instance must mark the listener"
|
||||
);
|
||||
let local_clients: Vec<_> = server_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.role == "local_client")
|
||||
.collect();
|
||||
assert_eq!(
|
||||
local_clients.len(),
|
||||
2,
|
||||
"transient shared-instance detection sockets must not remain registered"
|
||||
);
|
||||
assert!(
|
||||
roles.iter().filter(|role| *role == "local_client").count() >= 2,
|
||||
"accepted shared clients must be marked for transport policy"
|
||||
local_clients.iter().all(|entry| entry.online),
|
||||
"accepted shared clients must be online"
|
||||
);
|
||||
assert!(
|
||||
local_clients.iter().all(|entry| entry.tx_drops == 0),
|
||||
"accepted shared clients must not accumulate TX drops"
|
||||
);
|
||||
|
||||
let shared_control_stats = handle_b
|
||||
@@ -4427,6 +4922,30 @@ enabled = yes
|
||||
.expect("shared instance did not forward local-client plain packet");
|
||||
assert_eq!(received.as_ref(), raw.as_ref());
|
||||
|
||||
let post_forward_stats = handle_b
|
||||
.query_control(rns_transport::messages::TransportQuery::GetInterfaceStats)
|
||||
.await
|
||||
.expect("post-forward control query should reach shared instance");
|
||||
let post_forward_entries = match post_forward_stats {
|
||||
rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => entries,
|
||||
other => panic!("unexpected post-forward stats response: {other:?}"),
|
||||
};
|
||||
let post_forward_local_clients: Vec<_> = post_forward_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.role == "local_client")
|
||||
.collect();
|
||||
assert_eq!(
|
||||
post_forward_local_clients.len(),
|
||||
2,
|
||||
"forwarding through shared instance must not retain stale local clients"
|
||||
);
|
||||
assert!(
|
||||
post_forward_local_clients
|
||||
.iter()
|
||||
.all(|entry| entry.tx_drops == 0),
|
||||
"forwarding through shared instance must not report TX drops"
|
||||
);
|
||||
|
||||
shutdown_c.trigger();
|
||||
shutdown_b.trigger();
|
||||
shutdown_a.trigger();
|
||||
@@ -4591,6 +5110,9 @@ type = RNodeInterface
|
||||
port = /dev/ttyACM0
|
||||
frequency = 868000000
|
||||
bandwidth = 125000
|
||||
spreadingfactor = 7
|
||||
codingrate = 5
|
||||
txpower = 17
|
||||
|
||||
[[OpenCom XL]]
|
||||
type = RNodeMultiInterface
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -169,7 +169,7 @@ async fn run_rnsh_listener_inner(
|
||||
event_rx,
|
||||
&cfg.identity,
|
||||
RNSH_APP_NAME,
|
||||
signing_key,
|
||||
Some(signing_key),
|
||||
);
|
||||
|
||||
let announce_tx = transport_tx.clone();
|
||||
|
||||
@@ -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,
|
||||
@@ -213,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;
|
||||
@@ -1399,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));
|
||||
@@ -1406,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;
|
||||
}
|
||||
@@ -1416,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));
|
||||
@@ -1580,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(|_| {
|
||||
@@ -1603,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);
|
||||
@@ -1628,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(|_| {
|
||||
@@ -1850,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];
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -42,7 +42,7 @@ use rns_runtime::rncp::{
|
||||
};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
|
||||
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)
|
||||
{
|
||||
@@ -806,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.");
|
||||
}
|
||||
@@ -26,7 +26,7 @@ use rns_transport::messages::{
|
||||
#[cfg(feature = "hardware")]
|
||||
mod hw_commands;
|
||||
|
||||
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
const DEFAULT_ASPECTS: &str = "rns.id";
|
||||
const PUB_EXT: &str = "pub";
|
||||
const SIG_EXT: &str = "rsg";
|
||||
@@ -187,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)]
|
||||
@@ -200,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")]
|
||||
@@ -230,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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.5";
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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.5";
|
||||
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.5";
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ use rns_runtime::rnsh::{
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
const RNS_VERSION: &str = "1.2.5";
|
||||
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}");
|
||||
@@ -172,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) {
|
||||
@@ -182,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}");
|
||||
@@ -253,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
|
||||
@@ -873,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.5 (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.5";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -125,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) {
|
||||
|
||||
@@ -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";
|
||||
@@ -51,8 +51,8 @@ fn write_config(tmp: &TempDir) {
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn wait_until_running(child: &mut Child) -> bool {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
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;
|
||||
@@ -62,49 +62,75 @@ fn wait_until_running(child: &mut Child) -> bool {
|
||||
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(mut child: Child, name: &str) {
|
||||
if !wait_until_running(&mut child) {
|
||||
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)
|
||||
);
|
||||
}
|
||||
fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
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(5);
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = child.try_wait().expect("poll child after SIGINT") {
|
||||
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");
|
||||
assert!(
|
||||
status.success(),
|
||||
"{name} exited unsuccessfully after SIGINT: {status}\nstdout:\n{}\nstderr:\n{}",
|
||||
panic!(
|
||||
"{name} exited before SIGINT\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
|
||||
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)
|
||||
);
|
||||
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)]
|
||||
@@ -112,18 +138,21 @@ fn assert_sigint_exits(mut child: Child, name: &str) {
|
||||
fn rncp_listener_exits_on_sigint() {
|
||||
let tmp = TempDir::new("rncp-sigint");
|
||||
write_config(&tmp);
|
||||
let child = 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");
|
||||
|
||||
assert_sigint_exits(child, "rncp-rs");
|
||||
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)]
|
||||
@@ -131,15 +160,18 @@ fn rncp_listener_exits_on_sigint() {
|
||||
fn rnsh_listener_exits_on_sigint() {
|
||||
let tmp = TempDir::new("rnsh-sigint");
|
||||
write_config(&tmp);
|
||||
let child = 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");
|
||||
|
||||
assert_sigint_exits(child, "rnsh-rs");
|
||||
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",
|
||||
);
|
||||
}
|
||||
@@ -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(
|
||||
@@ -477,11 +478,15 @@ impl TransportActor {
|
||||
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) => {
|
||||
@@ -491,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) => {
|
||||
@@ -502,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;
|
||||
|
||||
@@ -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 {
|
||||
@@ -61,7 +65,7 @@ impl TransportActor {
|
||||
// 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;
|
||||
}
|
||||
@@ -134,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;
|
||||
@@ -165,6 +172,20 @@ impl TransportActor {
|
||||
.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);
|
||||
@@ -467,10 +488,13 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sweep `recent_announces`. Keep retained + pathed entries; reap the
|
||||
/// rest past `DESTINATION_TIMEOUT` (7 days). No count cap.
|
||||
/// 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
|
||||
@@ -485,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();
|
||||
|
||||
@@ -577,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,
|
||||
@@ -585,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();
|
||||
@@ -614,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,
|
||||
);
|
||||
|
||||
@@ -644,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()));
|
||||
}
|
||||
}
|
||||
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) {
|
||||
@@ -128,7 +129,9 @@ impl TransportActor {
|
||||
"outbound: no path, broadcasting"
|
||||
);
|
||||
self.broadcast_on_interfaces(&request.raw, None);
|
||||
self.on_automatic_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),
|
||||
@@ -363,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),
|
||||
|
||||
@@ -4,10 +4,7 @@ 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(
|
||||
@@ -23,24 +20,32 @@ fn recent_announce_from_cached_packet(
|
||||
timestamp,
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
raw_packet,
|
||||
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(&recent.raw_packet)
|
||||
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
|
||||
&& recent.raw_packet.len() >= offset
|
||||
&& let Ok(announce) = rns_identity::announce::AnnounceData::unpack(
|
||||
&recent.raw_packet[offset..],
|
||||
header.flags.context_flag,
|
||||
)
|
||||
&& raw_packet.len() >= offset
|
||||
{
|
||||
recent.app_data = announce.app_data;
|
||||
recent.public_key = Some(announce.public_key);
|
||||
recent.ratchet = announce.ratchet;
|
||||
recent.name_hash = announce.name_hash;
|
||||
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
|
||||
@@ -85,15 +90,240 @@ fn load_indexed_python_cached_announce(
|
||||
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 self.shared_instance_client_mode {
|
||||
trace!("skipping routing-state save in shared-instance client mode");
|
||||
@@ -102,117 +332,18 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
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_and_tunnels(
|
||||
&self.path_table,
|
||||
Some(&self.tunnel_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());
|
||||
}
|
||||
|
||||
let python_tunnels_path = dir.join("tunnels");
|
||||
if let Err(e) = crate::persistence::save_python_tunnel_table(
|
||||
&self.tunnel_table,
|
||||
&interface_names,
|
||||
&python_tunnels_path,
|
||||
) {
|
||||
trace!("failed to save Python tunnels table: {}", e);
|
||||
}
|
||||
|
||||
// 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();
|
||||
@@ -231,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();
|
||||
}
|
||||
@@ -567,66 +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();
|
||||
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]
|
||||
};
|
||||
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!(count, expired, "loaded announce cache entries from disk");
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -842,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(
|
||||
@@ -130,12 +131,7 @@ impl TransportActor {
|
||||
.recent_announces
|
||||
.values()
|
||||
.map(|a| {
|
||||
let is_path_response =
|
||||
rns_wire::header::PacketHeader::unpack(&a.raw_packet)
|
||||
.ok()
|
||||
.is_some_and(|(header, _)| {
|
||||
header.context == rns_wire::context::PacketContext::PathResponse
|
||||
});
|
||||
let is_path_response = a.is_path_response;
|
||||
AnnounceRpcEntry {
|
||||
dest_hash: a.dest_hash,
|
||||
hops: a.hops,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -82,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;
|
||||
|
||||
@@ -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]>,
|
||||
|
||||
@@ -4,6 +4,15 @@
|
||||
//! [`actor::TransportActor`] owns all mutable state; other crates send typed
|
||||
//! [`messages::TransportMessage`]s over a Tokio mpsc channel.
|
||||
|
||||
/// Unix time as f64 seconds — Python `time.time()` equivalent, the timebase
|
||||
/// used across path/reverse/rate/blackhole/tunnel tables.
|
||||
pub fn now_f64() -> f64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64()
|
||||
}
|
||||
|
||||
pub mod actor;
|
||||
pub mod announce;
|
||||
pub mod await_path;
|
||||
|
||||
@@ -100,10 +100,7 @@ impl LinkTable {
|
||||
/// Returns `(total_culled, expired_unvalidated_links)` — the caller can
|
||||
/// apply failed-link rediscovery rules using the retained route metadata.
|
||||
pub fn cull_stale(&mut self, timeout: f64) -> (usize, Vec<ExpiredLink>) {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
let cutoff = now - timeout;
|
||||
|
||||
let mut unvalidated_expired = Vec::new();
|
||||
@@ -228,10 +225,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_link_table_cull_validated_vs_unvalidated() {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
let mut table = LinkTable::new();
|
||||
|
||||
@@ -314,10 +308,7 @@ mod tests {
|
||||
active.insert(1u64);
|
||||
active.insert(2u64);
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
table.insert(
|
||||
[0x01; 16],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::now_f64;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::constants::{
|
||||
AP_PATH_TIME, DESTINATION_TIMEOUT, InterfaceMode, MAX_RANDOM_BLOBS, PERSIST_RANDOM_BLOBS,
|
||||
@@ -88,6 +88,7 @@ impl PathEntry {
|
||||
|
||||
/// Destination-hash → path mapping plus a parallel liveness state map so we
|
||||
/// can probe unresponsive paths without rewriting the entries.
|
||||
#[derive(Clone)]
|
||||
pub struct PathTable {
|
||||
entries: HashMap<DestHash, PathEntry>,
|
||||
states: HashMap<DestHash, PathState>,
|
||||
@@ -262,13 +263,6 @@ fn path_expiry(mode: InterfaceMode) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
fn now_f64() -> f64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Atomic msgpack persistence for transport tables. `atomic_write` is
|
||||
//! write-to-tmp + rename so a crash leaves either the old or new file.
|
||||
//! write-to-tmp + fsync + rename (via the shared rns-identity helper) so a
|
||||
//! crash or power loss leaves either the old or the new file, never a torn one.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
@@ -255,106 +256,36 @@ pub fn load_python_destination_table(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn save_python_announce_cache_for_paths<'a, I>(
|
||||
path_entries: &PathTable,
|
||||
announces: I,
|
||||
interface_names: &HashMap<u64, String>,
|
||||
announce_cache_dir: &Path,
|
||||
) -> Result<(), PersistenceError>
|
||||
where
|
||||
I: IntoIterator<Item = &'a crate::actor::RecentAnnounce>,
|
||||
{
|
||||
save_python_announce_cache_for_paths_and_tunnels(
|
||||
path_entries,
|
||||
None,
|
||||
announces,
|
||||
interface_names,
|
||||
announce_cache_dir,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn save_python_announce_cache_for_paths_and_tunnels<'a, I>(
|
||||
path_entries: &PathTable,
|
||||
tunnel_table: Option<&crate::tunnel::TunnelTable>,
|
||||
announces: I,
|
||||
interface_names: &HashMap<u64, String>,
|
||||
announce_cache_dir: &Path,
|
||||
) -> Result<(), PersistenceError>
|
||||
where
|
||||
I: IntoIterator<Item = &'a crate::actor::RecentAnnounce>,
|
||||
{
|
||||
std::fs::create_dir_all(announce_cache_dir).map_err(PersistenceError::Io)?;
|
||||
let announces_by_dest: HashMap<[u8; 16], &crate::actor::RecentAnnounce> =
|
||||
announces.into_iter().map(|a| (a.dest_hash, a)).collect();
|
||||
let mut written = std::collections::HashSet::new();
|
||||
|
||||
for (dest_hash, path_entry) in path_entries.iter() {
|
||||
let Some(packet_hash) = path_entry.packet_hash else {
|
||||
continue;
|
||||
};
|
||||
let Some(announce) = announces_by_dest.get(dest_hash.as_bytes()) else {
|
||||
continue;
|
||||
};
|
||||
if announce.raw_packet.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let interface_reference = interface_names
|
||||
.get(&path_entry.interface_id)
|
||||
.map(|name| Value::String(name.as_str().into()))
|
||||
.unwrap_or(Value::Nil);
|
||||
write_python_cached_announce(
|
||||
announce_cache_dir,
|
||||
&packet_hash,
|
||||
announce.raw_packet.clone(),
|
||||
interface_reference,
|
||||
)?;
|
||||
written.insert(packet_hash);
|
||||
}
|
||||
|
||||
if let Some(tunnel_table) = tunnel_table {
|
||||
for tunnel in tunnel_table.iter().map(|(_, tunnel)| tunnel) {
|
||||
let interface_reference = interface_names
|
||||
.get(&tunnel.interface_id)
|
||||
.map(|name| Value::String(name.as_str().into()))
|
||||
.unwrap_or(Value::Nil);
|
||||
for (dest_hash, tunnel_path) in &tunnel.tunnel_paths {
|
||||
let Some(packet_hash) = tunnel_path.packet_hash else {
|
||||
continue;
|
||||
};
|
||||
if written.contains(&packet_hash) {
|
||||
continue;
|
||||
}
|
||||
let Some(announce) = announces_by_dest.get(dest_hash) else {
|
||||
continue;
|
||||
};
|
||||
if announce.raw_packet.is_empty() {
|
||||
continue;
|
||||
}
|
||||
write_python_cached_announce(
|
||||
announce_cache_dir,
|
||||
&packet_hash,
|
||||
announce.raw_packet.clone(),
|
||||
interface_reference.clone(),
|
||||
)?;
|
||||
written.insert(packet_hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_python_cached_announce(
|
||||
/// Write one announce's raw bytes into the Python-compatible per-packet
|
||||
/// announce cache, skipping when the file already exists (cache files are
|
||||
/// content-addressed by packet hash, and SINGLE announces retransmit
|
||||
/// byte-identical). Plain tmp+rename without fsync — matches Python
|
||||
/// `Transport.cache`'s plain write; the cache is best-effort and rebuilt
|
||||
/// from live traffic, and this runs on the actor for every fresh announce.
|
||||
pub fn write_python_cached_announce_if_absent(
|
||||
announce_cache_dir: &Path,
|
||||
packet_hash: &[u8; 32],
|
||||
raw_packet: Vec<u8>,
|
||||
interface_reference: Value,
|
||||
raw_packet: &[u8],
|
||||
interface_name: Option<&str>,
|
||||
) -> Result<(), PersistenceError> {
|
||||
let value = Value::Array(vec![Value::Binary(raw_packet), interface_reference]);
|
||||
let path = announce_cache_dir.join(hex::encode(packet_hash));
|
||||
if path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(announce_cache_dir).map_err(PersistenceError::Io)?;
|
||||
let interface_reference = interface_name
|
||||
.map(|name| Value::String(name.into()))
|
||||
.unwrap_or(Value::Nil);
|
||||
let value = Value::Array(vec![
|
||||
Value::Binary(raw_packet.to_vec()),
|
||||
interface_reference,
|
||||
]);
|
||||
let mut serialized = Vec::new();
|
||||
rmpv::encode::write_value(&mut serialized, &value)
|
||||
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
|
||||
let path = announce_cache_dir.join(hex::encode(packet_hash));
|
||||
atomic_write_bytes(&path, &serialized)
|
||||
let tmp = path.with_extension("tmp");
|
||||
std::fs::write(&tmp, &serialized).map_err(PersistenceError::Io)?;
|
||||
std::fs::rename(&tmp, &path).map_err(PersistenceError::Io)
|
||||
}
|
||||
|
||||
pub fn load_python_cached_announce(
|
||||
@@ -602,11 +533,9 @@ fn atomic_write<T: Serialize>(path: &Path, data: &T) -> Result<(), PersistenceEr
|
||||
}
|
||||
|
||||
fn atomic_write_bytes(path: &Path, serialized: &[u8]) -> Result<(), PersistenceError> {
|
||||
let tmp_path = path.with_extension("tmp");
|
||||
std::fs::write(&tmp_path, serialized).map_err(PersistenceError::Io)?;
|
||||
std::fs::rename(&tmp_path, path).map_err(PersistenceError::Io)?;
|
||||
|
||||
Ok(())
|
||||
// Single canonical atomic-write implementation (fsync + rename + dir
|
||||
// sync) lives in rns-identity; transport tables share it (AF-2026-04.2).
|
||||
rns_identity::persistence::atomic_write(path, serialized).map_err(PersistenceError::Io)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -839,15 +768,42 @@ pub struct PersistedAnnounceEntry {
|
||||
pub timestamp: f64,
|
||||
pub public_key: Option<Vec<u8>>,
|
||||
pub ratchet: Option<Vec<u8>>,
|
||||
/// Raw announce bytes so CacheRequest replays hit a byte-identical packet
|
||||
/// instead of re-serialising (which would disturb signatures).
|
||||
pub raw_packet: Vec<u8>,
|
||||
/// Disk announce-cache key (`cache/announces/<hex>`). Raw announce bytes
|
||||
/// are not persisted inline since v6 — CacheRequest replays read the
|
||||
/// byte-identical packet from the per-announce cache file.
|
||||
#[serde(default)]
|
||||
pub packet_hash: Option<Vec<u8>>,
|
||||
/// Pinned via `RetainDestination`; the maintenance sweep skips the
|
||||
/// entry regardless of age while this is `true`.
|
||||
pub retained: bool,
|
||||
/// `SHA-256(app_name)[:10]` of the announced aspect. Lets cache consumers
|
||||
/// retro-filter without re-parsing `raw_packet`.
|
||||
/// retro-filter without re-parsing the announce.
|
||||
pub name_hash: Vec<u8>,
|
||||
#[serde(default)]
|
||||
pub is_path_response: bool,
|
||||
#[serde(default)]
|
||||
pub last_used: Option<f64>,
|
||||
}
|
||||
|
||||
/// Exact v5 on-disk entry shape (raw announce bytes inline), kept for
|
||||
/// one-shot migration to the disk-backed v6 cache.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct LegacyPersistedAnnounceEntryV5 {
|
||||
pub destination_hash: Vec<u8>,
|
||||
pub hops: u8,
|
||||
pub app_data: Option<Vec<u8>>,
|
||||
pub timestamp: f64,
|
||||
pub public_key: Option<Vec<u8>>,
|
||||
pub ratchet: Option<Vec<u8>>,
|
||||
pub raw_packet: Vec<u8>,
|
||||
pub retained: bool,
|
||||
pub name_hash: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct LegacyPersistedAnnounceCacheV5 {
|
||||
entries: Vec<LegacyPersistedAnnounceEntryV5>,
|
||||
version: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -857,7 +813,8 @@ pub struct PersistedAnnounceCache {
|
||||
}
|
||||
|
||||
impl PersistedAnnounceCache {
|
||||
pub const CURRENT_VERSION: u32 = 5;
|
||||
pub const CURRENT_VERSION: u32 = 6;
|
||||
pub const LEGACY_RAW_VERSION: u32 = 5;
|
||||
}
|
||||
|
||||
pub fn save_announce_cache<'a, I>(announces: I, path: &Path) -> Result<(), PersistenceError>
|
||||
@@ -873,9 +830,11 @@ where
|
||||
timestamp: a.timestamp,
|
||||
public_key: a.public_key.map(|k| k.to_vec()),
|
||||
ratchet: a.ratchet.map(|r| r.to_vec()),
|
||||
raw_packet: a.raw_packet.clone(),
|
||||
packet_hash: a.packet_hash.map(|h| h.to_vec()),
|
||||
retained: a.retained,
|
||||
name_hash: a.name_hash.to_vec(),
|
||||
is_path_response: a.is_path_response,
|
||||
last_used: a.last_used,
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -902,6 +861,70 @@ pub fn load_announce_cache(path: &Path) -> Result<Vec<PersistedAnnounceEntry>, P
|
||||
Ok(persisted.entries)
|
||||
}
|
||||
|
||||
/// Decode a v5 announce cache (raw bytes inline). Used only as the fallback
|
||||
/// path when `load_announce_cache` rejects the file.
|
||||
pub fn load_announce_cache_legacy_v5(
|
||||
path: &Path,
|
||||
) -> Result<Vec<LegacyPersistedAnnounceEntryV5>, PersistenceError> {
|
||||
let data = std::fs::read(path).map_err(PersistenceError::Io)?;
|
||||
let persisted: LegacyPersistedAnnounceCacheV5 =
|
||||
rmp_serde::from_slice(&data).map_err(|e| PersistenceError::Deserialize(e.to_string()))?;
|
||||
if persisted.version != PersistedAnnounceCache::LEGACY_RAW_VERSION {
|
||||
return Err(PersistenceError::VersionMismatch {
|
||||
expected: PersistedAnnounceCache::LEGACY_RAW_VERSION,
|
||||
found: persisted.version,
|
||||
});
|
||||
}
|
||||
Ok(persisted.entries)
|
||||
}
|
||||
|
||||
/// One-shot v5 → v6 migration: write each entry's raw announce into the
|
||||
/// per-packet disk cache, derive `packet_hash`/`is_path_response` from the
|
||||
/// raw bytes, and return the slim v6 shape. Entries whose raw bytes fail to
|
||||
/// parse keep `packet_hash = None` (replay treats that as a cache miss).
|
||||
pub fn migrate_legacy_announce_entries(
|
||||
legacy: Vec<LegacyPersistedAnnounceEntryV5>,
|
||||
announce_cache_dir: &Path,
|
||||
) -> Vec<PersistedAnnounceEntry> {
|
||||
legacy
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let mut packet_hash = None;
|
||||
let mut is_path_response = false;
|
||||
if !e.raw_packet.is_empty() {
|
||||
if let Ok((header, _)) = rns_wire::header::PacketHeader::unpack(&e.raw_packet) {
|
||||
let hash = rns_wire::hash::packet_hash(&e.raw_packet, header.flags.header_type);
|
||||
is_path_response =
|
||||
header.context == rns_wire::context::PacketContext::PathResponse;
|
||||
if write_python_cached_announce_if_absent(
|
||||
announce_cache_dir,
|
||||
&hash,
|
||||
&e.raw_packet,
|
||||
None,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
packet_hash = Some(hash.to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
PersistedAnnounceEntry {
|
||||
destination_hash: e.destination_hash,
|
||||
hops: e.hops,
|
||||
app_data: e.app_data,
|
||||
timestamp: e.timestamp,
|
||||
public_key: e.public_key,
|
||||
ratchet: e.ratchet,
|
||||
packet_hash,
|
||||
retained: e.retained,
|
||||
name_hash: e.name_hash,
|
||||
is_path_response,
|
||||
last_used: None,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PersistedTunnelEntry {
|
||||
pub tunnel_id: Vec<u8>,
|
||||
@@ -1052,6 +1075,32 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_write_bytes_uses_shared_fsync_helper() {
|
||||
// AF-2026-04.2: transport tables must go through the rns-identity
|
||||
// atomic_write (fsync before rename). The shared helper creates the
|
||||
// temp file with mode 0600 — observable proof of delegation, unlike
|
||||
// the old fs::write path (umask default).
|
||||
let dir = std::env::temp_dir().join("reticulum_rs_test_atomic_bytes");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let path = dir.join("snapshot.msgpack");
|
||||
|
||||
atomic_write_bytes(&path, b"first").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"first");
|
||||
// Overwrite must replace cleanly (rename on top).
|
||||
atomic_write_bytes(&path, b"second").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"second");
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_skips_entries_with_no_interface_name() {
|
||||
let mut table = PathTable::new();
|
||||
@@ -1154,19 +1203,14 @@ mod tests {
|
||||
);
|
||||
assert_eq!(loaded[0].packet_hash, packet_hash);
|
||||
|
||||
let announces = [crate::actor::RecentAnnounce {
|
||||
dest_hash: destination_hash,
|
||||
hops: 2,
|
||||
app_data: None,
|
||||
timestamp: 1234.5,
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
raw_packet: vec![0xFE; 42],
|
||||
retained: false,
|
||||
name_hash: [0xAB; 10],
|
||||
}];
|
||||
let cache_dir = dir.join("cache").join("announces");
|
||||
save_python_announce_cache_for_paths(&table, announces.iter(), &names, &cache_dir).unwrap();
|
||||
write_python_cached_announce_if_absent(
|
||||
&cache_dir,
|
||||
&packet_hash,
|
||||
&[0xFE; 42],
|
||||
Some("Interface[Test]"),
|
||||
)
|
||||
.unwrap();
|
||||
let cached = load_python_cached_announce(&cache_dir, &packet_hash)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
@@ -1179,6 +1223,41 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_announce_write_if_absent_does_not_overwrite() {
|
||||
let dir = std::env::temp_dir().join("reticulum_rs_test_announce_if_absent");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let cache_dir = dir.join("cache").join("announces");
|
||||
let packet_hash = [0xCC; 32];
|
||||
|
||||
write_python_cached_announce_if_absent(
|
||||
&cache_dir,
|
||||
&packet_hash,
|
||||
&[0xFE; 42],
|
||||
Some("Interface[First]"),
|
||||
)
|
||||
.unwrap();
|
||||
// Second write for the same packet hash is a no-op.
|
||||
write_python_cached_announce_if_absent(
|
||||
&cache_dir,
|
||||
&packet_hash,
|
||||
&[0x00; 8],
|
||||
Some("Interface[Second]"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let cached = load_python_cached_announce(&cache_dir, &packet_hash)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(cached.raw_packet, vec![0xFE; 42]);
|
||||
assert_eq!(
|
||||
cached.interface_reference.as_deref(),
|
||||
Some("Interface[First]")
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_load_python_tunnel_table_and_tunnel_announce_cache() {
|
||||
let destination_hash = [0xAB; 16];
|
||||
@@ -1228,25 +1307,12 @@ mod tests {
|
||||
assert_eq!(loaded[0].paths[0].hops, 3);
|
||||
assert_eq!(loaded[0].paths[0].packet_hash, packet_hash);
|
||||
|
||||
let announces = [crate::actor::RecentAnnounce {
|
||||
dest_hash: destination_hash,
|
||||
hops: 3,
|
||||
app_data: None,
|
||||
timestamp: 1234.5,
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
raw_packet: vec![0xFE; 42],
|
||||
retained: false,
|
||||
name_hash: [0xAB; 10],
|
||||
}];
|
||||
let empty_paths = PathTable::new();
|
||||
let cache_dir = dir.join("cache").join("announces");
|
||||
save_python_announce_cache_for_paths_and_tunnels(
|
||||
&empty_paths,
|
||||
Some(&tunnels),
|
||||
announces.iter(),
|
||||
&names,
|
||||
write_python_cached_announce_if_absent(
|
||||
&cache_dir,
|
||||
&packet_hash,
|
||||
&[0xFE; 42],
|
||||
Some("Interface[Tunnel]"),
|
||||
)
|
||||
.unwrap();
|
||||
let cached = load_python_cached_announce(&cache_dir, &packet_hash)
|
||||
@@ -1529,8 +1595,10 @@ mod tests {
|
||||
timestamp: 1000.0,
|
||||
public_key: None,
|
||||
ratchet: Some([0xDD; 32]),
|
||||
raw_packet: vec![0xEE; 64],
|
||||
packet_hash: Some([0xEE; 32]),
|
||||
is_path_response: true,
|
||||
retained: false,
|
||||
last_used: Some(1234.0),
|
||||
name_hash: [0xAB; 10],
|
||||
}];
|
||||
|
||||
@@ -1545,6 +1613,117 @@ mod tests {
|
||||
assert_eq!(loaded[0].destination_hash, [0xCC; 16].to_vec());
|
||||
assert_eq!(loaded[0].hops, 3);
|
||||
assert_eq!(loaded[0].ratchet, Some(vec![0xDD; 32]));
|
||||
assert_eq!(loaded[0].packet_hash, Some([0xEE; 32].to_vec()));
|
||||
assert!(loaded[0].is_path_response);
|
||||
assert_eq!(loaded[0].last_used, Some(1234.0));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn packed_test_announce(context: rns_wire::context::PacketContext, fill: u8) -> Vec<u8> {
|
||||
let header = rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
context_flag: false,
|
||||
transport_type: rns_wire::flags::TransportType::Broadcast,
|
||||
destination_type: rns_wire::flags::DestinationType::Single,
|
||||
packet_type: rns_wire::flags::PacketType::Announce,
|
||||
},
|
||||
hops: 1,
|
||||
transport_id: None,
|
||||
destination_hash: [fill; 16],
|
||||
context,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(&[fill; 32]);
|
||||
raw
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_v5_announce_cache_migrates_raw_to_disk_cache() {
|
||||
// Exact v5 on-disk shape: raw announce bytes inline, no packet_hash /
|
||||
// is_path_response / last_used.
|
||||
#[derive(Serialize)]
|
||||
struct V5Entry {
|
||||
destination_hash: Vec<u8>,
|
||||
hops: u8,
|
||||
app_data: Option<Vec<u8>>,
|
||||
timestamp: f64,
|
||||
public_key: Option<Vec<u8>>,
|
||||
ratchet: Option<Vec<u8>>,
|
||||
raw_packet: Vec<u8>,
|
||||
retained: bool,
|
||||
name_hash: Vec<u8>,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct V5Cache {
|
||||
entries: Vec<V5Entry>,
|
||||
version: u32,
|
||||
}
|
||||
|
||||
let plain_raw = packed_test_announce(rns_wire::context::PacketContext::None, 0xA1);
|
||||
let plain_hash =
|
||||
rns_wire::hash::packet_hash(&plain_raw, rns_wire::flags::HeaderType::Header1);
|
||||
let pr_raw = packed_test_announce(rns_wire::context::PacketContext::PathResponse, 0xB2);
|
||||
let pr_hash = rns_wire::hash::packet_hash(&pr_raw, rns_wire::flags::HeaderType::Header1);
|
||||
|
||||
let entry = |dest: u8, raw: Vec<u8>, retained: bool| V5Entry {
|
||||
destination_hash: vec![dest; 16],
|
||||
hops: 1,
|
||||
app_data: None,
|
||||
timestamp: 1000.0,
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
raw_packet: raw,
|
||||
retained,
|
||||
name_hash: vec![0xAB; 10],
|
||||
};
|
||||
let v5 = V5Cache {
|
||||
entries: vec![
|
||||
entry(0xA1, plain_raw.clone(), true),
|
||||
entry(0xB2, pr_raw.clone(), false),
|
||||
// Too short for PacketHeader::unpack — must migrate as a miss.
|
||||
entry(0xC3, vec![0x01], false),
|
||||
],
|
||||
version: 5,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec(&v5).unwrap();
|
||||
|
||||
let dir = std::env::temp_dir().join("reticulum_rs_test_announce_v5_migration");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("announce_cache.msgpack");
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
|
||||
assert!(
|
||||
load_announce_cache(&path).is_err(),
|
||||
"v6 loader must reject a v5 snapshot"
|
||||
);
|
||||
|
||||
let legacy = load_announce_cache_legacy_v5(&path).unwrap();
|
||||
assert_eq!(legacy.len(), 3);
|
||||
let cache_dir = dir.join("cache").join("announces");
|
||||
let migrated = migrate_legacy_announce_entries(legacy, &cache_dir);
|
||||
|
||||
assert_eq!(migrated.len(), 3);
|
||||
assert_eq!(migrated[0].destination_hash, vec![0xA1; 16]);
|
||||
assert_eq!(migrated[0].packet_hash, Some(plain_hash.to_vec()));
|
||||
assert!(!migrated[0].is_path_response);
|
||||
assert!(migrated[0].retained);
|
||||
assert_eq!(migrated[0].last_used, None);
|
||||
assert_eq!(migrated[1].packet_hash, Some(pr_hash.to_vec()));
|
||||
assert!(migrated[1].is_path_response);
|
||||
assert_eq!(migrated[2].packet_hash, None);
|
||||
|
||||
// Raw bytes landed in the per-packet disk cache, byte-identical.
|
||||
let on_disk = load_python_cached_announce(&cache_dir, &plain_hash)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(on_disk.raw_packet, plain_raw);
|
||||
let on_disk_pr = load_python_cached_announce(&cache_dir, &pr_hash)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(on_disk_pr.raw_packet, pr_raw);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::constants::MAX_RATE_TIMESTAMPS;
|
||||
@@ -42,10 +41,7 @@ impl RateTable {
|
||||
/// and "blocked" as a single numeric comparison.
|
||||
pub fn record(&mut self, dest_hash: impl Into<DestHash>) -> f64 {
|
||||
let dest_hash = dest_hash.into();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
let entry = self.entries.entry(dest_hash).or_insert_with(|| RateEntry {
|
||||
timestamps: Vec::new(),
|
||||
@@ -101,10 +97,7 @@ impl RateTable {
|
||||
}
|
||||
|
||||
pub fn is_blocked(&self, dest_hash: &[u8; 16]) -> bool {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
self.entries
|
||||
.get(dest_hash)
|
||||
.is_some_and(|e| e.blocked_until > now)
|
||||
@@ -151,10 +144,7 @@ impl RateTable {
|
||||
rate_penalty: f64,
|
||||
) -> bool {
|
||||
let dest_hash = dest_hash.into();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
let entry = match self.entries.entry(dest_hash) {
|
||||
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::constants::REVERSE_TIMEOUT;
|
||||
use crate::messages::InterfaceId;
|
||||
@@ -48,10 +47,7 @@ impl ReverseTable {
|
||||
remaining_hops: u8,
|
||||
outbound_interface: Option<InterfaceId>,
|
||||
) {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
self.entries.insert(
|
||||
packet_hash.into(),
|
||||
@@ -73,10 +69,7 @@ impl ReverseTable {
|
||||
}
|
||||
|
||||
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 cutoff = now - REVERSE_TIMEOUT as f64;
|
||||
|
||||
let before = self.entries.len();
|
||||
@@ -86,10 +79,7 @@ impl ReverseTable {
|
||||
|
||||
/// Batched cull — bounds per-tick work on large tables.
|
||||
pub fn cull_expired_batch(&mut self, limit: usize) -> usize {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
let cutoff = now - REVERSE_TIMEOUT as f64;
|
||||
|
||||
let to_remove: Vec<TruncatedHash> = self
|
||||
|
||||
@@ -23,6 +23,7 @@ pub struct TunnelPath {
|
||||
pub packet_hash: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TunnelTable {
|
||||
entries: HashMap<[u8; 32], TunnelEntry>,
|
||||
}
|
||||
@@ -79,10 +80,7 @@ impl TunnelTable {
|
||||
}
|
||||
|
||||
pub fn cull_expired(&mut self) -> usize {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
let before = self.entries.len();
|
||||
self.entries.retain(|_, entry| entry.expires > now);
|
||||
@@ -91,10 +89,7 @@ impl TunnelTable {
|
||||
|
||||
/// Batched cull — bounds per-tick work on large tables.
|
||||
pub fn cull_expired_batch(&mut self, limit: usize) -> usize {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
|
||||
let to_remove: Vec<[u8; 32]> = self
|
||||
.entries
|
||||
@@ -182,10 +177,7 @@ pub fn handle_tunnel(
|
||||
interface_id: crate::messages::InterfaceId,
|
||||
destination_timeout: f64,
|
||||
) {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
let now = crate::now_f64();
|
||||
let expires = now + destination_timeout;
|
||||
|
||||
if let Some(existing) = tunnel_table.get_mut(&tunnel_id) {
|
||||
|
||||
Reference in new issue
Block a user