mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
i2p: announce one discoverable interface at its own b32 and keep peers at Python's defaults
This commit is contained in:
1 parent
53515b3d41
commit
f3f72ead60
7 files changed
+411
-35
No files matched your search
@@ -16,6 +16,7 @@
|
||||
- PLAIN and GROUP packets that arrive from more than one hop away, and announces typed PLAIN or GROUP, are dropped before deduplication, as in Python Reticulum.
|
||||
- TCP, Backbone and I2P client interfaces open every connection with a tunnel synthesis, so a transport hub restores their paths after a reconnect, and traffic queued while a connection was down or failing to open is dropped when it opens, as in Python Reticulum.
|
||||
- A client of a Unix-socket shared instance drops traffic queued while the instance was unreachable, as in Python Reticulum.
|
||||
- A discoverable I2P interface announces itself once, at its own b32 address, instead of once per peer at a peer's address, and the peers listed in `peers` keep Python's defaults instead of the interface's mode and announce settings, sharing only its IFAC, as in Python Reticulum.
|
||||
- Python Reticulum 1.5 `rnstatus` and `rnpath` work against `rnsd-rs`, locally and with `-R`: interface stats carry every field they read, including announce and path request counts, violation counters and the transport instance, and remote management answers on the transport identity, as in Python Reticulum.
|
||||
- Announces held during an ingress burst on an IFAC interface are processed when released instead of being dropped, and released or replayed announces no longer count as received traffic again, as in Python Reticulum.
|
||||
- Interface discovery announces name this stack, `rsRNS`, and its version. `rnsd-rs` auto-connects only to Backbone interfaces announced by Python Reticulum 1.5.2 or later, or to any announced Backbone interface with `autoconnect_unverified_implementations`, and no longer stores or lists discovered TCP client interfaces, as in Python Reticulum.
|
||||
|
||||
@@ -42,6 +42,10 @@ reports an unqualified filesystem. `persistence::storage_risk` classifies networ
|
||||
or user-space (`Remote`) and RAM-backed (`Volatile`) storage so applications can
|
||||
warn their users.
|
||||
|
||||
`I2PServerConfig` gains `b32`, which receives the server's b32 address when
|
||||
SAM creates its session, and `i2p::destination_b32` derives that address from
|
||||
a SAM private key; build the config with `new`.
|
||||
|
||||
`TunnelEntry::interface_id` is now `Option<InterfaceId>`, `None` while the
|
||||
tunnel is unbound, instead of the id-0 sentinel. `spawn_local_server` and
|
||||
`spawn_i2p_server` take the listener's allocated `InterfaceId`, which their
|
||||
|
||||
@@ -459,6 +459,7 @@ pub rns_interface::i2p::I2PClientConfig::tunnel_identity: core::option::Option<r
|
||||
impl rns_interface::i2p::I2PClientConfig
|
||||
pub fn rns_interface::i2p::I2PClientConfig::new(&str, &str) -> Self
|
||||
pub struct rns_interface::i2p::I2PServerConfig
|
||||
pub rns_interface::i2p::I2PServerConfig::b32: core::option::Option<tokio::sync::watch::Sender<core::option::Option<alloc::string::String>>>
|
||||
pub rns_interface::i2p::I2PServerConfig::keyfile: core::option::Option<alloc::string::String>
|
||||
pub rns_interface::i2p::I2PServerConfig::mode: rns_interface::traits::InterfaceMode
|
||||
pub rns_interface::i2p::I2PServerConfig::name: alloc::string::String
|
||||
@@ -480,6 +481,7 @@ pub const rns_interface::i2p::RECONNECT_WAIT: u64
|
||||
pub const rns_interface::i2p::RECONNECT_WAIT_MAX: u64
|
||||
pub const rns_interface::i2p::SAM_VERSION: &str
|
||||
pub const rns_interface::i2p::TUNNEL_KEEPALIVE: u64
|
||||
pub fn rns_interface::i2p::destination_b32(&str) -> core::option::Option<alloc::string::String>
|
||||
pub fn rns_interface::i2p::parse_sam_reply(&str) -> alloc::vec::Vec<(alloc::string::String, alloc::string::String)>
|
||||
pub fn rns_interface::i2p::sam_reply_get<'a>(&'a [(alloc::string::String, alloc::string::String)], &str) -> core::option::Option<&'a str>
|
||||
pub fn rns_interface::i2p::sam_reply_has_token(&[(alloc::string::String, alloc::string::String)], &str) -> bool
|
||||
|
||||
+2
-2
@@ -78,8 +78,8 @@
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-interface.txt",
|
||||
"itemCount": 1428,
|
||||
"sha256": "e34b67309d70de46edbcec1941517a5602603bdf76a1944e249bd3fa95bf2146"
|
||||
"itemCount": 1430,
|
||||
"sha256": "00ef8baba7b42d50c77748061dc1ed3cf4c3fbf0d6b5756ac316f2a5e0cb5731"
|
||||
},
|
||||
{
|
||||
"name": "rns-runtime",
|
||||
|
||||
@@ -293,6 +293,9 @@ pub struct I2PServerConfig {
|
||||
pub keyfile: Option<String>,
|
||||
pub reconnect_delay: u64,
|
||||
pub mode: InterfaceMode,
|
||||
/// Receives the server's b32 address (Python `I2PInterface.b32`) whenever
|
||||
/// SAM creates its session.
|
||||
pub b32: Option<tokio::sync::watch::Sender<Option<String>>>,
|
||||
}
|
||||
|
||||
impl I2PServerConfig {
|
||||
@@ -304,10 +307,65 @@ impl I2PServerConfig {
|
||||
keyfile: None,
|
||||
reconnect_delay: RECONNECT_WAIT,
|
||||
mode: InterfaceMode::Full,
|
||||
b32: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The b32 address of the destination in a SAM private key: the hash of its
|
||||
/// first 387 bytes plus its certificate (i2plib `Destination.base32`,
|
||||
/// RNS/vendor/i2plib/sam.py:113-129).
|
||||
pub fn destination_b32(private_key: &str) -> Option<String> {
|
||||
let key = i2p_base64_decode(private_key)?;
|
||||
let certificate = usize::from(u16::from_be_bytes(key.get(385..387)?.try_into().ok()?));
|
||||
let hash = rns_crypto::sha::sha256(key.get(..387 + certificate)?);
|
||||
Some(base32_lowercase(&hash))
|
||||
}
|
||||
|
||||
/// Base64 with I2P's `-~` alphabet (i2plib `i2p_b64decode`).
|
||||
fn i2p_base64_decode(text: &str) -> Option<Vec<u8>> {
|
||||
let mut bytes = Vec::with_capacity(text.len() * 3 / 4);
|
||||
let (mut buffer, mut bits) = (0u32, 0u32);
|
||||
for c in text.trim_end_matches('=').bytes() {
|
||||
let value = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'-' => 62,
|
||||
b'~' => 63,
|
||||
_ => return None,
|
||||
};
|
||||
buffer = buffer << 6 | u32::from(value);
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
bytes.push((buffer >> bits) as u8);
|
||||
buffer &= (1 << bits) - 1;
|
||||
}
|
||||
}
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// RFC 4648 base32, lowercase and unpadded.
|
||||
fn base32_lowercase(bytes: &[u8]) -> String {
|
||||
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
|
||||
let mut text = String::with_capacity(bytes.len().div_ceil(5) * 8);
|
||||
let (mut buffer, mut bits) = (0u32, 0u32);
|
||||
for byte in bytes {
|
||||
buffer = buffer << 8 | u32::from(*byte);
|
||||
bits += 8;
|
||||
while bits >= 5 {
|
||||
bits -= 5;
|
||||
text.push(char::from(ALPHABET[(buffer >> bits) as usize & 31]));
|
||||
}
|
||||
buffer &= (1 << bits) - 1;
|
||||
}
|
||||
if bits > 0 {
|
||||
text.push(char::from(ALPHABET[(buffer << (5 - bits)) as usize & 31]));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct I2PClientConfig {
|
||||
pub name: String,
|
||||
@@ -688,6 +746,9 @@ pub async fn spawn_i2p_server(
|
||||
dest_len = our_dest.len(),
|
||||
"I2P server: session created, accepting streams"
|
||||
);
|
||||
if let Some(b32) = &config.b32 {
|
||||
b32.send_replace(destination_b32(&our_dest));
|
||||
}
|
||||
online_task.store(true, Ordering::SeqCst);
|
||||
|
||||
// Each STREAM ACCEPT needs its own SAM TCP connection.
|
||||
@@ -1099,6 +1160,49 @@ mod tests {
|
||||
assert!(!sam_reply_has_token(&pairs, "NONEXISTENT"));
|
||||
}
|
||||
|
||||
fn i2p_base64(bytes: &[u8]) -> String {
|
||||
const ALPHABET: &[u8; 64] =
|
||||
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
|
||||
let mut text = String::new();
|
||||
for chunk in bytes.chunks(3) {
|
||||
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
|
||||
bits | u32::from(*byte) << (16 - 8 * n)
|
||||
});
|
||||
for n in 0..=chunk.len() {
|
||||
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
|
||||
}
|
||||
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn private_key(certificate: &[u8], secret: u8) -> Vec<u8> {
|
||||
let mut key: Vec<u8> = (0..384).map(|n| n as u8).collect();
|
||||
key.extend_from_slice(certificate);
|
||||
key.extend(std::iter::repeat_n(secret, 288));
|
||||
key
|
||||
}
|
||||
|
||||
/// Only the destination, keys plus certificate, names the address
|
||||
/// (i2plib sam.py:113-129); the golden is checked against i2plib in tests.
|
||||
#[test]
|
||||
fn the_b32_address_hashes_only_the_destination() {
|
||||
let ed25519 = [5, 0, 4, 0, 7, 0, 0];
|
||||
let b32 = destination_b32(&i2p_base64(&private_key(&ed25519, 0x42))).unwrap();
|
||||
assert_eq!(b32.len(), 52);
|
||||
assert!(b32.bytes().all(|c| matches!(c, b'a'..=b'z' | b'2'..=b'7')));
|
||||
assert_eq!(
|
||||
destination_b32(&i2p_base64(&private_key(&ed25519, 0x24))).as_ref(),
|
||||
Some(&b32)
|
||||
);
|
||||
assert_ne!(
|
||||
destination_b32(&i2p_base64(&private_key(&[0, 0, 0], 0x42))).as_ref(),
|
||||
Some(&b32)
|
||||
);
|
||||
assert_eq!(destination_b32("not+base64"), None);
|
||||
assert_eq!(destination_b32(&i2p_base64(&[0; 300])), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_session_id() {
|
||||
let id1 = generate_session_id();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! to a Shared instance over a local socket; **Standalone** owns its
|
||||
//! interfaces and exposes no IPC. Python: `RNS/Reticulum.py`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
@@ -1125,6 +1125,8 @@ struct LocalDiscoveryInterface {
|
||||
id: u64,
|
||||
config: DiscoveryInterfaceConfig,
|
||||
online: Option<Arc<AtomicBool>>,
|
||||
/// Overrides `config.reachable_on` once the interface learns its address.
|
||||
reachable_on: Option<tokio::sync::watch::Receiver<Option<String>>>,
|
||||
}
|
||||
|
||||
impl ReticulumHandle {
|
||||
@@ -3533,6 +3535,12 @@ pub async fn init_with_policy(
|
||||
.iter()
|
||||
.map(|owned| (owned.interface.id, owned.interface.online.clone()))
|
||||
.collect();
|
||||
let discovery_addresses: HashMap<_, _> = iface_handles
|
||||
.iter()
|
||||
.filter_map(|owned| {
|
||||
Some((owned.interface.id, owned.discovery_address.clone()?))
|
||||
})
|
||||
.collect();
|
||||
match register_interfaces_with_post_init_batch(
|
||||
&transport_tx,
|
||||
iface_handles,
|
||||
@@ -3551,13 +3559,25 @@ pub async fn init_with_policy(
|
||||
{
|
||||
startup_rnode_runtimes.push(runtime);
|
||||
}
|
||||
for registered_id in registered_ids {
|
||||
// Python announces an I2P interface itself, never its
|
||||
// peers (Discovery.py:112); without a server the
|
||||
// first peer stands in.
|
||||
let announced = match iface_config {
|
||||
interface_factory::InterfaceConfig::I2P(_) => {
|
||||
®istered_ids[..registered_ids.len().min(1)]
|
||||
}
|
||||
_ => ®istered_ids[..],
|
||||
};
|
||||
for ®istered_id in announced {
|
||||
if let Some(ref cfg) = discovery_config {
|
||||
discovery_runtime.local_interfaces.lock().await.push(
|
||||
LocalDiscoveryInterface {
|
||||
id: registered_id,
|
||||
config: cfg.clone(),
|
||||
online: discovery_online.get(®istered_id).cloned(),
|
||||
reachable_on: discovery_addresses
|
||||
.get(®istered_id)
|
||||
.cloned(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -3938,6 +3958,10 @@ fn interface_kind_for_config(config: &interface_factory::InterfaceConfig) -> Int
|
||||
struct OwnedInterfaceHandle {
|
||||
interface: rns_interface::traits::InterfaceHandle,
|
||||
driver: Option<rns_interface::rnode::RNodeDriverHandle>,
|
||||
/// An I2P peer that Python's `I2PInterface` creates for a configured peer.
|
||||
configured_peer: bool,
|
||||
/// The address a discoverable interface learns at runtime (I2P b32).
|
||||
discovery_address: Option<tokio::sync::watch::Receiver<Option<String>>>,
|
||||
}
|
||||
|
||||
/// Startup-only observation captured before ownership moves into the
|
||||
@@ -4019,6 +4043,8 @@ impl From<rns_interface::traits::InterfaceHandle> for OwnedInterfaceHandle {
|
||||
Self {
|
||||
interface,
|
||||
driver: None,
|
||||
configured_peer: false,
|
||||
discovery_address: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4028,6 +4054,8 @@ impl From<rns_interface::rnode::SpawnedRNodeInterface> for OwnedInterfaceHandle
|
||||
Self {
|
||||
interface: spawned.interface,
|
||||
driver: Some(spawned.driver),
|
||||
configured_peer: false,
|
||||
discovery_address: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4516,7 +4544,9 @@ async fn prepare_interface_with_role_and_overrides(
|
||||
error.to_string(),
|
||||
));
|
||||
}
|
||||
let OwnedInterfaceHandle { interface, driver } = owned;
|
||||
let OwnedInterfaceHandle {
|
||||
interface, driver, ..
|
||||
} = owned;
|
||||
let handle = interface;
|
||||
let name = handle.name.clone();
|
||||
let id = handle.id;
|
||||
@@ -4724,6 +4754,29 @@ fn clone_interface_post_init(
|
||||
}
|
||||
}
|
||||
|
||||
/// Python's configured I2P peers take only IFAC from their interface and keep
|
||||
/// every other default (I2PInterface.py:359-381).
|
||||
fn configured_peer_post_init(
|
||||
post_init: &interface_factory::InterfacePostInit,
|
||||
) -> interface_factory::InterfacePostInit {
|
||||
interface_factory::InterfacePostInit {
|
||||
outgoing: true,
|
||||
bitrate: None,
|
||||
announce_cap: None,
|
||||
announce_rate_target: None,
|
||||
announce_rate_grace: None,
|
||||
announce_rate_penalty: None,
|
||||
ifac_network_name: post_init.ifac_network_name.clone(),
|
||||
ifac_passphrase: post_init.ifac_passphrase.clone(),
|
||||
ifac_size: post_init.ifac_size,
|
||||
default_ifac_size: post_init.default_ifac_size,
|
||||
ingress_control: true,
|
||||
ingress_overrides: Default::default(),
|
||||
recursive_prs: false,
|
||||
announces_from_internal: true,
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare_interface_with_post_init(
|
||||
owned: OwnedInterfaceHandle,
|
||||
post_init: &interface_factory::InterfacePostInit,
|
||||
@@ -4732,6 +4785,13 @@ async fn prepare_interface_with_post_init(
|
||||
interface_registry: &InterfaceRegistry,
|
||||
kind: InterfaceKind,
|
||||
) -> Result<PreparedInterfaceRegistration, InterfaceRegistrationError> {
|
||||
let peer_post_init;
|
||||
let post_init = if owned.configured_peer {
|
||||
peer_post_init = configured_peer_post_init(post_init);
|
||||
&peer_post_init
|
||||
} else {
|
||||
post_init
|
||||
};
|
||||
let ingress = if post_init.ingress_overrides.is_empty() {
|
||||
rns_transport::ingress::IngressController::new()
|
||||
} else {
|
||||
@@ -4767,7 +4827,9 @@ async fn prepare_interface_with_post_init(
|
||||
error.to_string(),
|
||||
));
|
||||
}
|
||||
let OwnedInterfaceHandle { interface, driver } = owned;
|
||||
let OwnedInterfaceHandle {
|
||||
interface, driver, ..
|
||||
} = owned;
|
||||
let handle = interface;
|
||||
// Outbound = physical capability AND `outgoing` config flag.
|
||||
let direction = rns_transport::constants::InterfaceDirection {
|
||||
@@ -5553,6 +5615,7 @@ async fn rollback_unreserved_interface(owned: OwnedInterfaceHandle, kind: Interf
|
||||
let OwnedInterfaceHandle {
|
||||
interface: handle,
|
||||
driver,
|
||||
..
|
||||
} = owned;
|
||||
handle.online.store(false, Ordering::SeqCst);
|
||||
stop_special_interface_before_abort(kind).await;
|
||||
@@ -5895,21 +5958,11 @@ fn discovery_config_for_interface(
|
||||
None,
|
||||
None,
|
||||
),
|
||||
interface_factory::InterfaceConfig::I2P(c) => (
|
||||
"I2PInterface",
|
||||
configured_reachable_on(section).or_else(|| {
|
||||
if c.connectable {
|
||||
c.peers.first().cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
// The server announces its own b32 once SAM assigns it
|
||||
// (Discovery.py:215-216).
|
||||
interface_factory::InterfaceConfig::I2P(_) => {
|
||||
("I2PInterface", None, None, None, None, None, None)
|
||||
}
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
interface_factory::InterfaceConfig::RNode(c) => (
|
||||
"RNodeInterface",
|
||||
@@ -6218,7 +6271,7 @@ async fn run_discovery_publisher(
|
||||
}
|
||||
let mut publications: HashMap<u64, Publication> = HashMap::new();
|
||||
let mut announcer = Announcer::new(stamper);
|
||||
let mut registered = HashSet::new();
|
||||
let mut registered: HashMap<u64, Option<String>> = HashMap::new();
|
||||
let mut next_prepare = std::time::Instant::now();
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(1));
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
@@ -6236,12 +6289,21 @@ async fn run_discovery_publisher(
|
||||
.online
|
||||
.as_ref()
|
||||
.is_none_or(|online| online.load(Ordering::Acquire));
|
||||
if online && registered.insert(local.id) {
|
||||
announcer.register(
|
||||
local.id,
|
||||
handle.transport_identity.hash,
|
||||
local.config.clone(),
|
||||
);
|
||||
let reachable_on = local
|
||||
.reachable_on
|
||||
.as_ref()
|
||||
.map(|reachable_on| reachable_on.borrow().clone());
|
||||
let moved = reachable_on
|
||||
.as_ref()
|
||||
.is_some_and(|reachable_on| registered.get(&local.id) != Some(reachable_on));
|
||||
if online && (!registered.contains_key(&local.id) || moved) {
|
||||
let mut config = local.config.clone();
|
||||
if let Some(reachable_on) = reachable_on.clone() {
|
||||
config.reachable_on = reachable_on;
|
||||
}
|
||||
registered.insert(local.id, reachable_on.flatten());
|
||||
publications.remove(&local.id);
|
||||
announcer.register(local.id, handle.transport_identity.hash, config);
|
||||
next_prepare = now;
|
||||
}
|
||||
}
|
||||
@@ -8123,6 +8185,8 @@ async fn spawn_interface_with_rnode_startup_options(
|
||||
server_config.sam_host = c.i2p_sam_host.clone();
|
||||
server_config.sam_port = c.i2p_sam_port;
|
||||
server_config.mode = c.mode;
|
||||
let (b32_tx, b32_rx) = tokio::sync::watch::channel(None);
|
||||
server_config.b32 = Some(b32_tx);
|
||||
let server_id = next.take().unwrap_or_else(|| next_id(&id_gen));
|
||||
let server = rns_interface::i2p::spawn_i2p_server(
|
||||
server_config,
|
||||
@@ -8133,7 +8197,10 @@ async fn spawn_interface_with_rnode_startup_options(
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("I2P server: {e}"))?;
|
||||
handles.push(server.into());
|
||||
handles.push(OwnedInterfaceHandle {
|
||||
discovery_address: Some(b32_rx),
|
||||
..server.into()
|
||||
});
|
||||
}
|
||||
for peer in &c.peers {
|
||||
let mut client_config = rns_interface::i2p::I2PClientConfig::new(
|
||||
@@ -8142,7 +8209,6 @@ async fn spawn_interface_with_rnode_startup_options(
|
||||
);
|
||||
client_config.sam_host = c.i2p_sam_host.clone();
|
||||
client_config.sam_port = c.i2p_sam_port;
|
||||
client_config.mode = c.mode;
|
||||
client_config.tunnel_identity = Some(tunnel_identity.clone());
|
||||
let peer_id = next.take().unwrap_or_else(|| next_id(&id_gen));
|
||||
match rns_interface::i2p::spawn_i2p_client(
|
||||
@@ -8152,7 +8218,10 @@ async fn spawn_interface_with_rnode_startup_options(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(client) => handles.push(client.into()),
|
||||
Ok(client) => handles.push(OwnedInterfaceHandle {
|
||||
configured_peer: true,
|
||||
..client.into()
|
||||
}),
|
||||
Err(e) => {
|
||||
for spawned in handles {
|
||||
rollback_unreserved_interface(spawned, InterfaceKind::Standard).await;
|
||||
@@ -8471,6 +8540,7 @@ pub enum ReticulumError {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
mod interface_stats;
|
||||
mod tunnels;
|
||||
@@ -11772,6 +11842,7 @@ loglevel = 7
|
||||
id,
|
||||
config,
|
||||
online: None,
|
||||
reachable_on: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11868,6 +11939,45 @@ loglevel = 7
|
||||
}
|
||||
}
|
||||
|
||||
/// An interface announces the address it learns at runtime, and again
|
||||
/// whenever that address changes (Discovery.py:215-216).
|
||||
#[tokio::test]
|
||||
async fn discovery_publisher_announces_the_address_an_interface_learns() {
|
||||
use rns_interface::traits::InterfaceMode;
|
||||
let (handle, actor) = discovery_actor();
|
||||
let (_, mut sink) = discovery_egress(&handle, 1, InterfaceMode::Full, 8).await;
|
||||
let (address, reachable_on) = tokio::sync::watch::channel(Some("a".repeat(52)));
|
||||
let mut i2p = advertised_service(44, false);
|
||||
i2p.config.interface_type = "I2PInterface".into();
|
||||
i2p.config.reachable_on = None;
|
||||
i2p.config.port = None;
|
||||
i2p.reachable_on = Some(reachable_on);
|
||||
let publisher = tokio::spawn(run_discovery_announcer(
|
||||
handle.clone(),
|
||||
Arc::new(StaticStamper),
|
||||
vec![i2p],
|
||||
));
|
||||
for b32 in ["a".repeat(52), "b".repeat(52)] {
|
||||
address.send_replace(Some(b32.clone()));
|
||||
let raw = tokio::time::timeout(Duration::from_secs(3), sink.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(read_discovery_packet(&raw, &handle).reachable_on, Some(b32));
|
||||
}
|
||||
handle.shutdown.trigger();
|
||||
tokio::time::timeout(Duration::from_secs(2), publisher)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
handle
|
||||
.transport_tx
|
||||
.send(TransportMessage::Shutdown)
|
||||
.await
|
||||
.unwrap();
|
||||
actor.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_publisher_recovers_eligibility_fifo_and_services_attached_path_requests() {
|
||||
use rns_interface::traits::InterfaceMode;
|
||||
|
||||
@@ -94,6 +94,26 @@ async fn wait_for_interface(
|
||||
}
|
||||
}
|
||||
|
||||
/// A SAM private key in I2P's base64 alphabet: a destination of 384 key bytes
|
||||
/// and an Ed25519 key certificate, then 256 private and 32 signing-key bytes.
|
||||
fn fake_sam_private_key() -> String {
|
||||
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
|
||||
let mut key: Vec<u8> = (0..384).map(|n| n as u8).collect();
|
||||
key.extend_from_slice(&[5, 0, 4, 0, 7, 0, 0]);
|
||||
key.extend(std::iter::repeat_n(0x42, 256 + 32));
|
||||
let mut text = String::new();
|
||||
for chunk in key.chunks(3) {
|
||||
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
|
||||
bits | u32::from(*byte) << (16 - 8 * n)
|
||||
});
|
||||
for n in 0..=chunk.len() {
|
||||
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
|
||||
}
|
||||
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Minimal SAM v3.1 bridge. Completes HELLO, SESSION CREATE and every STREAM
|
||||
/// CONNECT, plus the first `accepts` STREAM ACCEPTs, handing each data socket
|
||||
/// to the test; later accepts stay pending.
|
||||
@@ -128,10 +148,11 @@ async fn fake_sam(
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
|
||||
.is_ok();
|
||||
if command.starts_with("SESSION CREATE") {
|
||||
let _ = reader
|
||||
.get_mut()
|
||||
.write_all(b"SESSION STATUS RESULT=OK DESTINATION=fakesamsession\n")
|
||||
.await;
|
||||
let reply = format!(
|
||||
"SESSION STATUS RESULT=OK DESTINATION={}\n",
|
||||
fake_sam_private_key()
|
||||
);
|
||||
let _ = reader.get_mut().write_all(reply.as_bytes()).await;
|
||||
} else if command.starts_with("STREAM CONNECT") || accepted {
|
||||
let reply: &[u8] = if accepted {
|
||||
b"STREAM STATUS RESULT=OK\npeerdestination0123456789\n"
|
||||
@@ -267,6 +288,140 @@ async fn an_i2p_interface_runs_its_server_and_every_peer() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Python announces only the `I2PInterface` itself; its peers are not
|
||||
/// discoverable (Interface.py:119, Discovery.py:112, :140). Rust has no
|
||||
/// interface for a non-connectable server, so its first peer stands in.
|
||||
#[tokio::test]
|
||||
async fn a_discoverable_i2p_interface_announces_once() {
|
||||
for (connectable, announcer) in [
|
||||
("yes", "Golden I2P"),
|
||||
("no", "Golden I2P to peeraaaaaaaaaaaa.b32.i2p"),
|
||||
] {
|
||||
let (sam_port, _streams) = fake_sam(0).await;
|
||||
let dir = config_dir(
|
||||
"i2p-discovery",
|
||||
&format!(
|
||||
"[reticulum]\n share_instance = No\n enable_transport = Yes\n\n[interfaces]\n [[Golden I2P]]\n type = I2PInterface\n enabled = yes\n connectable = {connectable}\n peers = peeraaaaaaaaaaaa.b32.i2p, peerbbbbbbbbbbbb.b32.i2p\n discoverable = yes\n bootstrap_only = yes\n i2p_sam_host = 127.0.0.1\n i2p_sam_port = {sam_port}\n"
|
||||
),
|
||||
);
|
||||
let handle = start(&dir).await;
|
||||
let registered = interfaces(&handle).await;
|
||||
let name = |id: u64| {
|
||||
registered
|
||||
.iter()
|
||||
.find(|entry| entry.id == id)
|
||||
.map(|entry| entry.name.clone())
|
||||
};
|
||||
let discoverable: Vec<_> = handle
|
||||
.discovery
|
||||
.local_interfaces
|
||||
.lock()
|
||||
.await
|
||||
.iter()
|
||||
.map(|local| name(local.id))
|
||||
.collect();
|
||||
let bootstrap: Vec<_> = handle
|
||||
.discovery
|
||||
.bootstrap_interfaces
|
||||
.lock()
|
||||
.await
|
||||
.iter()
|
||||
.map(|id| name(*id))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
discoverable,
|
||||
[Some(announcer.to_string())],
|
||||
"connectable = {connectable}"
|
||||
);
|
||||
assert_eq!(
|
||||
bootstrap,
|
||||
[Some(announcer.to_string())],
|
||||
"connectable = {connectable}"
|
||||
);
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Python announces a connectable I2P interface at its own b32 address
|
||||
/// (Discovery.py:215-216), never at a configured peer's.
|
||||
#[tokio::test]
|
||||
async fn a_connectable_i2p_interface_announces_its_own_b32() {
|
||||
let (sam_port, _streams) = fake_sam(0).await;
|
||||
let dir = config_dir(
|
||||
"i2p-b32",
|
||||
&format!(
|
||||
"[reticulum]\n share_instance = No\n enable_transport = Yes\n\n[interfaces]\n [[Golden I2P]]\n type = I2PInterface\n enabled = yes\n connectable = yes\n peers = peeraaaaaaaaaaaa.b32.i2p\n discoverable = yes\n i2p_sam_host = 127.0.0.1\n i2p_sam_port = {sam_port}\n"
|
||||
),
|
||||
);
|
||||
let handle = start(&dir).await;
|
||||
let mut reachable = handle.discovery.local_interfaces.lock().await[0]
|
||||
.reachable_on
|
||||
.clone()
|
||||
.expect("the server publishes its address");
|
||||
let b32 = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
reachable.wait_for(|b32| b32.is_some()),
|
||||
)
|
||||
.await
|
||||
.expect("SAM creates the server's session")
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(
|
||||
b32,
|
||||
rns_interface::i2p::destination_b32(&fake_sam_private_key())
|
||||
);
|
||||
assert_eq!(
|
||||
handle.discovery.local_interfaces.lock().await[0]
|
||||
.config
|
||||
.reachable_on,
|
||||
None,
|
||||
"a configured peer is not our address"
|
||||
);
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Python's configured peers keep MODE_FULL and no announce-rate settings,
|
||||
/// and take only IFAC from their interface (I2PInterface.py:359-381); the
|
||||
/// interface's own settings apply to it alone (Reticulum.py:1030, :1059).
|
||||
#[tokio::test]
|
||||
async fn configured_i2p_peers_take_only_ifac_from_their_interface() {
|
||||
let (sam_port, _streams) = fake_sam(0).await;
|
||||
let peer = "peeraaaaaaaaaaaa.b32.i2p";
|
||||
let dir = config_dir(
|
||||
"i2p-peer-settings",
|
||||
&format!(
|
||||
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Golden I2P]]\n type = I2PInterface\n enabled = yes\n connectable = yes\n peers = {peer}\n mode = gateway\n announce_rate_target = 3600\n announce_cap = 5\n network_name = tunnelnet\n i2p_sam_host = 127.0.0.1\n i2p_sam_port = {sam_port}\n"
|
||||
),
|
||||
);
|
||||
let handle = start(&dir).await;
|
||||
let server = wait_for_interface(&handle, |entry| entry.name == "Golden I2P")
|
||||
.await
|
||||
.unwrap();
|
||||
let peer = wait_for_interface(&handle, |entry| {
|
||||
entry.name == format!("Golden I2P to {peer}")
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(server.mode.as_str(), server.announce_rate_target),
|
||||
("Gateway", Some(3600.0))
|
||||
);
|
||||
assert_eq!(
|
||||
(peer.mode.as_str(), peer.announce_rate_target),
|
||||
("Full", None)
|
||||
);
|
||||
assert_eq!(peer.announce_cap, ANNOUNCE_CAP);
|
||||
assert!(server.ifac_size > 0);
|
||||
assert_eq!(peer.ifac_size, server.ifac_size);
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn i2p_server_peers_register_under_their_server() {
|
||||
|
||||
Reference in new issue
Block a user