diff --git a/crates/rns-crypto/src/aes_cbc.rs b/crates/rns-crypto/src/aes_cbc.rs index da97b69..230abd3 100644 --- a/crates/rns-crypto/src/aes_cbc.rs +++ b/crates/rns-crypto/src/aes_cbc.rs @@ -34,7 +34,7 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result, AesCb if iv.len() != 16 { return Err(AesCbcError::InvalidIvLength(iv.len())); } - if plaintext.is_empty() || !plaintext.len().is_multiple_of(16) { + if plaintext.is_empty() || plaintext.len() % 16 != 0 { return Err(AesCbcError::NotBlockAligned); } @@ -68,7 +68,7 @@ pub fn decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result, AesC if iv.len() != 16 { return Err(AesCbcError::InvalidIvLength(iv.len())); } - if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) { + if ciphertext.is_empty() || ciphertext.len() % 16 != 0 { return Err(AesCbcError::NotBlockAligned); } diff --git a/crates/rns-crypto/src/token.rs b/crates/rns-crypto/src/token.rs index dd9a349..09626a5 100644 --- a/crates/rns-crypto/src/token.rs +++ b/crates/rns-crypto/src/token.rs @@ -85,7 +85,7 @@ pub fn decrypt(token: &[u8], key: &[u8]) -> Result, TokenError> { let iv = &signed_parts[..16]; let ciphertext = &signed_parts[16..]; - if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) { + if ciphertext.is_empty() || ciphertext.len() % 16 != 0 { return Err(TokenError::AuthenticationFailed); } diff --git a/crates/rns-identity/src/announce.rs b/crates/rns-identity/src/announce.rs index ee96b95..eb8cf45 100644 --- a/crates/rns-identity/src/announce.rs +++ b/crates/rns-identity/src/announce.rs @@ -245,15 +245,15 @@ impl AnnounceData { // First-seen key binding: a valid signature on a different public key // for an already-known destination hash implies a collision attack. - if let Some(known_key) = known_public_key - && known_key != &self.public_key - { - tracing::error!( - dest = hex::encode(packet_dest_hash), - "announce has valid signature and destination hash, but public key \ - differs from already known key — possible hash collision attack, rejecting" - ); - return Err(AnnounceError::HashCollision); + if let Some(known_key) = known_public_key { + if known_key != &self.public_key { + tracing::error!( + dest = hex::encode(packet_dest_hash), + "announce has valid signature and destination hash, but public key \ + differs from already known key — possible hash collision attack, rejecting" + ); + return Err(AnnounceError::HashCollision); + } } Ok(identity) diff --git a/crates/rns-identity/src/destination.rs b/crates/rns-identity/src/destination.rs index e18e280..81aca35 100644 --- a/crates/rns-identity/src/destination.rs +++ b/crates/rns-identity/src/destination.rs @@ -491,10 +491,10 @@ impl Destination { let plaintext = self.decrypt(data, identity)?; - if packet_type == 0x00 - && let Some(ref cb) = self.packet_callback - { - cb(&plaintext, data); + if packet_type == 0x00 { + if let Some(ref cb) = self.packet_callback { + cb(&plaintext, data); + } } Ok(Some(plaintext)) @@ -581,10 +581,10 @@ impl Destination { self.path_responses .retain(|_, v| now <= v.timestamp + PR_TAG_WINDOW); - if let Some(tag_bytes) = tag - && let Some(cached) = self.path_responses.get(tag_bytes) - { - return Ok((cached.announce_data.clone(), ratchet.is_some())); + if let Some(tag_bytes) = tag { + if let Some(cached) = self.path_responses.get(tag_bytes) { + return Ok((cached.announce_data.clone(), ratchet.is_some())); + } } let effective_app_data = app_data diff --git a/crates/rns-identity/src/identity.rs b/crates/rns-identity/src/identity.rs index 9403af4..a0a2d05 100644 --- a/crates/rns-identity/src/identity.rs +++ b/crates/rns-identity/src/identity.rs @@ -233,10 +233,10 @@ impl Identity { let mut shared = ratchet_prv.exchange(&peer_pub); let derived_result = derive_key_64(&shared, &self.hash); shared.zeroize(); - if let Ok(derived) = derived_result - && let Ok(plaintext) = token::decrypt(ct, &derived) - { - return Ok(plaintext); + if let Ok(derived) = derived_result { + if let Ok(plaintext) = token::decrypt(ct, &derived) { + return Ok(plaintext); + } } } } diff --git a/crates/rns-identity/src/ifac.rs b/crates/rns-identity/src/ifac.rs index 3e33862..9357923 100644 --- a/crates/rns-identity/src/ifac.rs +++ b/crates/rns-identity/src/ifac.rs @@ -66,7 +66,7 @@ pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) { } fn hex_decode(s: &str) -> Option> { - if !s.len().is_multiple_of(2) { + if s.len() % 2 != 0 { return None; } (0..s.len()) diff --git a/crates/rns-identity/src/ratchet.rs b/crates/rns-identity/src/ratchet.rs index 6a3b7a4..0154611 100644 --- a/crates/rns-identity/src/ratchet.rs +++ b/crates/rns-identity/src/ratchet.rs @@ -386,10 +386,10 @@ impl ReceivedRatchetStore { /// Record `ratchet_pub` for `dest_hash`. Re-inserting the identical key is a no-op; /// any other value replaces the entry and is written to disk when backed. pub fn remember(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32]) { - if let Some(existing) = self.entries.get(&dest_hash) - && existing.ratchet_pub == ratchet_pub - { - return; + if let Some(existing) = self.entries.get(&dest_hash) { + if existing.ratchet_pub == ratchet_pub { + return; + } } let received = ReceivedRatchet::new(ratchet_pub); @@ -412,28 +412,28 @@ impl ReceivedRatchetStore { /// Return the current ratchet public key for `dest_hash`, loading from /// disk on miss. Yields `None` if the entry is expired or absent. pub fn get(&mut self, dest_hash: &[u8; 16]) -> Option<[u8; 32]> { - if !self.entries.contains_key(dest_hash) - && let Some(ref dir) = self.storage_dir - { - let hexhash = hex::encode(dest_hash); - let path = dir.join(&hexhash); - if path.exists() { - match ReceivedRatchet::load(&path) { - Ok(ratchet) => { - if !ratchet.is_expired() && ratchet.ratchet_pub.len() == 32 { - self.entries.insert(*dest_hash, ratchet); - } else { + if !self.entries.contains_key(dest_hash) { + if let Some(ref dir) = self.storage_dir { + let hexhash = hex::encode(dest_hash); + let path = dir.join(&hexhash); + if path.exists() { + match ReceivedRatchet::load(&path) { + Ok(ratchet) => { + if !ratchet.is_expired() && ratchet.ratchet_pub.len() == 32 { + self.entries.insert(*dest_hash, ratchet); + } else { + return None; + } + } + Err(e) => { + tracing::error!( + dest = hexhash, + error = %e, + "failed to load ratchet from disk" + ); return None; } } - Err(e) => { - tracing::error!( - dest = hexhash, - error = %e, - "failed to load ratchet from disk" - ); - return None; - } } } } diff --git a/crates/rns-interface/src/auto.rs b/crates/rns-interface/src/auto.rs index 6d32c4f..79c6101 100644 --- a/crates/rns-interface/src/auto.rs +++ b/crates/rns-interface/src/auto.rs @@ -450,10 +450,10 @@ fn iface_passes_filters( if ignored_devices.iter().any(|n| n == iface_name) { return false; } - if let Some(allowed) = devices - && !allowed.iter().any(|n| n == iface_name) - { - return false; + if let Some(allowed) = devices { + if !allowed.iter().any(|n| n == iface_name) { + return false; + } } true } @@ -494,19 +494,19 @@ fn get_link_local_addrs( if !iface_passes_filters(&iface.name, devices, ignored_devices) { continue; } - if let std::net::IpAddr::V6(addr) = iface.addr.ip() - && (addr.segments()[0] & 0xffc0) == 0xfe80 - { - let scope_id = iface_scope_id(&iface); - if scope_id == 0 { - tracing::warn!( - iface = %iface.name, - addr = %addr, - "skipping link-local: could not resolve scope id (would send on wrong NIC)" - ); - continue; + if let std::net::IpAddr::V6(addr) = iface.addr.ip() { + if (addr.segments()[0] & 0xffc0) == 0xfe80 { + let scope_id = iface_scope_id(&iface); + if scope_id == 0 { + tracing::warn!( + iface = %iface.name, + addr = %addr, + "skipping link-local: could not resolve scope id (would send on wrong NIC)" + ); + continue; + } + result.push((iface.name.clone(), addr, scope_id)); } - result.push((iface.name.clone(), addr, scope_id)); } } } diff --git a/crates/rns-interface/src/ble_central_apple.rs b/crates/rns-interface/src/ble_central_apple.rs index e96e512..a9ee6cf 100644 --- a/crates/rns-interface/src/ble_central_apple.rs +++ b/crates/rns-interface/src/ble_central_apple.rs @@ -256,16 +256,16 @@ pub async fn teardown_central() -> Result<(), String> { } fn finalize_stop() { - if let Some(lock) = POWERED_ON_TX.get() - && let Ok(mut g) = lock.lock() - { - *g = None; + if let Some(lock) = POWERED_ON_TX.get() { + if let Ok(mut g) = lock.lock() { + *g = None; + } } // Drop the discovery sender so receivers don't hang on recv. - if let Some(lock) = DISCOVERY_TX.get() - && let Ok(mut g) = lock.lock() - { - *g = None; + if let Some(lock) = DISCOVERY_TX.get() { + if let Ok(mut g) = lock.lock() { + *g = None; + } } apply_event(CentralEvent::ScanStopped); apply_event(CentralEvent::Reset); @@ -566,11 +566,12 @@ fn get_delegate_class() -> &'static AnyClass { // No sender means stop_scan raced us between the radio event // and this callback — drop silently. - if let Some(lock) = DISCOVERY_TX.get() - && let Ok(g) = lock.lock() - && let Some(tx) = g.as_ref() - { - let _ = tx.send(event); + if let Some(lock) = DISCOVERY_TX.get() { + if let Ok(g) = lock.lock() { + if let Some(tx) = g.as_ref() { + let _ = tx.send(event); + } + } } } diff --git a/crates/rns-interface/src/ble_central_apple_connect.rs b/crates/rns-interface/src/ble_central_apple_connect.rs index a565779..d7aa550 100644 --- a/crates/rns-interface/src/ble_central_apple_connect.rs +++ b/crates/rns-interface/src/ble_central_apple_connect.rs @@ -749,10 +749,10 @@ pub fn on_did_disconnect(address: &str, err: Option) { if let Some(peer) = removed { peer.online.store(false, Ordering::SeqCst); } - if let Ok(mut g) = online_flags().lock() - && let Some(flag) = g.remove(address) - { - flag.store(false, Ordering::SeqCst); + if let Ok(mut g) = online_flags().lock() { + if let Some(flag) = g.remove(address) { + flag.store(false, Ordering::SeqCst); + } } let classified = classify_disconnect_reason(err.as_deref()); diff --git a/crates/rns-interface/src/ble_peer.rs b/crates/rns-interface/src/ble_peer.rs index 34ada00..a7c6611 100644 --- a/crates/rns-interface/src/ble_peer.rs +++ b/crates/rns-interface/src/ble_peer.rs @@ -126,12 +126,12 @@ pub fn anti_loop_record(map: &AntiLoopMap, source: String, payload: &[u8]) { /// false iff `dest` is one of the peers `payload` arrived from. pub fn anti_loop_should_send(map: &AntiLoopMap, dest: &str, payload: &[u8]) -> bool { let h = payload_hash(payload); - if let Ok(g) = map.lock() - && let Some((srcs, t)) = g.get(&h) - && t.elapsed() < ANTI_LOOP_TTL - && srcs.contains(dest) - { - return false; + if let Ok(g) = map.lock() { + if let Some((srcs, t)) = g.get(&h) { + if t.elapsed() < ANTI_LOOP_TTL && srcs.contains(dest) { + return false; + } + } } true } @@ -143,10 +143,11 @@ pub fn anti_loop_prune(map: &AntiLoopMap) { } fn reconnect_in_backoff(map: &RecentlyDisconnected, identity_hex: &str) -> bool { - if let Ok(guard) = map.lock() - && let Some((when, fails)) = guard.get(identity_hex) - { - return *fails >= RECONNECT_BACKOFF_FAILURES && when.elapsed() < RECONNECT_BACKOFF_DURATION; + if let Ok(guard) = map.lock() { + if let Some((when, fails)) = guard.get(identity_hex) { + return *fails >= RECONNECT_BACKOFF_FAILURES + && when.elapsed() < RECONNECT_BACKOFF_DURATION; + } } false } @@ -372,14 +373,15 @@ pub fn clear_event_dispatcher() { /// can happen during burst events. Log so we see it instead of state silently /// going stale (e.g. UI stuck "Scanning…" because a Connected was dropped). pub(crate) fn dispatch_event(event: BlePeerEvent) { - if let Ok(slot) = event_dispatch_slot().read() - && let Some(tx) = slot.as_ref() - && let Err(e) = tx.try_send(event) - { - tracing::warn!( - error = %e, - "BLE peer event dispatch dropped — relay channel full or closed" - ); + if let Ok(slot) = event_dispatch_slot().read() { + if let Some(tx) = slot.as_ref() { + if let Err(e) = tx.try_send(event) { + tracing::warn!( + error = %e, + "BLE peer event dispatch dropped — relay channel full or closed" + ); + } + } } } @@ -1642,10 +1644,10 @@ mod apple_peripheral { let char_uuid = uuid_for_characteristic(characteristic); let all_gone = { let mut chars_map = central_subscribed_chars_map().lock().unwrap(); - if let Some(u) = char_uuid - && let Some(set) = chars_map.get_mut(&id) - { - set.remove(&u); + if let Some(u) = char_uuid { + if let Some(set) = chars_map.get_mut(&id) { + set.remove(&u); + } } let empty = chars_map.get(&id).is_none_or(|s| s.is_empty()); if empty { @@ -1879,17 +1881,19 @@ mod apple_peripheral { /// replayed coherently without per-central addressing, so they don't. pub fn notify_tx(to_peer: Option<&str>, char_uuid: Uuid, data: &[u8]) -> bool { let ok = notify_tx_inner(to_peer, char_uuid, data); - if !ok && let Some(peer_id) = to_peer { - let mut q = pending_notify_queue().lock().unwrap(); - if q.len() >= PENDING_NOTIFY_CAP { - q.pop_front(); + if !ok { + if let Some(peer_id) = to_peer { + let mut q = pending_notify_queue().lock().unwrap(); + if q.len() >= PENDING_NOTIFY_CAP { + q.pop_front(); + } + q.push_back(PendingNotify { + peer: peer_id.to_string(), + char_uuid, + data: data.to_vec(), + }); + tracing::warn!(%char_uuid, bytes = data.len(), peer = %peer_id, depth = q.len(), "Apple BLE notify_tx: queued for retry (radio queue full)"); } - q.push_back(PendingNotify { - peer: peer_id.to_string(), - char_uuid, - data: data.to_vec(), - }); - tracing::warn!(%char_uuid, bytes = data.len(), peer = %peer_id, depth = q.len(), "Apple BLE notify_tx: queued for retry (radio queue full)"); } ok } @@ -2362,10 +2366,10 @@ mod apple_peripheral { // OnceLock can't be cleared, but the inner Mutex lets us // null the pointer so notify_tx + the next start cycle see no manager. - if let Some(lock) = MANAGER_PTR.get() - && let Ok(mut guard) = lock.lock() - { - *guard = SendPtr(std::ptr::null_mut()); + if let Some(lock) = MANAGER_PTR.get() { + if let Ok(mut guard) = lock.lock() { + *guard = SendPtr(std::ptr::null_mut()); + } } // Any queued retries reference characteristics we just released; @@ -3498,21 +3502,21 @@ mod linux_peripheral { let char_uuid = rx_uuid_for_trace; let byte_len = new_value.len(); Box::pin(async move { - if let Some(tx) = INBOUND_TX.get() - && let Err(e) = tx.try_send((addr.clone(), new_value)) - { - // Channel full — log so operators see the - // backpressure signal instead of finding - // silent fragment loss. - tracing::warn!( - target: "ble_trace", - step = "linux_rx.channel_full", - peer = %addr, - %char_uuid, - bytes = byte_len, - err = %e, - "Linux BLE RX: inbound channel full, dropping frame" - ); + if let Some(tx) = INBOUND_TX.get() { + if let Err(e) = tx.try_send((addr.clone(), new_value)) { + // Channel full — log so operators see the + // backpressure signal instead of finding + // silent fragment loss. + tracing::warn!( + target: "ble_trace", + step = "linux_rx.channel_full", + peer = %addr, + %char_uuid, + bytes = byte_len, + err = %e, + "Linux BLE RX: inbound channel full, dropping frame" + ); + } } Ok(()) }) @@ -4533,7 +4537,7 @@ async fn peer_write_loop( } } tx_count += 1; - if tx_count.is_multiple_of(5) { + if tx_count % 5 == 0 { tracing::info!( target: "ble_trace", step = "peer.tx_progress", @@ -4710,17 +4714,19 @@ pub async fn spawn_ble_peer_interface( // caller-side deduplication. Cheap: parses header only, // doesn't validate the announce // signature (transport will do that). - if !identity_announced.contains(&peer) - && let Ok(parsed) = &parse_result - && parsed.header.flags.packet_type - == rns_wire::flags::PacketType::Announce - { - let id_hex = hex::encode(parsed.header.destination_hash); - identity_announced.insert(peer.clone()); - dispatch_event(BlePeerEvent::IdentityResolved { - address: peer.clone(), - identity_hash: id_hex, - }); + if !identity_announced.contains(&peer) { + if let Ok(parsed) = &parse_result { + if parsed.header.flags.packet_type + == rns_wire::flags::PacketType::Announce + { + let id_hex = hex::encode(parsed.header.destination_hash); + identity_announced.insert(peer.clone()); + dispatch_event(BlePeerEvent::IdentityResolved { + address: peer.clone(), + identity_hash: id_hex, + }); + } + } } // Record this packet's source so the outbound // fan-out can skip echoing it back to the same peer. @@ -5374,7 +5380,7 @@ pub async fn spawn_ble_peer_interface( break; } tx_count += 1; - if tx_count.is_multiple_of(5) { + if tx_count % 5 == 0 { tracing::info!( target: "ble_trace", step = "peer.tx_progress", diff --git a/crates/rns-interface/src/ble_rnode.rs b/crates/rns-interface/src/ble_rnode.rs index dae5603..10aad3c 100644 --- a/crates/rns-interface/src/ble_rnode.rs +++ b/crates/rns-interface/src/ble_rnode.rs @@ -78,12 +78,12 @@ fn unregister_running(id: InterfaceId) { /// Idempotent. Safe to call before or after deregistering from the /// transport actor. pub fn stop_ble_rnode_interface(id: InterfaceId) { - if let Ok(map) = running_map().lock() - && let Some(flag) = map.get(&id) - { - flag.store(false, Ordering::SeqCst); - tracing::info!(id, "BLE RNode: stop signal sent"); - ble_diag(format!("[ble] stop_ble_rnode_interface({id})")); + if let Ok(map) = running_map().lock() { + if let Some(flag) = map.get(&id) { + flag.store(false, Ordering::SeqCst); + tracing::info!(id, "BLE RNode: stop signal sent"); + ble_diag(format!("[ble] stop_ble_rnode_interface({id})")); + } } } @@ -254,14 +254,14 @@ static LINUX_PAIRING_ATTEMPT_COUNTER: std::sync::atomic::AtomicU64 = /// `false` if no pairing is in flight or the attempt was aborted. #[cfg(target_os = "linux")] pub fn linux_submit_passkey(passkey: u32) -> bool { - if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() - && let Some(state) = guard.as_mut() - { - if state.aborted { - return false; - } - if let Some(tx) = state.passkey_tx.take() { - return tx.send(passkey).is_ok(); + if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() { + if let Some(state) = guard.as_mut() { + if state.aborted { + return false; + } + if let Some(tx) = state.passkey_tx.take() { + return tx.send(passkey).is_ok(); + } } } false @@ -530,11 +530,12 @@ async fn resolve_ble_target( } // A populated list without NUS means a different device; // only fall back to the name on empty service lists. - if props.services.is_empty() - && let Some(ref name) = props.local_name - && name.starts_with("RNode ") - { - return Ok(p.clone()); + if props.services.is_empty() { + if let Some(ref name) = props.local_name { + if name.starts_with("RNode ") { + return Ok(p.clone()); + } + } } } } @@ -555,12 +556,13 @@ async fn resolve_ble_target( // Fallback for UIs that pass a friendly name instead of platform id. for p in &peripherals { - if let Ok(Some(props)) = p.properties().await - && let Some(ref name) = props.local_name - && name == target - { - ble_diag(format!("[ble] resolve matched by name: {name}")); - return Ok(p.clone()); + if let Ok(Some(props)) = p.properties().await { + if let Some(ref name) = props.local_name { + if name == target { + ble_diag(format!("[ble] resolve matched by name: {name}")); + return Ok(p.clone()); + } + } } } @@ -864,15 +866,15 @@ fn parse_linux_ble_address(addr: &str) -> Result if let Ok(parsed) = addr.parse::() { return Ok(parsed); } - if let Some(tail) = addr.rsplit('/').next() - && let Some(mac_part) = tail.strip_prefix("dev_") - { - let mac = mac_part.replace('_', ":"); - return mac.parse::().map_err(|e| { - InterfaceError::SendFailed(format!( - "invalid BLE address (BlueZ path '{addr}' → '{mac}'): {e}" - )) - }); + if let Some(tail) = addr.rsplit('/').next() { + if let Some(mac_part) = tail.strip_prefix("dev_") { + let mac = mac_part.replace('_', ":"); + return mac.parse::().map_err(|e| { + InterfaceError::SendFailed(format!( + "invalid BLE address (BlueZ path '{addr}' → '{mac}'): {e}" + )) + }); + } } Err(InterfaceError::SendFailed(format!( "invalid BLE address {addr}: not a MAC nor a BlueZ D-Bus path" @@ -1038,11 +1040,13 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa Ok(()) => "ok".to_string(), Err(e) => format!("{e}"), }; - if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() - && let Some(state) = guard.as_ref() - && state.attempt_id == attempt_id - { - *guard = None; + if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() { + if guard + .as_ref() + .is_some_and(|state| state.attempt_id == attempt_id) + { + *guard = None; + } } let _ = linux_pairing_finished_sender().send(LinuxPairingFinished { attempt_id, status }); outcome diff --git a/crates/rns-interface/src/local.rs b/crates/rns-interface/src/local.rs index da27c9a..a48119a 100644 --- a/crates/rns-interface/src/local.rs +++ b/crates/rns-interface/src/local.rs @@ -19,10 +19,10 @@ pub const DEFAULT_SOCKET_PATH: &str = "/tmp/rns_reticulum.sock"; /// On Android `/tmp` isn't writable; falls back to caller's data directory. pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf { - if cfg!(target_os = "android") - && let Some(dir) = data_dir - { - return dir.join("cache").join("rns_reticulum.sock"); + if cfg!(target_os = "android") { + if let Some(dir) = data_dir { + return dir.join("cache").join("rns_reticulum.sock"); + } } std::path::PathBuf::from(DEFAULT_SOCKET_PATH) } diff --git a/crates/rns-interface/src/rnode_multi.rs b/crates/rns-interface/src/rnode_multi.rs index 0931b58..f4af53b 100644 --- a/crates/rns-interface/src/rnode_multi.rs +++ b/crates/rns-interface/src/rnode_multi.rs @@ -142,21 +142,21 @@ impl SubInterfaceConfig { self.coding_rate, self.name )); } - if let Some(st) = self.st_alock - && (!(0.0..=100.0).contains(&st)) - { - return Err(format!( - "Invalid short-term airtime limit {} for sub-interface {}", - st, self.name - )); + if let Some(st) = self.st_alock { + if !(0.0..=100.0).contains(&st) { + return Err(format!( + "Invalid short-term airtime limit {} for sub-interface {}", + st, self.name + )); + } } - if let Some(lt) = self.lt_alock - && (!(0.0..=100.0).contains(<)) - { - return Err(format!( - "Invalid long-term airtime limit {} for sub-interface {}", - lt, self.name - )); + if let Some(lt) = self.lt_alock { + if !(0.0..=100.0).contains(<) { + return Err(format!( + "Invalid long-term airtime limit {} for sub-interface {}", + lt, self.name + )); + } } if self.vport as usize > MAX_SUBINTERFACES { return Err(format!( diff --git a/crates/rns-interface/src/socket_tuning.rs b/crates/rns-interface/src/socket_tuning.rs index 5b68959..a9a6e2c 100644 --- a/crates/rns-interface/src/socket_tuning.rs +++ b/crates/rns-interface/src/socket_tuning.rs @@ -183,21 +183,21 @@ mod tests { let candidates = ["lo", "lo0", "Loopback Pseudo-Interface 1"]; let mut found_v4 = false; for name in candidates { - if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false) - && v4.is_loopback() - { - found_v4 = true; - break; + if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false) { + if v4.is_loopback() { + found_v4 = true; + break; + } } } // Hermetic CI may not expose loopback by name; only assert when seen. - if let Ok(ifaces) = if_addrs::get_if_addrs() - && ifaces.iter().any(|i| candidates.contains(&i.name.as_str())) - { - assert!( - found_v4, - "expected a loopback IPv4 on one of {candidates:?}" - ); + if let Ok(ifaces) = if_addrs::get_if_addrs() { + if ifaces.iter().any(|i| candidates.contains(&i.name.as_str())) { + assert!( + found_v4, + "expected a loopback IPv4 on one of {candidates:?}" + ); + } } } diff --git a/crates/rns-link/src/keepalive.rs b/crates/rns-link/src/keepalive.rs index 63581e8..23d9b6e 100644 --- a/crates/rns-link/src/keepalive.rs +++ b/crates/rns-link/src/keepalive.rs @@ -112,20 +112,20 @@ impl KeepaliveState { /// link that just came up isn't immediately flagged stale on a quiet channel. pub fn is_stale(&self) -> bool { let mut latest = self.last_inbound; - if let Some(proof) = self.last_proof - && proof > latest - { - latest = proof; + if let Some(proof) = self.last_proof { + if proof > latest { + latest = proof; + } } - if let Some(outbound) = self.last_outbound - && outbound > latest - { - latest = outbound; + if let Some(outbound) = self.last_outbound { + if outbound > latest { + latest = outbound; + } } - if let Some(activated) = self.activated_at - && activated > latest - { - latest = activated; + if let Some(activated) = self.activated_at { + if activated > latest { + latest = activated; + } } latest.elapsed() >= self.stale_time } diff --git a/crates/rns-link/src/link.rs b/crates/rns-link/src/link.rs index f2ab482..16ac720 100644 --- a/crates/rns-link/src/link.rs +++ b/crates/rns-link/src/link.rs @@ -484,14 +484,14 @@ impl Link { .map_err(|_| HandshakeError::InvalidSignature)?; // RTT is a msgpack f64 — see matching encode in validate_proof(). - if let Ok(value) = rmpv::decode::read_value(&mut &plaintext[..]) - && let Some(peer_rtt) = value.as_f64() - { - let local_rtt = self.request_time.elapsed().as_secs_f64(); - let rtt = local_rtt.max(peer_rtt); - let rtt_dur = Duration::from_secs_f64(rtt); - self.rtt = Some(rtt_dur); - self.keepalive.update_from_rtt(rtt_dur); + if let Ok(value) = rmpv::decode::read_value(&mut &plaintext[..]) { + if let Some(peer_rtt) = value.as_f64() { + let local_rtt = self.request_time.elapsed().as_secs_f64(); + let rtt = local_rtt.max(peer_rtt); + let rtt_dur = Duration::from_secs_f64(rtt); + self.rtt = Some(rtt_dur); + self.keepalive.update_from_rtt(rtt_dur); + } } self.state = LinkState::Active; @@ -1083,12 +1083,12 @@ impl Link { // otherwise we'd have nothing to sign the teardown with. let rtt = self.rtt.unwrap_or(Duration::from_secs(1)); let grace = self.keepalive.stale_grace_timeout(rtt); - if let Some(stale_since) = self.stale_since - && stale_since.elapsed() >= grace - { - let teardown_data = self.encrypt(&self.link_id).unwrap_or_default(); - self.close(CloseReason::Timeout); - return LinkAction::SendTeardownAndClose(teardown_data); + if let Some(stale_since) = self.stale_since { + if stale_since.elapsed() >= grace { + let teardown_data = self.encrypt(&self.link_id).unwrap_or_default(); + self.close(CloseReason::Timeout); + return LinkAction::SendTeardownAndClose(teardown_data); + } } LinkAction::None } diff --git a/crates/rns-protocol/src/buffer.rs b/crates/rns-protocol/src/buffer.rs index 15252c1..0a1131c 100644 --- a/crates/rns-protocol/src/buffer.rs +++ b/crates/rns-protocol/src/buffer.rs @@ -154,11 +154,10 @@ impl StreamWriter { if segment_len <= 32 { break; } - if let Ok(compressed) = compression::bz2_compress(&chunk[..segment_len]) - && compressed.len() < self.max_data_len - && compressed.len() < segment_len - { - return (compressed, segment_len, true); + if let Ok(compressed) = compression::bz2_compress(&chunk[..segment_len]) { + if compressed.len() < self.max_data_len && compressed.len() < segment_len { + return (compressed, segment_len, true); + } } } diff --git a/crates/rns-protocol/src/resource.rs b/crates/rns-protocol/src/resource.rs index 28a5ac6..61fdbd4 100644 --- a/crates/rns-protocol/src/resource.rs +++ b/crates/rns-protocol/src/resource.rs @@ -1545,10 +1545,11 @@ impl OutboundTransfer { for i in search_start..search_end { if i < self.resource.map_hashes.len() && requested_map_hashes.contains(&self.resource.map_hashes[i]) - && let Some(part_data) = self.resource.get_part(i) { - actions.push(TransferAction::SendPart(i, part_data.to_vec())); - sent_count += 1; + if let Some(part_data) = self.resource.get_part(i) { + actions.push(TransferAction::SendPart(i, part_data.to_vec())); + sent_count += 1; + } } } @@ -1582,7 +1583,7 @@ impl OutboundTransfer { // Python cancels if an exhausted request cursor is not aligned to // a hashmap segment boundary. - if hashmap_max_len > 0 && !part_index.is_multiple_of(hashmap_max_len) { + if hashmap_max_len > 0 && part_index % hashmap_max_len != 0 { self.resource.state = ResourceState::Failed; actions.push(TransferAction::SendCancel( CancelType::Icl, @@ -2146,8 +2147,10 @@ impl InboundTransfer { hmu.push(exhausted); // If exhausted (complete), include the last map hash - if is_complete && let Some(last_mh) = self.resource.map_hashes.last() { - hmu.extend_from_slice(last_mh); + if is_complete { + if let Some(last_mh) = self.resource.map_hashes.last() { + hmu.extend_from_slice(last_mh); + } } // Include the resource hash for identification diff --git a/crates/rns-protocol/src/rnsh.rs b/crates/rns-protocol/src/rnsh.rs index 9d13728..a386319 100644 --- a/crates/rns-protocol/src/rnsh.rs +++ b/crates/rns-protocol/src/rnsh.rs @@ -552,10 +552,10 @@ fn value_to_u64(value: &Value, field: &'static str) -> Result= 0 - { - return Ok(number as u64); + if let Some(number) = value.as_i64() { + if number >= 0 { + return Ok(number as u64); + } } Err(RnshCodecError::InvalidShape(field)) } @@ -564,10 +564,10 @@ fn value_to_i64(value: &Value, field: &'static str) -> Result Result<(), } fn hex_decode(s: &str) -> Option> { - if !s.len().is_multiple_of(2) { + if s.len() % 2 != 0 { return None; } (0..s.len()) diff --git a/crates/rns-runtime/src/interface_factory.rs b/crates/rns-runtime/src/interface_factory.rs index 28800d7..b44d4f2 100644 --- a/crates/rns-runtime/src/interface_factory.rs +++ b/crates/rns-runtime/src/interface_factory.rs @@ -865,21 +865,21 @@ fn validate_rnode_multi_subinterface( message: format!("{} is outside 5..=8", sub.coding_rate), }); } - if let Some(v) = sub.st_alock - && !(0.0..=100.0).contains(&v) - { - return Err(InterfaceFactoryError::InvalidValue { - field: format!("{}.airtime_limit_short", sub.name), - message: format!("{v} is outside 0..=100 percent"), - }); + if let Some(v) = sub.st_alock { + if !(0.0..=100.0).contains(&v) { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.airtime_limit_short", sub.name), + message: format!("{v} is outside 0..=100 percent"), + }); + } } - if let Some(v) = sub.lt_alock - && !(0.0..=100.0).contains(&v) - { - return Err(InterfaceFactoryError::InvalidValue { - field: format!("{}.airtime_limit_long", sub.name), - message: format!("{v} is outside 0..=100 percent"), - }); + if let Some(v) = sub.lt_alock { + if !(0.0..=100.0).contains(&v) { + return Err(InterfaceFactoryError::InvalidValue { + field: format!("{}.airtime_limit_long", sub.name), + message: format!("{v} is outside 0..=100 percent"), + }); + } } if sub.frequency == 0 { return Err(InterfaceFactoryError::InvalidValue { diff --git a/crates/rns-runtime/src/link_client.rs b/crates/rns-runtime/src/link_client.rs index b89bde2..8ea0c31 100644 --- a/crates/rns-runtime/src/link_client.rs +++ b/crates/rns-runtime/src/link_client.rs @@ -231,10 +231,10 @@ async fn wait_for_pubkey( ) -> Result<[u8; 64], LinkClientError> { let fut = async { while let Some(ev) = rx.recv().await { - if ev.destination_hash == target_dest_hash - && let Some(pk) = ev.public_key - { - return Ok(pk); + if ev.destination_hash == target_dest_hash { + if let Some(pk) = ev.public_key { + return Ok(pk); + } } } Err(LinkClientError::PubkeyNotDiscovered) diff --git a/crates/rns-runtime/src/link_manager.rs b/crates/rns-runtime/src/link_manager.rs index f48c50b..c823af2 100644 --- a/crates/rns-runtime/src/link_manager.rs +++ b/crates/rns-runtime/src/link_manager.rs @@ -476,11 +476,11 @@ impl LinkManager { let hops = header.hops; - if let Some(ref dest) = self.destination - && !dest.accept_link_requests - { - tracing::debug!("link request rejected — destination not accepting links"); - return; + if let Some(ref dest) = self.destination { + if !dest.accept_link_requests { + tracing::debug!("link request rejected — destination not accepting links"); + return; + } } let (link, proof_data) = @@ -620,33 +620,33 @@ impl LinkManager { match header.context { rns_wire::context::PacketContext::Lrrtt => { - if let Some(active) = self.active_links.get_mut(&link_id) - && active.link.state == LinkState::Handshake - { - match active.link.receive_rtt_packet(data) { - Ok(()) => { - tracing::info!( - link_id = hex::encode(link_id), - rtt_ms = active.link.rtt.map(|r| r.as_millis()).unwrap_or(0), - "link activated via LRRTT" - ); + if let Some(active) = self.active_links.get_mut(&link_id) { + if active.link.state == LinkState::Handshake { + match active.link.receive_rtt_packet(data) { + Ok(()) => { + tracing::info!( + link_id = hex::encode(link_id), + rtt_ms = active.link.rtt.map(|r| r.as_millis()).unwrap_or(0), + "link activated via LRRTT" + ); - if let Some(ref cb) = active.link.link_established_callback { - cb(&active.link); + if let Some(ref cb) = active.link.link_established_callback { + cb(&active.link); + } + if let Some(ref dest) = self.destination { + dest.on_link_established(link_id); + } + if let Some(ref tx) = self.link_established_tx { + let _ = tx.try_send(link_id); + } } - if let Some(ref dest) = self.destination { - dest.on_link_established(link_id); + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + error = %e, + "LRRTT processing failed" + ); } - if let Some(ref tx) = self.link_established_tx { - let _ = tx.try_send(link_id); - } - } - Err(e) => { - tracing::warn!( - link_id = hex::encode(link_id), - error = %e, - "LRRTT processing failed" - ); } } } @@ -886,32 +886,34 @@ impl LinkManager { // Python Resource.accept → request_next: initial request // accepts the ADV and names the parts. let action = transfer.request_next(); - if let TransferAction::SendRequest(req_data) = action - && let Ok(encrypted) = active.link.encrypt(&req_data) - { - let req_header = rns_wire::header::PacketHeader { - flags: rns_wire::flags::PacketFlags { - header_type: rns_wire::flags::HeaderType::Header1, - context_flag: false, - transport_type: - rns_wire::flags::TransportType::Broadcast, - destination_type: - rns_wire::flags::DestinationType::Link, - packet_type: rns_wire::flags::PacketType::Data, - }, - hops: 0, - transport_id: None, - destination_hash: link_id, - context: rns_wire::context::PacketContext::ResourceReq, - }; - let mut req_raw = req_header.pack(); - req_raw.extend_from_slice(&encrypted); - let _ = self.transport_tx.try_send( - TransportMessage::Outbound(OutboundRequest { - raw: Bytes::from(req_raw), + if let TransferAction::SendRequest(req_data) = action { + if let Ok(encrypted) = active.link.encrypt(&req_data) { + let req_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: + rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: + rns_wire::flags::TransportType::Broadcast, + destination_type: + rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, destination_hash: link_id, - }), - ); + context: + rns_wire::context::PacketContext::ResourceReq, + }; + let mut req_raw = req_header.pack(); + req_raw.extend_from_slice(&encrypted); + let _ = self.transport_tx.try_send( + TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(req_raw), + destination_hash: link_id, + }), + ); + } } active.link.track_incoming_resource(adv.resource_hash); @@ -1021,94 +1023,58 @@ impl LinkManager { }) }; - if let Some(transfer) = active.inbound_resources.get_mut(&rh) - && let Ok((assembled_data, proof)) = + if let Some(transfer) = active.inbound_resources.get_mut(&rh) { + if let Ok((assembled_data, proof)) = transfer.complete(Some(&decrypt_fn)) - { - // PROOF+RESOURCE_PRF = plaintext, PacketType::Proof - // (Packet.py:195-197). Each split segment still needs its - // own proof or the sender retries. - let prf_header = rns_wire::header::PacketHeader { - flags: rns_wire::flags::PacketFlags { - header_type: rns_wire::flags::HeaderType::Header1, - context_flag: false, - transport_type: rns_wire::flags::TransportType::Broadcast, - destination_type: rns_wire::flags::DestinationType::Link, - packet_type: rns_wire::flags::PacketType::Proof, - }, - hops: 0, - transport_id: None, - destination_hash: link_id, - context: rns_wire::context::PacketContext::ResourcePrf, - }; - let mut prf_raw = prf_header.pack(); - prf_raw.extend_from_slice(&proof); - active.link.record_tx(prf_raw.len()); - let _ = self.transport_tx.try_send(TransportMessage::Outbound( - OutboundRequest { - raw: Bytes::from(prf_raw), + { + // PROOF+RESOURCE_PRF = plaintext, PacketType::Proof + // (Packet.py:195-197). Each split segment still needs its + // own proof or the sender retries. + let prf_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: + rns_wire::flags::TransportType::Broadcast, + destination_type: + rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Proof, + }, + hops: 0, + transport_id: None, destination_hash: link_id, - }, - )); + context: rns_wire::context::PacketContext::ResourcePrf, + }; + let mut prf_raw = prf_header.pack(); + prf_raw.extend_from_slice(&proof); + active.link.record_tx(prf_raw.len()); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(prf_raw), + destination_hash: link_id, + }, + )); - // Split resources route to a coordinator keyed by - // `original_hash`; completion fires only on full reassembly. - if let Some(route) = active.segment_routing.remove(&rh) { - let seg_meta = active - .inbound_resources - .get(&rh) - .and_then(|t| t.resource.metadata.clone()); + // Split resources route to a coordinator keyed by + // `original_hash`; completion fires only on full reassembly. + if let Some(route) = active.segment_routing.remove(&rh) { + let seg_meta = active + .inbound_resources + .get(&rh) + .and_then(|t| t.resource.metadata.clone()); - if let Some(coord) = - active.inbound_split_resources.get_mut(&route.original_hash) - { - match coord - .set_segment_data(route.segment_index, assembled_data) + if let Some(coord) = active + .inbound_split_resources + .get_mut(&route.original_hash) { - Ok(()) => { - if let Some(meta) = seg_meta { - coord.set_metadata(meta); - } - } - Err(e) => { - tracing::warn!( - link_id = hex::encode(link_id), - original = hex::encode( - &route.original_hash[..8] - ), - segment = route.segment_index, - error = ?e, - "split-resource coordinator rejected segment" - ); - } - } - - if coord.is_complete() { - match coord.reassemble() { - Ok(blob) => { - let metadata = coord.metadata.take(); - let total_segments = coord.total_segments; - if let Some(ref tx) = - self.resource_completion_tx - { - let _ = tx.try_send(ResourceCompletion { - link_id, - resource_hash: route.original_hash, - data: blob.clone(), - metadata, - }); + match coord.set_segment_data( + route.segment_index, + assembled_data, + ) { + Ok(()) => { + if let Some(meta) = seg_meta { + coord.set_metadata(meta); } - if let Some(ref tx) = self.resource_completed_tx - { - let _ = tx.try_send((blob, link_id)); - } - tracing::info!( - link_id = hex::encode(link_id), - original = - hex::encode(&route.original_hash[..8]), - total_segments, - "split-resource reassembly complete" - ); } Err(e) => { tracing::warn!( @@ -1116,56 +1082,102 @@ impl LinkManager { original = hex::encode( &route.original_hash[..8] ), + segment = route.segment_index, error = ?e, - "split-resource reassembly failed" + "split-resource coordinator rejected segment" ); } } - active - .inbound_split_resources - .remove(&route.original_hash); + + if coord.is_complete() { + match coord.reassemble() { + Ok(blob) => { + let metadata = coord.metadata.take(); + let total_segments = coord.total_segments; + if let Some(ref tx) = + self.resource_completion_tx + { + let _ = + tx.try_send(ResourceCompletion { + link_id, + resource_hash: route + .original_hash, + data: blob.clone(), + metadata, + }); + } + if let Some(ref tx) = + self.resource_completed_tx + { + let _ = tx.try_send((blob, link_id)); + } + tracing::info!( + link_id = hex::encode(link_id), + original = hex::encode( + &route.original_hash[..8] + ), + total_segments, + "split-resource reassembly complete" + ); + } + Err(e) => { + tracing::warn!( + link_id = hex::encode(link_id), + original = hex::encode( + &route.original_hash[..8] + ), + error = ?e, + "split-resource reassembly failed" + ); + } + } + active + .inbound_split_resources + .remove(&route.original_hash); + } else { + tracing::debug!( + link_id = hex::encode(link_id), + original = + hex::encode(&route.original_hash[..8]), + segment = route.segment_index, + progress = coord.assembled_count(), + total = coord.total_segments, + "split-resource segment received — awaiting more" + ); + } } else { - tracing::debug!( + tracing::warn!( link_id = hex::encode(link_id), original = hex::encode(&route.original_hash[..8]), - segment = route.segment_index, - progress = coord.assembled_count(), - total = coord.total_segments, - "split-resource segment received — awaiting more" + "split-resource coordinator missing for completed segment" ); } } else { - tracing::warn!( + // Single-segment path: rncp channel keeps metadata + + // resource hash; the legacy LXMF channel drops both. + if let Some(ref tx) = self.resource_completion_tx { + let metadata = active + .inbound_resources + .get(&rh) + .and_then(|t| t.resource.metadata.clone()); + let _ = tx.try_send(ResourceCompletion { + link_id, + resource_hash: rh, + data: assembled_data.clone(), + metadata, + }); + } + + if let Some(ref tx) = self.resource_completed_tx { + let _ = tx.try_send((assembled_data, link_id)); + } + + tracing::debug!( link_id = hex::encode(link_id), - original = hex::encode(&route.original_hash[..8]), - "split-resource coordinator missing for completed segment" + resource = hex::encode(&rh[..8]), + "inbound resource transfer completed — proof sent" ); } - } else { - // Single-segment path: rncp channel keeps metadata + - // resource hash; the legacy LXMF channel drops both. - if let Some(ref tx) = self.resource_completion_tx { - let metadata = active - .inbound_resources - .get(&rh) - .and_then(|t| t.resource.metadata.clone()); - let _ = tx.try_send(ResourceCompletion { - link_id, - resource_hash: rh, - data: assembled_data.clone(), - metadata, - }); - } - - if let Some(ref tx) = self.resource_completed_tx { - let _ = tx.try_send((assembled_data, link_id)); - } - - tracing::debug!( - link_id = hex::encode(link_id), - resource = hex::encode(&rh[..8]), - "inbound resource transfer completed — proof sent" - ); } } active.link.untrack_resource(&rh); @@ -1178,100 +1190,102 @@ impl LinkManager { // Receiver's HMU for outbound transfer (Link.py:1104-1124). if let Some(active) = self.active_links.get_mut(&link_id) { active.link.record_inbound(); - if let Ok(plaintext) = active.link.decrypt(data) - && plaintext.len() > 32 - { - // Exhaustion flag shifts the resource hash by MAPHASH_LEN. - let resource_hash_start = - if plaintext[0] == rns_protocol::resource::HASHMAP_IS_EXHAUSTED { - 1 + rns_protocol::resource::MAPHASH_LEN - } else { - 1 - }; - if plaintext.len() >= resource_hash_start + 32 { - let mut rh = [0u8; 32]; - rh.copy_from_slice( - &plaintext[resource_hash_start..resource_hash_start + 32], - ); - let packet_hash = - rns_wire::hash::packet_hash(raw, header.flags.header_type); - let actions = active - .outbound_resources - .get_mut(&rh) - .map(|transfer| { - transfer.handle_request_packet(packet_hash, &plaintext) - }) - .unwrap_or_default(); - for action in actions { - let (context, body) = match action { - TransferAction::SendPart(idx, part_data) => { - tracing::trace!( - link_id = hex::encode(link_id), - part = idx, - "sent resource part (request response)" - ); - ( - rns_wire::context::PacketContext::Resource, - Bytes::from(part_data), - ) - } - TransferAction::SendHmu(hmu) => { - let Ok(encrypted) = active.link.encrypt(&hmu) else { - continue; - }; - ( - rns_wire::context::PacketContext::ResourceHmu, - Bytes::from(encrypted), - ) - } - TransferAction::SendRequest(req) => { - let Ok(encrypted) = active.link.encrypt(&req) else { - continue; - }; - ( - rns_wire::context::PacketContext::ResourceReq, - Bytes::from(encrypted), - ) - } - TransferAction::SendCancel(cancel_type, resource_hash) => { - let Ok(encrypted) = active.link.encrypt(&resource_hash) - else { - continue; - }; - let context = match cancel_type { - rns_protocol::resource::CancelType::Icl => { - rns_wire::context::PacketContext::ResourceIcl - } - rns_protocol::resource::CancelType::Rcl => { - rns_wire::context::PacketContext::ResourceRcl - } - }; - (context, Bytes::from(encrypted)) - } - _ => continue, + if let Ok(plaintext) = active.link.decrypt(data) { + if plaintext.len() > 32 { + // Exhaustion flag shifts the resource hash by MAPHASH_LEN. + let resource_hash_start = + if plaintext[0] == rns_protocol::resource::HASHMAP_IS_EXHAUSTED { + 1 + rns_protocol::resource::MAPHASH_LEN + } else { + 1 }; - let part_header = rns_wire::header::PacketHeader { - flags: rns_wire::flags::PacketFlags { - header_type: rns_wire::flags::HeaderType::Header1, - context_flag: false, - transport_type: rns_wire::flags::TransportType::Broadcast, - destination_type: rns_wire::flags::DestinationType::Link, - packet_type: rns_wire::flags::PacketType::Data, - }, - hops: 0, - transport_id: None, - destination_hash: link_id, - context, - }; - let mut raw = part_header.pack(); - raw.extend_from_slice(&body); - active.link.record_tx(raw.len()); - let _ = self.transport_tx.try_send(TransportMessage::Outbound( - OutboundRequest { - raw: Bytes::from(raw), + if plaintext.len() >= resource_hash_start + 32 { + let mut rh = [0u8; 32]; + rh.copy_from_slice( + &plaintext[resource_hash_start..resource_hash_start + 32], + ); + let packet_hash = + rns_wire::hash::packet_hash(raw, header.flags.header_type); + let actions = active + .outbound_resources + .get_mut(&rh) + .map(|transfer| { + transfer.handle_request_packet(packet_hash, &plaintext) + }) + .unwrap_or_default(); + for action in actions { + let (context, body) = match action { + TransferAction::SendPart(idx, part_data) => { + tracing::trace!( + link_id = hex::encode(link_id), + part = idx, + "sent resource part (request response)" + ); + ( + rns_wire::context::PacketContext::Resource, + Bytes::from(part_data), + ) + } + TransferAction::SendHmu(hmu) => { + let Ok(encrypted) = active.link.encrypt(&hmu) else { + continue; + }; + ( + rns_wire::context::PacketContext::ResourceHmu, + Bytes::from(encrypted), + ) + } + TransferAction::SendRequest(req) => { + let Ok(encrypted) = active.link.encrypt(&req) else { + continue; + }; + ( + rns_wire::context::PacketContext::ResourceReq, + Bytes::from(encrypted), + ) + } + TransferAction::SendCancel(cancel_type, resource_hash) => { + let Ok(encrypted) = active.link.encrypt(&resource_hash) + else { + continue; + }; + let context = match cancel_type { + rns_protocol::resource::CancelType::Icl => { + rns_wire::context::PacketContext::ResourceIcl + } + rns_protocol::resource::CancelType::Rcl => { + rns_wire::context::PacketContext::ResourceRcl + } + }; + (context, Bytes::from(encrypted)) + } + _ => continue, + }; + let part_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: + rns_wire::flags::TransportType::Broadcast, + destination_type: + rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, destination_hash: link_id, - }, - )); + context, + }; + let mut raw = part_header.pack(); + raw.extend_from_slice(&body); + active.link.record_tx(raw.len()); + let _ = self.transport_tx.try_send(TransportMessage::Outbound( + OutboundRequest { + raw: Bytes::from(raw), + destination_hash: link_id, + }, + )); + } } } } @@ -1281,47 +1295,47 @@ impl LinkManager { // Sender-initiated cancel of an inbound transfer (Link.py:1135-1142). if let Some(active) = self.active_links.get_mut(&link_id) { active.link.record_inbound(); - if let Ok(plaintext) = active.link.decrypt(data) - && plaintext.len() >= 32 - { - let mut rh = [0u8; 32]; - rh.copy_from_slice(&plaintext[..32]); - if let Some(transfer) = active.inbound_resources.get_mut(&rh) { - transfer.handle_cancel(); - tracing::debug!( - link_id = hex::encode(link_id), - "RESOURCE_ICL — inbound transfer cancelled" - ); - } - active.inbound_resources.remove(&rh); + if let Ok(plaintext) = active.link.decrypt(data) { + if plaintext.len() >= 32 { + let mut rh = [0u8; 32]; + rh.copy_from_slice(&plaintext[..32]); + if let Some(transfer) = active.inbound_resources.get_mut(&rh) { + transfer.handle_cancel(); + tracing::debug!( + link_id = hex::encode(link_id), + "RESOURCE_ICL — inbound transfer cancelled" + ); + } + active.inbound_resources.remove(&rh); - // Sender-cancel of a split-segment tears down the whole - // reassembly state (coordinator + sibling segments) so - // the coordinator isn't orphaned forever. - if let Some(route) = active.segment_routing.remove(&rh) { - let oh = route.original_hash; - active.inbound_split_resources.remove(&oh); - let siblings: Vec<[u8; 32]> = active - .segment_routing - .iter() - .filter_map(|(seg_rh, r)| { - if r.original_hash == oh { - Some(*seg_rh) - } else { - None - } - }) - .collect(); - for sibling_rh in siblings { - active.segment_routing.remove(&sibling_rh); - active.inbound_resources.remove(&sibling_rh); - active.link.untrack_resource(&sibling_rh); + // Sender-cancel of a split-segment tears down the whole + // reassembly state (coordinator + sibling segments) so + // the coordinator isn't orphaned forever. + if let Some(route) = active.segment_routing.remove(&rh) { + let oh = route.original_hash; + active.inbound_split_resources.remove(&oh); + let siblings: Vec<[u8; 32]> = active + .segment_routing + .iter() + .filter_map(|(seg_rh, r)| { + if r.original_hash == oh { + Some(*seg_rh) + } else { + None + } + }) + .collect(); + for sibling_rh in siblings { + active.segment_routing.remove(&sibling_rh); + active.inbound_resources.remove(&sibling_rh); + active.link.untrack_resource(&sibling_rh); + } + tracing::debug!( + link_id = hex::encode(link_id), + original = hex::encode(&oh[..8]), + "split-resource cancelled by sender — coordinator + siblings dropped" + ); } - tracing::debug!( - link_id = hex::encode(link_id), - original = hex::encode(&oh[..8]), - "split-resource cancelled by sender — coordinator + siblings dropped" - ); } } } @@ -1330,56 +1344,60 @@ impl LinkManager { // Receiver-initiated reject of an outbound transfer (Link.py:1144-1151). if let Some(active) = self.active_links.get_mut(&link_id) { active.link.record_inbound(); - if let Ok(plaintext) = active.link.decrypt(data) - && plaintext.len() >= 32 - { - let mut rh = [0u8; 32]; - rh.copy_from_slice(&plaintext[..32]); - if let Some(transfer) = active.outbound_resources.get_mut(&rh) { - transfer.resource.handle_cancel(); - tracing::debug!( - link_id = hex::encode(link_id), - "RESOURCE_RCL — outbound transfer rejected" - ); + if let Ok(plaintext) = active.link.decrypt(data) { + if plaintext.len() >= 32 { + let mut rh = [0u8; 32]; + rh.copy_from_slice(&plaintext[..32]); + if let Some(transfer) = active.outbound_resources.get_mut(&rh) { + transfer.resource.handle_cancel(); + tracing::debug!( + link_id = hex::encode(link_id), + "RESOURCE_RCL — outbound transfer rejected" + ); + } + active.outbound_resources.remove(&rh); } - active.outbound_resources.remove(&rh); } } } rns_wire::context::PacketContext::ResourceHmu => { if let Some(active) = self.active_links.get_mut(&link_id) { active.link.record_inbound(); - if let Ok(plaintext) = active.link.decrypt(data) - && let Ok((rh, segment, hashmap)) = + if let Ok(plaintext) = active.link.decrypt(data) { + if let Ok((rh, segment, hashmap)) = rns_protocol::resource::parse_hashmap_update(&plaintext) - && let Some(transfer) = active.inbound_resources.get_mut(&rh) - { - let action = transfer.hashmap_update(segment, &hashmap); - if let TransferAction::SendRequest(req) = action - && let Ok(encrypted) = active.link.encrypt(&req) { - let req_header = rns_wire::header::PacketHeader { - flags: rns_wire::flags::PacketFlags { - header_type: rns_wire::flags::HeaderType::Header1, - context_flag: false, - transport_type: rns_wire::flags::TransportType::Broadcast, - destination_type: rns_wire::flags::DestinationType::Link, - packet_type: rns_wire::flags::PacketType::Data, - }, - hops: 0, - transport_id: None, - destination_hash: link_id, - context: rns_wire::context::PacketContext::ResourceReq, - }; - let mut req_raw = req_header.pack(); - req_raw.extend_from_slice(&encrypted); - active.link.record_tx(req_raw.len()); - let _ = self.transport_tx.try_send(TransportMessage::Outbound( - OutboundRequest { - raw: Bytes::from(req_raw), - destination_hash: link_id, - }, - )); + if let Some(transfer) = active.inbound_resources.get_mut(&rh) { + let action = transfer.hashmap_update(segment, &hashmap); + if let TransferAction::SendRequest(req) = action { + if let Ok(encrypted) = active.link.encrypt(&req) { + let req_header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: + rns_wire::flags::TransportType::Broadcast, + destination_type: + rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::ResourceReq, + }; + let mut req_raw = req_header.pack(); + req_raw.extend_from_slice(&encrypted); + active.link.record_tx(req_raw.len()); + let _ = self.transport_tx.try_send( + TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(req_raw), + destination_hash: link_id, + }), + ); + } + } + } } } } @@ -1522,8 +1540,8 @@ impl LinkManager { ); } - if let Some((data, metadata, auto_compress)) = fetch_spec - && self + if let Some((data, metadata, auto_compress)) = fetch_spec { + if self .start_resource_transfer_inner( &link_id, ResourceTransferStart { @@ -1536,11 +1554,12 @@ impl LinkManager { }, ) .is_none() - { - tracing::warn!( - link_id = hex::encode(link_id), - "link request resource response could not be started" - ); + { + tracing::warn!( + link_id = hex::encode(link_id), + "link request resource response could not be started" + ); + } } } } @@ -1914,16 +1933,16 @@ impl LinkManager { } let rtt = active.link.rtt_secs(); - if let Some(channel) = active.channel.as_mut() - && let Some(sequence) = channel.delivered_by_packet_hash(&packet_hash, rtt) - { - active.link.keepalive.record_proof(); - tracing::debug!( - link_id = hex::encode(link_id), - sequence, - packet_hash = hex::encode(&packet_hash[..8]), - "channel packet delivery proof accepted" - ); + if let Some(channel) = active.channel.as_mut() { + if let Some(sequence) = channel.delivered_by_packet_hash(&packet_hash, rtt) { + active.link.keepalive.record_proof(); + tracing::debug!( + link_id = hex::encode(link_id), + sequence, + packet_hash = hex::encode(&packet_hash[..8]), + "channel packet delivery proof accepted" + ); + } } } @@ -3238,11 +3257,11 @@ mod tests { // Widen the receiver's WINDOW_INITIAL=4 so the blast fits in one shot. let segment_rh = transfer.resource.resource_hash; let total_parts = transfer.resource.parts.len(); - if let Some(active) = lm.active_links.get_mut(&link_id) - && let Some(in_transfer) = active.inbound_resources.get_mut(&segment_rh) - { - in_transfer.resource.window.window = total_parts; - in_transfer.outstanding_parts = total_parts; + if let Some(active) = lm.active_links.get_mut(&link_id) { + if let Some(in_transfer) = active.inbound_resources.get_mut(&segment_rh) { + in_transfer.resource.window.window = total_parts; + in_transfer.outstanding_parts = total_parts; + } } for part in &transfer.resource.parts { diff --git a/crates/rns-runtime/src/probe.rs b/crates/rns-runtime/src/probe.rs index 730389a..d885b85 100644 --- a/crates/rns-runtime/src/probe.rs +++ b/crates/rns-runtime/src/probe.rs @@ -178,10 +178,10 @@ impl DeliveryProofWaiter { Ok(None) => return None, Err(_) => return None, }; - if let DestinationEvent::DeliveryProof { msg_id, rtt } = ev - && msg_id == self.msg_id - { - return Some(rtt); + if let DestinationEvent::DeliveryProof { msg_id, rtt } = ev { + if msg_id == self.msg_id { + return Some(rtt); + } } } } @@ -382,11 +382,12 @@ async fn collect_path_meta(tx: &mpsc::Sender, dest: [u8; 16]) let mut meta = PathMeta::default(); if let Ok(TransportQueryResponse::PathTable(entries)) = query(tx, TransportQuery::GetPathTable).await - && let Some(entry) = entries.into_iter().find(|e| e.hash == dest) { - meta.hops = entry.hops; - meta.via = entry.via; - meta.interface = Some(entry.interface); + if let Some(entry) = entries.into_iter().find(|e| e.hash == dest) { + meta.hops = entry.hops; + meta.via = entry.via; + meta.interface = Some(entry.interface); + } } meta } diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 58c2006..78ff37d 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -155,34 +155,40 @@ impl ReticulumHandle { /// Python exposes, then fall back to the local actor for Rust-only/local /// diagnostics such as recent announce snapshots. pub async fn query_control(&self, query: TransportQuery) -> Option { - if self.instance_mode == InstanceMode::Client - && let Some(request) = transport_query_to_rpc_request(&query) - && let Some(rpc_key) = self.config.rpc_key.as_deref() - { - let rpc_result = match self.config.shared_rpc_endpoint(&self.socket_base) { - SharedInstanceRpcEndpoint::Tcp(port) => { - crate::rpc::connect_and_request(port, rpc_key, &request, Duration::from_secs(5)) - .await - } - SharedInstanceRpcEndpoint::Unix(socket_path) => { - crate::rpc::connect_unix_and_request( - &socket_path, - rpc_key, - &request, - Duration::from_secs(5), - ) - .await - } - }; - match rpc_result { - Ok(response) => { - if let Some(mapped) = rpc_response_to_transport_response(response) { - return Some(mapped); + if self.instance_mode == InstanceMode::Client { + if let Some(request) = transport_query_to_rpc_request(&query) { + if let Some(rpc_key) = self.config.rpc_key.as_deref() { + let rpc_result = match self.config.shared_rpc_endpoint(&self.socket_base) { + SharedInstanceRpcEndpoint::Tcp(port) => { + crate::rpc::connect_and_request( + port, + rpc_key, + &request, + Duration::from_secs(5), + ) + .await + } + SharedInstanceRpcEndpoint::Unix(socket_path) => { + crate::rpc::connect_unix_and_request( + &socket_path, + rpc_key, + &request, + Duration::from_secs(5), + ) + .await + } + }; + match rpc_result { + Ok(response) => { + if let Some(mapped) = rpc_response_to_transport_response(response) { + return Some(mapped); + } + } + Err(e) => { + tracing::debug!(error = %e, "shared instance control RPC failed; falling back to local actor"); + } } } - Err(e) => { - tracing::debug!(error = %e, "shared instance control RPC failed; falling back to local actor"); - } } } @@ -707,10 +713,10 @@ fn parse_hash16_list(key: &str, list: Option>) -> Result PathBuf { - if (path == "~" || path.starts_with("~/")) - && let Ok(home) = std::env::var("HOME") - { - return PathBuf::from(format!("{home}{}", &path[1..])); + if path == "~" || path.starts_with("~/") { + if let Ok(home) = std::env::var("HOME") { + return PathBuf::from(format!("{home}{}", &path[1..])); + } } PathBuf::from(path) } @@ -803,10 +809,10 @@ impl ReticulumConfig { } } - if let Some(sec) = config.section("logging") - && let Some(level) = config_int("logging", sec, "loglevel")? - { - rc.loglevel = (level as i32).clamp(0, 7); + if let Some(sec) = config.section("logging") { + if let Some(level) = config_int("logging", sec, "loglevel")? { + rc.loglevel = (level as i32).clamp(0, 7); + } } Ok(rc) @@ -879,10 +885,10 @@ pub async fn init( // Python defaults the local shared-instance RPC key to a hash of the // persistent transport identity, so CLI/control clients work without an // explicit config key as long as they share the same config directory. - if rc.rpc_key.is_none() - && let Some(private_key) = transport_identity.get_private_key() - { - rc.rpc_key = Some(crate::rpc::derive_rpc_key(&*private_key).to_vec()); + if rc.rpc_key.is_none() { + if let Some(private_key) = transport_identity.get_private_key() { + rc.rpc_key = Some(crate::rpc::derive_rpc_key(&*private_key).to_vec()); + } } let transport_identity = Arc::new(transport_identity); @@ -1275,34 +1281,35 @@ pub async fn init( } // RPC server runs only on Shared; CLI clients authenticate against `rpc_key`. - if instance_mode == InstanceMode::Shared - && let Some(rpc_key) = rc.rpc_key.clone() - { - let rpc_tx = transport_tx.clone(); - let rpc_shutdown = shutdown.clone(); - if rc.shared_instance_type == SharedInstanceType::Unix { - let rpc_socket = shared_unix_rpc_socket_path(&rc.instance_name, &socket_base); - tokio::spawn(async move { - if let Err(e) = crate::rpc_server::run_unix_rpc_server( - &rpc_socket, - rpc_key, - rpc_tx, - rpc_shutdown, - ) - .await - { - tracing::warn!("Unix RPC server error: {}", e); - } - }); - } else { - let rpc_port = rc.control_port; - tokio::spawn(async move { - if let Err(e) = - crate::rpc_server::run_rpc_server(rpc_port, rpc_key, rpc_tx, rpc_shutdown).await - { - tracing::warn!("RPC server error: {}", e); - } - }); + if instance_mode == InstanceMode::Shared { + if let Some(rpc_key) = rc.rpc_key.clone() { + let rpc_tx = transport_tx.clone(); + let rpc_shutdown = shutdown.clone(); + if rc.shared_instance_type == SharedInstanceType::Unix { + let rpc_socket = shared_unix_rpc_socket_path(&rc.instance_name, &socket_base); + tokio::spawn(async move { + if let Err(e) = crate::rpc_server::run_unix_rpc_server( + &rpc_socket, + rpc_key, + rpc_tx, + rpc_shutdown, + ) + .await + { + tracing::warn!("Unix RPC server error: {}", e); + } + }); + } else { + let rpc_port = rc.control_port; + tokio::spawn(async move { + if let Err(e) = + crate::rpc_server::run_rpc_server(rpc_port, rpc_key, rpc_tx, rpc_shutdown) + .await + { + tracing::warn!("RPC server error: {}", e); + } + }); + } } } @@ -3026,15 +3033,18 @@ fn clean_cache(cache_dir: &Path) { if let Ok(entries) = std::fs::read_dir(cache_dir) { for entry in entries.flatten() { - if let Ok(metadata) = entry.metadata() - && metadata.is_file() - && let Ok(modified) = metadata.modified() - && let Ok(age) = now.duration_since(modified) - && age > cache_ttl - { - let path = entry.path(); - if std::fs::remove_file(&path).is_ok() { - tracing::trace!("cleaned cache entry: {}", path.display()); + if let Ok(metadata) = entry.metadata() { + if metadata.is_file() { + if let Ok(modified) = metadata.modified() { + if let Ok(age) = now.duration_since(modified) { + if age > cache_ttl { + let path = entry.path(); + if std::fs::remove_file(&path).is_ok() { + tracing::trace!("cleaned cache entry: {}", path.display()); + } + } + } + } } } } @@ -3042,7 +3052,7 @@ fn clean_cache(cache_dir: &Path) { } fn hex_decode(s: &str) -> Option> { - if !s.len().is_multiple_of(2) { + if s.len() % 2 != 0 { return None; } (0..s.len()) diff --git a/crates/rns-runtime/src/rncp.rs b/crates/rns-runtime/src/rncp.rs index db1a71d..9d7c98f 100644 --- a/crates/rns-runtime/src/rncp.rs +++ b/crates/rns-runtime/src/rncp.rs @@ -1293,21 +1293,21 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result) -> Result { diff --git a/crates/rns-runtime/src/rnsh.rs b/crates/rns-runtime/src/rnsh.rs index 9bf5b16..8b1cf2b 100644 --- a/crates/rns-runtime/src/rnsh.rs +++ b/crates/rns-runtime/src/rnsh.rs @@ -661,23 +661,23 @@ async fn handle_client_message( RnshMessage::StreamData(stream) => match stream.stream_id { STREAM_ID_STDOUT => { stdout.extend_from_slice(&stream.data); - if let Some(tx) = stdout_tx - && !stream.data.is_empty() - { - tx.send(stream.data) - .await - .map_err(|_| RnshError::Process("stdout stream receiver closed".into()))?; + if let Some(tx) = stdout_tx { + if !stream.data.is_empty() { + tx.send(stream.data).await.map_err(|_| { + RnshError::Process("stdout stream receiver closed".into()) + })?; + } } Ok(None) } STREAM_ID_STDERR => { stderr.extend_from_slice(&stream.data); - if let Some(tx) = stderr_tx - && !stream.data.is_empty() - { - tx.send(stream.data) - .await - .map_err(|_| RnshError::Process("stderr stream receiver closed".into()))?; + if let Some(tx) = stderr_tx { + if !stream.data.is_empty() { + tx.send(stream.data).await.map_err(|_| { + RnshError::Process("stderr stream receiver closed".into()) + })?; + } } Ok(None) } @@ -1091,10 +1091,10 @@ async fn handle_listener_channel_message( .await?; return Ok(()); } - if let Some(stdin) = session.stdin.as_mut() - && !stream.data.is_empty() - { - stdin.write_all(&stream.data).await?; + if let Some(stdin) = session.stdin.as_mut() { + if !stream.data.is_empty() { + stdin.write_all(&stream.data).await?; + } } if stream.eof { if let Some(stdin) = session.stdin.as_mut() { @@ -1247,20 +1247,20 @@ async fn start_listener_process( stderr, ))); } - if let Some(ref pty) = pty - && (!pipe_stdout || !pipe_stderr) - { - let stream_id = if !pipe_stdout { - STREAM_ID_STDOUT - } else { - STREAM_ID_STDERR - }; - reader_tasks.push(tokio::spawn(stream_reader_task( - command_tx.clone(), - link_id, - stream_id, - pty_reader_file(pty)?, - ))); + if let Some(ref pty) = pty { + if !pipe_stdout || !pipe_stderr { + let stream_id = if !pipe_stdout { + STREAM_ID_STDOUT + } else { + STREAM_ID_STDERR + }; + reader_tasks.push(tokio::spawn(stream_reader_task( + command_tx.clone(), + link_id, + stream_id, + pty_reader_file(pty)?, + ))); + } } let window = pty.take().map(pty_window_target); diff --git a/crates/rns-runtime/src/rpc_server.rs b/crates/rns-runtime/src/rpc_server.rs index 78c96cd..f981156 100644 --- a/crates/rns-runtime/src/rpc_server.rs +++ b/crates/rns-runtime/src/rpc_server.rs @@ -450,78 +450,82 @@ async fn process_rpc_request( } } RpcRequest::GetPacketRssi { packet_hash } => { - if let Some(hash) = packet_hash_to_array(&packet_hash) - && let Some(TransportQueryResponse::FloatResult(v)) = query_transport( + if let Some(hash) = packet_hash_to_array(&packet_hash) { + if let Some(TransportQueryResponse::FloatResult(v)) = query_transport( transport_tx, TransportQuery::GetPacketRssi { packet_hash: hash }, ) .await - { - RpcResponse::FloatResult(v) - } else { - RpcResponse::FloatResult(None) + { + return RpcResponse::FloatResult(v); + } } + RpcResponse::FloatResult(None) } RpcRequest::GetPacketSnr { packet_hash } => { - if let Some(hash) = packet_hash_to_array(&packet_hash) - && let Some(TransportQueryResponse::FloatResult(v)) = query_transport( + if let Some(hash) = packet_hash_to_array(&packet_hash) { + if let Some(TransportQueryResponse::FloatResult(v)) = query_transport( transport_tx, TransportQuery::GetPacketSnr { packet_hash: hash }, ) .await - { - RpcResponse::FloatResult(v) - } else { - RpcResponse::FloatResult(None) + { + return RpcResponse::FloatResult(v); + } } + RpcResponse::FloatResult(None) } RpcRequest::GetPacketQ { packet_hash } => { - if let Some(hash) = packet_hash_to_array(&packet_hash) - && let Some(TransportQueryResponse::FloatResult(v)) = query_transport( + if let Some(hash) = packet_hash_to_array(&packet_hash) { + if let Some(TransportQueryResponse::FloatResult(v)) = query_transport( transport_tx, TransportQuery::GetPacketQ { packet_hash: hash }, ) .await - { - RpcResponse::FloatResult(v) - } else { - RpcResponse::FloatResult(None) + { + return RpcResponse::FloatResult(v); + } } + RpcResponse::FloatResult(None) } RpcRequest::DropAllVia { transport_hash } => { - if let Some(next_hop) = hash_to_array(&transport_hash) - && let Some(TransportQueryResponse::IntResult(n)) = + if let Some(next_hop) = hash_to_array(&transport_hash) { + if let Some(TransportQueryResponse::IntResult(n)) = query_transport(transport_tx, TransportQuery::DropAllVia { next_hop }).await - { - return RpcResponse::IntResult(n); + { + return RpcResponse::IntResult(n); + } } RpcResponse::IntResult(0) } RpcRequest::UseDestination { destination_hash } => { - if let Some(dest) = hash_to_array(&destination_hash) - && let Some(TransportQueryResponse::BoolResult(v)) = + if let Some(dest) = hash_to_array(&destination_hash) { + if let Some(TransportQueryResponse::BoolResult(v)) = query_transport(transport_tx, TransportQuery::UseDestination { dest }).await - { - return RpcResponse::BoolResult(v); + { + return RpcResponse::BoolResult(v); + } } RpcResponse::BoolResult(false) } RpcRequest::RetainDestination { destination_hash } => { - if let Some(dest) = hash_to_array(&destination_hash) - && let Some(TransportQueryResponse::BoolResult(v)) = + if let Some(dest) = hash_to_array(&destination_hash) { + if let Some(TransportQueryResponse::BoolResult(v)) = query_transport(transport_tx, TransportQuery::RetainDestination { dest }).await - { - return RpcResponse::BoolResult(v); + { + return RpcResponse::BoolResult(v); + } } RpcResponse::BoolResult(false) } RpcRequest::UnretainDestination { destination_hash } => { - if let Some(dest) = hash_to_array(&destination_hash) - && let Some(TransportQueryResponse::BoolResult(v)) = + if let Some(dest) = hash_to_array(&destination_hash) { + if let Some(TransportQueryResponse::BoolResult(v)) = query_transport(transport_tx, TransportQuery::UnretainDestination { dest }) .await - { - return RpcResponse::BoolResult(v); + { + return RpcResponse::BoolResult(v); + } } RpcResponse::BoolResult(false) } diff --git a/crates/rns-tools/src/commands/rncp.rs b/crates/rns-tools/src/commands/rncp.rs index c7e63a3..4b71d92 100644 --- a/crates/rns-tools/src/commands/rncp.rs +++ b/crates/rns-tools/src/commands/rncp.rs @@ -24,10 +24,10 @@ use rns_transport::messages::{OutboundRequest, TransportMessage}; use tokio::io::AsyncWriteExt; fn expand_tilde(p: &str) -> PathBuf { - if let Some(rest) = p.strip_prefix("~/") - && let Some(home) = std::env::var_os("HOME") - { - return PathBuf::from(home).join(rest); + if let Some(rest) = p.strip_prefix("~/") { + if let Some(home) = std::env::var_os("HOME") { + return PathBuf::from(home).join(rest); + } } PathBuf::from(p) } @@ -171,16 +171,16 @@ fn load_or_create_identity( )), } } else { - if let Some(parent) = path.parent() - && let Err(e) = std::fs::create_dir_all(parent) - { - return Err(( - 2, - format!( - "Could not create identity directory \"{}\": {e}", - parent.display() - ), - )); + if let Some(parent) = path.parent() { + if let Err(e) = std::fs::create_dir_all(parent) { + return Err(( + 2, + format!( + "Could not create identity directory \"{}\": {e}", + parent.display() + ), + )); + } } let id = Identity::new(); if let Err(e) = id.to_file(&path) { @@ -604,11 +604,11 @@ async fn run_listen(args: Args) -> ! { } let fetch_jail = args.jail.as_deref().map(expand_tilde); - if let Some(ref jail) = fetch_jail - && !jail.is_dir() - { - eprintln!("Fetch jail directory not found: {}", jail.display()); - process::exit(3); + if let Some(ref jail) = fetch_jail { + if !jail.is_dir() { + eprintln!("Fetch jail directory not found: {}", jail.display()); + process::exit(3); + } } let (event_tx, mut event_rx) = tokio::sync::mpsc::channel::(64); diff --git a/crates/rns-tools/src/commands/rnid/main.rs b/crates/rns-tools/src/commands/rnid/main.rs index 330d6a1..6d5e0c2 100644 --- a/crates/rns-tools/src/commands/rnid/main.rs +++ b/crates/rns-tools/src/commands/rnid/main.rs @@ -990,7 +990,7 @@ fn encode_base32(bytes: &[u8]) -> String { let index = ((buffer << (5 - bits)) & 0x1f) as usize; out.push(ALPHABET[index] as char); } - while !out.len().is_multiple_of(8) { + while out.len() % 8 != 0 { out.push('='); } out diff --git a/crates/rns-tools/src/commands/rnpath.rs b/crates/rns-tools/src/commands/rnpath.rs index 93ca09d..f3cb787 100644 --- a/crates/rns-tools/src/commands/rnpath.rs +++ b/crates/rns-tools/src/commands/rnpath.rs @@ -1075,13 +1075,13 @@ async fn run_remote(args: Args) -> ExitCode { }; req_args.push(rmpv::Value::Binary(dest.to_vec())); } - if args.table - && let Some(m) = args.max - { - if args.destination.is_none() { - req_args.push(rmpv::Value::Nil); + if args.table { + if let Some(m) = args.max { + if args.destination.is_none() { + req_args.push(rmpv::Value::Nil); + } + req_args.push(rmpv::Value::from(m)); } - req_args.push(rmpv::Value::from(m)); } let req_value = rmpv::Value::Array(req_args); let mut payload = Vec::new(); diff --git a/crates/rns-tools/src/commands/rnstatus.rs b/crates/rns-tools/src/commands/rnstatus.rs index 1516c7c..32f21b0 100644 --- a/crates/rns-tools/src/commands/rnstatus.rs +++ b/crates/rns-tools/src/commands/rnstatus.rs @@ -440,13 +440,13 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option, println!(" IFAC : {} bits", entry.ifac_size * 8); } if args.announce_stats { - if let Some(queued) = entry.announce_queue - && queued > 0 - { - println!( - " Queued : {queued} announce{}", - if queued == 1 { "" } else { "s" } - ); + if let Some(queued) = entry.announce_queue { + if queued > 0 { + println!( + " Queued : {queued} announce{}", + if queued == 1 { "" } else { "s" } + ); + } } if entry.held_announces > 0 { println!( @@ -1026,13 +1026,13 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode { println!(" Clients : {clients}"); } if args.announce_stats { - if let Some(queued) = iface.announce_queue - && queued > 0 - { - println!( - " Queued : {queued} announce{}", - if queued == 1 { "" } else { "s" } - ); + if let Some(queued) = iface.announce_queue { + if queued > 0 { + println!( + " Queued : {queued} announce{}", + if queued == 1 { "" } else { "s" } + ); + } } if iface.held_announces > 0 { println!( diff --git a/crates/rns-transport/src/actor/inbound.rs b/crates/rns-transport/src/actor/inbound.rs index 88c82cc..97082a7 100644 --- a/crates/rns-transport/src/actor/inbound.rs +++ b/crates/rns-transport/src/actor/inbound.rs @@ -14,19 +14,21 @@ impl TransportActor { // Strip the IFAC tag if the interface gates membership on one; packets // that fail verification are silently dropped so a misconfigured peer // can't leak into a closed access group. - let raw: bytes::Bytes = if let Some(entry) = self.interfaces.get(&packet.interface_id) - && let Some(ref ifac_key) = entry.ifac_key - { - let ifac_size = entry.ifac_size; - match crate::ifac::ifac_verify(&packet.raw, ifac_key, ifac_size) { - Some(stripped) => bytes::Bytes::from(stripped), - None => { - trace!( - interface_id = packet.interface_id, - "IFAC verification failed, dropping packet" - ); - return; + let raw: bytes::Bytes = if let Some(entry) = self.interfaces.get(&packet.interface_id) { + if let Some(ref ifac_key) = entry.ifac_key { + let ifac_size = entry.ifac_size; + match crate::ifac::ifac_verify(&packet.raw, ifac_key, ifac_size) { + Some(stripped) => bytes::Bytes::from(stripped), + None => { + trace!( + interface_id = packet.interface_id, + "IFAC verification failed, dropping packet" + ); + return; + } } + } else { + packet.raw.clone() } } else { packet.raw.clone() @@ -174,16 +176,24 @@ impl TransportActor { .interfaces .get(&interface_id) .is_some_and(|entry| entry.announce_rate_target.is_some()); - if has_interface_rate_limit - && let Some(entry) = self.interfaces.get(&interface_id) - && let Some(target) = entry.announce_rate_target - && self.rate_table.check_interface_rate( - header.destination_hash, - target, - entry.announce_rate_grace.unwrap_or(0), - entry.announce_rate_penalty.unwrap_or(0.0), - ) - { + let interface_rate_blocked = if has_interface_rate_limit { + self.interfaces + .get(&interface_id) + .and_then(|entry| { + entry.announce_rate_target.map(|target| { + self.rate_table.check_interface_rate( + header.destination_hash, + target, + entry.announce_rate_grace.unwrap_or(0), + entry.announce_rate_penalty.unwrap_or(0.0), + ) + }) + }) + .unwrap_or(false) + } else { + false + }; + if interface_rate_blocked { debug!( dest = hex::encode(header.destination_hash), interface = interface_id, @@ -296,33 +306,33 @@ impl TransportActor { // Cancel our queued rebroadcast when a neighbor already carried it. // Same-hop neighbor rebroadcast counts toward the local cap; // strict hops+1 forward drops our queued copy outright. - if self.is_transport_enabled - && let Some(existing) = self.announce_table.get(&header.destination_hash) - { - let existing_hops = existing.hops; - let existing_retries = existing.retries; - if header.hops > 0 && header.hops - 1 == existing_hops && existing_retries > 0 { - let existing_local_rebroadcasts = existing.local_rebroadcasts + 1; - if existing_local_rebroadcasts >= LOCAL_REBROADCASTS_MAX { - debug!( - dest = hex::encode(header.destination_hash), - "announce dedup: local rebroadcast limit reached, removing from table" - ); - self.announce_table.remove(&header.destination_hash); - } else if let Some(ae) = self.announce_table.get_mut(&header.destination_hash) { - ae.local_rebroadcasts = existing_local_rebroadcasts; + if self.is_transport_enabled { + if let Some(existing) = self.announce_table.get(&header.destination_hash) { + let existing_hops = existing.hops; + let existing_retries = existing.retries; + if header.hops > 0 && header.hops - 1 == existing_hops && existing_retries > 0 { + let existing_local_rebroadcasts = existing.local_rebroadcasts + 1; + if existing_local_rebroadcasts >= LOCAL_REBROADCASTS_MAX { + debug!( + dest = hex::encode(header.destination_hash), + "announce dedup: local rebroadcast limit reached, removing from table" + ); + self.announce_table.remove(&header.destination_hash); + } else if let Some(ae) = self.announce_table.get_mut(&header.destination_hash) { + ae.local_rebroadcasts = existing_local_rebroadcasts; + } } - } - if header.hops > 0 && header.hops - 1 == existing_hops + 1 && existing_retries > 0 { - let now = now_f64(); - if let Some(ae) = self.announce_table.get(&header.destination_hash) - && now < ae.retransmit_timeout - { - debug!( - dest = hex::encode(header.destination_hash), - "announce dedup: passed on by another node, cancelling rebroadcast" - ); - self.announce_table.remove(&header.destination_hash); + if header.hops > 0 && header.hops - 1 == existing_hops + 1 && existing_retries > 0 { + let now = now_f64(); + if let Some(ae) = self.announce_table.get(&header.destination_hash) { + if now < ae.retransmit_timeout { + debug!( + dest = hex::encode(header.destination_hash), + "announce dedup: passed on by another node, cancelling rebroadcast" + ); + self.announce_table.remove(&header.destination_hash); + } + } } } } @@ -468,15 +478,19 @@ impl TransportActor { } } - if is_from_local_client - && header.context == rns_wire::context::PacketContext::PathResponse - && let Some(waiting_interface) = self + if is_from_local_client && header.context == rns_wire::context::PacketContext::PathResponse + { + if let Some(waiting_interface) = self .pending_local_path_requests .remove(&header.destination_hash) - { - let response = - self.path_response_from_cached_announce(raw, header.destination_hash, header.hops); - self.send_to_interface(waiting_interface, &response); + { + let response = self.path_response_from_cached_announce( + raw, + header.destination_hash, + header.hops, + ); + self.send_to_interface(waiting_interface, &response); + } } self.send_announce_to_local_clients( @@ -690,33 +704,33 @@ impl TransportActor { "data packet routing" ); if self.local_destinations.contains(&header.destination_hash) { - if let Some(tx) = self.destination_channels.get(&header.destination_hash) - && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { + if let Some(tx) = self.destination_channels.get(&header.destination_hash) { + if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { raw: raw.clone(), interface_id, - }) - { - self.channel_drops += 1; - warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, - "failed to deliver InboundPacket to local destination (channel full)"); + }) { + self.channel_drops += 1; + warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver InboundPacket to local destination (channel full)"); + } } return; } - if (self.is_transport_enabled || from_local_client || for_local_client) - && let Some(path) = self.path_table.get(&header.destination_hash) - { - let target_interface = path.interface_id; - let mut forwarded = raw.to_vec(); - if forwarded.len() >= 2 { - forwarded[1] = header.hops.saturating_add(1); + if self.is_transport_enabled || from_local_client || for_local_client { + if let Some(path) = self.path_table.get(&header.destination_hash) { + let target_interface = path.interface_id; + let mut forwarded = raw.to_vec(); + if forwarded.len() >= 2 { + forwarded[1] = header.hops.saturating_add(1); + } + self.send_to_interface(target_interface, &forwarded); + trace!( + dest = hex::encode(header.destination_hash), + via_interface = target_interface, + "data packet forwarded" + ); } - self.send_to_interface(target_interface, &forwarded); - trace!( - dest = hex::encode(header.destination_hash), - via_interface = target_interface, - "data packet forwarded" - ); } } @@ -739,21 +753,22 @@ impl TransportActor { } if self.local_destinations.contains(&header.destination_hash) { - if let Some(tx) = self.destination_channels.get(&header.destination_hash) - && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::LinkRequest { + if let Some(tx) = self.destination_channels.get(&header.destination_hash) { + if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::LinkRequest { raw: raw.clone(), interface_id, - }) - { - self.channel_drops += 1; - error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, - "failed to deliver LinkRequest; link establishment will fail"); + }) { + self.channel_drops += 1; + error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver LinkRequest; link establishment will fail"); + } } return; } - if (self.is_transport_enabled || from_local_client || for_local_client) - && let Some(path) = self.path_table.get(&header.destination_hash) + if let Some(path) = (self.is_transport_enabled || from_local_client || for_local_client) + .then(|| self.path_table.get(&header.destination_hash)) + .flatten() { let target_interface = path.interface_id; let remaining_hops = path.hops; @@ -868,66 +883,65 @@ impl TransportActor { // `hops+1 == remaining_hops` here and we bump hops on forward so the // next relay sees the expected value. if header.context == rns_wire::context::PacketContext::Lrproof { - if (self.is_transport_enabled || from_local_client || for_local_client_link) - && self.link_table.contains(&header.destination_hash) - && let Some(link_entry) = self.link_table.get(&header.destination_hash) - { - let expected_hops = link_entry.remaining_hops; - let outbound_interface = link_entry.interface_id; - let target_interface = link_entry.receiving_interface; + if self.is_transport_enabled || from_local_client || for_local_client_link { + if let Some(link_entry) = self.link_table.get(&header.destination_hash) { + let expected_hops = link_entry.remaining_hops; + let outbound_interface = link_entry.interface_id; + let target_interface = link_entry.receiving_interface; - // Require that the proof arrived on the same interface we - // forwarded the request to; a mismatch is either a routing - // change or a spoof and must not be relayed. - let hops_match = if expected_hops == 0 { - header.hops == 0 - } else { - header.hops.saturating_add(1) == expected_hops - }; - if hops_match && _interface_id == outbound_interface { - let mut forwarded = raw.to_vec(); - if forwarded.len() >= 2 { - forwarded[1] = header.hops.saturating_add(1); + // Require that the proof arrived on the same interface we + // forwarded the request to; a mismatch is either a routing + // change or a spoof and must not be relayed. + let hops_match = if expected_hops == 0 { + header.hops == 0 + } else { + header.hops.saturating_add(1) == expected_hops + }; + if hops_match && _interface_id == outbound_interface { + let mut forwarded = raw.to_vec(); + if forwarded.len() >= 2 { + forwarded[1] = header.hops.saturating_add(1); + } + if let Some(entry) = self.link_table.get_mut(&header.destination_hash) { + entry.validated = true; + } + self.send_to_interface(target_interface, &forwarded); + debug!( + link_id = hex::encode(header.destination_hash), + via_interface = target_interface, + hops = header.hops + 1, + "link proof (LRPROOF) routed via link table" + ); + return; + } else if !hops_match { + warn!( + link_id = hex::encode(header.destination_hash), + expected_hops, + actual_hops = header.hops, + "link proof hop mismatch, not transporting (expected hops+1 == remaining_hops)" + ); + } else { + warn!( + link_id = hex::encode(header.destination_hash), + expected_interface = outbound_interface, + actual_interface = _interface_id, + "link proof received on wrong interface, not transporting" + ); } - if let Some(entry) = self.link_table.get_mut(&header.destination_hash) { - entry.validated = true; - } - self.send_to_interface(target_interface, &forwarded); - debug!( - link_id = hex::encode(header.destination_hash), - via_interface = target_interface, - hops = header.hops + 1, - "link proof (LRPROOF) routed via link table" - ); - return; - } else if !hops_match { - warn!( - link_id = hex::encode(header.destination_hash), - expected_hops, - actual_hops = header.hops, - "link proof hop mismatch, not transporting (expected hops+1 == remaining_hops)" - ); - } else { - warn!( - link_id = hex::encode(header.destination_hash), - expected_interface = outbound_interface, - actual_interface = _interface_id, - "link proof received on wrong interface, not transporting" - ); } } // Fall through to local-pending-link delivery when link_table // didn't claim the proof. - if let Some(tx) = self.destination_channels.get(&header.destination_hash) - && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { + if let Some(tx) = self.destination_channels.get(&header.destination_hash) { + if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { raw: raw.clone(), interface_id: _interface_id, - }) - { - self.channel_drops += 1; - warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, - "failed to deliver LRPROOF to local pending link (channel full)"); + }) { + self.channel_drops += 1; + warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver LRPROOF to local pending link (channel full)"); + } } return; } @@ -940,17 +954,26 @@ impl TransportActor { // entry records the outbound interface we forwarded on, enforce the // match — a proof on the wrong interface means a routing change or // a spoof. Older entries without that field route unconditionally. - if (self.is_transport_enabled || from_local_client || proof_for_local_client) - && let Some(reverse_entry) = self.reverse_table.remove(&header.destination_hash) - { - if let Some(expected_outbound) = reverse_entry.outbound_interface { - if _interface_id != expected_outbound { - debug!( - dest = hex::encode(header.destination_hash), - expected = expected_outbound, - actual = _interface_id, - "proof arrived on wrong interface, not routing via reverse table" - ); + if self.is_transport_enabled || from_local_client || proof_for_local_client { + if let Some(reverse_entry) = self.reverse_table.remove(&header.destination_hash) { + if let Some(expected_outbound) = reverse_entry.outbound_interface { + if _interface_id != expected_outbound { + debug!( + dest = hex::encode(header.destination_hash), + expected = expected_outbound, + actual = _interface_id, + "proof arrived on wrong interface, not routing via reverse table" + ); + } else { + let target_interface = reverse_entry.receiving_interface; + self.send_to_interface(target_interface, raw); + trace!( + dest = hex::encode(header.destination_hash), + via_interface = target_interface, + "proof routed via reverse table" + ); + return; + } } else { let target_interface = reverse_entry.receiving_interface; self.send_to_interface(target_interface, raw); @@ -961,27 +984,18 @@ impl TransportActor { ); return; } - } else { - let target_interface = reverse_entry.receiving_interface; - self.send_to_interface(target_interface, raw); - trace!( - dest = hex::encode(header.destination_hash), - via_interface = target_interface, - "proof routed via reverse table" - ); - return; } } - if let Some(tx) = self.destination_channels.get(&header.destination_hash) - && let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { + if let Some(tx) = self.destination_channels.get(&header.destination_hash) { + if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { raw: raw.clone(), interface_id: _interface_id, - }) - { - self.channel_drops += 1; - error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, - "failed to deliver link proof to local link"); + }) { + self.channel_drops += 1; + error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, + "failed to deliver link proof to local link"); + } } } diff --git a/crates/rns-transport/src/actor/maintenance.rs b/crates/rns-transport/src/actor/maintenance.rs index e7184ef..25e3632 100644 --- a/crates/rns-transport/src/actor/maintenance.rs +++ b/crates/rns-transport/src/actor/maintenance.rs @@ -358,16 +358,18 @@ impl TransportActor { } for dest_hash in &voided_destinations { - if self.local_destinations.contains(dest_hash) - && let Some(tx) = self.destination_channels.get(dest_hash) - && let Err(e) = - tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested( - crate::link_messages::AnnounceRequest::normal(String::new()), - )) - { - self.channel_drops += 1; - warn!(dest = hex::encode(dest_hash), drops = self.channel_drops, err = %e, - "failed to send re-announce after tunnel void (channel full)"); + if self.local_destinations.contains(dest_hash) { + if let Some(tx) = self.destination_channels.get(dest_hash) { + if let Err(e) = + tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested( + crate::link_messages::AnnounceRequest::normal(String::new()), + )) + { + self.channel_drops += 1; + warn!(dest = hex::encode(dest_hash), drops = self.channel_drops, err = %e, + "failed to send re-announce after tunnel void (channel full)"); + } + } } } } diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index 6659ac6..ca14359 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -342,20 +342,21 @@ impl TransportActor { .find(|(_, entry)| entry.packet_hash == Some(packet_hash)) .map(|(dest, _)| *dest.as_bytes()); - if let Some(dest) = local_hit - && let Some(cached) = self.recent_announces.get(&dest) - && !cached.raw_packet.is_empty() - { - debug!(hash = %hex::encode(&packet_hash[..8]), "cache request: local hit, replaying"); - let inbound = crate::messages::InboundPacket { - raw: Bytes::copy_from_slice(&cached.raw_packet), - interface_id: 0, - rssi: None, - snr: None, - q: None, - }; - self.on_inbound(inbound); - return; + if let Some(dest) = local_hit { + if let Some(cached) = self.recent_announces.get(&dest) { + if !cached.raw_packet.is_empty() { + debug!(hash = %hex::encode(&packet_hash[..8]), "cache request: local hit, replaying"); + let inbound = crate::messages::InboundPacket { + raw: Bytes::copy_from_slice(&cached.raw_packet), + interface_id: 0, + rssi: None, + snr: None, + q: None, + }; + self.on_inbound(inbound); + return; + } + } } // Local miss: only transport nodes forward the request diff --git a/crates/rns-transport/src/actor/outbound.rs b/crates/rns-transport/src/actor/outbound.rs index 27b1104..ad0b27e 100644 --- a/crates/rns-transport/src/actor/outbound.rs +++ b/crates/rns-transport/src/actor/outbound.rs @@ -145,10 +145,10 @@ impl TransportActor { let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type); self.packet_hashlist.insert(pkt_hash); self.send_to_interface(interface_id, &request.raw); - if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce - && let Some(entry) = self.interfaces.get_mut(&interface_id) - { - entry.ingress.sent_announce(); + if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce { + if let Some(entry) = self.interfaces.get_mut(&interface_id) { + entry.ingress.sent_announce(); + } } } } @@ -287,11 +287,11 @@ impl TransportActor { let mut unique_tag = Vec::with_capacity(32); unique_tag.extend_from_slice(&requested_dest); unique_tag.extend_from_slice(tag); - if let Some(last) = self.discovery_pr_tags.get(&unique_tag) - && now - last < PATH_REQUEST_GATE_TIMEOUT - { - trace!(dest = %hex::encode(requested_dest), "ignoring duplicate path request"); - return; + if let Some(last) = self.discovery_pr_tags.get(&unique_tag) { + if now - last < PATH_REQUEST_GATE_TIMEOUT { + trace!(dest = %hex::encode(requested_dest), "ignoring duplicate path request"); + return; + } } self.discovery_pr_tags.insert(unique_tag, now); @@ -300,8 +300,8 @@ impl TransportActor { dest = %hex::encode(requested_dest), "answering path request — destination is local" ); - if let Some(tx) = self.destination_channels.get(&requested_dest) - && let Err(e) = + if let Some(tx) = self.destination_channels.get(&requested_dest) { + if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested( crate::link_messages::AnnounceRequest { app_name: String::new(), @@ -310,28 +310,31 @@ impl TransportActor { attached_interface: Some(interface_id), }, )) - { - self.channel_drops += 1; - warn!(dest = hex::encode(requested_dest), drops = self.channel_drops, err = %e, - "failed to send AnnounceRequested for local path request"); + { + self.channel_drops += 1; + warn!(dest = hex::encode(requested_dest), drops = self.channel_drops, err = %e, + "failed to send AnnounceRequested for local path request"); + } } self.fire_path_waiters(&requested_dest); return; } - if !is_from_local_client - && let Some(path) = self.path_table.get(&requested_dest) - && self.is_local_client_interface(path.interface_id) - { - self.pending_local_path_requests - .insert(requested_dest, interface_id); + if !is_from_local_client { + if let Some(path) = self.path_table.get(&requested_dest) { + if self.is_local_client_interface(path.interface_id) { + self.pending_local_path_requests + .insert(requested_dest, interface_id); + } + } } // Python Transport.py: local shared clients are allowed to use the // shared instance's path cache even when the instance is not a transport // node. Ordinary peers still require transport mode. - if (self.is_transport_enabled || is_from_local_client) - && let Some(path) = self.path_table.get(&requested_dest) + if let Some(path) = (self.is_transport_enabled || is_from_local_client) + .then(|| self.path_table.get(&requested_dest)) + .flatten() { let requestor_is_next_hop = requestor_transport_id.is_some_and(|requestor| path.next_hop == Some(requestor)); @@ -464,10 +467,10 @@ impl TransportActor { fn build_path_request_packet(&self, destination_hash: [u8; 16], tag: Option<&[u8]>) -> Vec { let mut request_data = Vec::with_capacity(48); request_data.extend_from_slice(&destination_hash); - if self.is_transport_enabled - && let Some(identity_hash) = self.transport_identity_hash - { - request_data.extend_from_slice(&identity_hash); + if self.is_transport_enabled { + if let Some(identity_hash) = self.transport_identity_hash { + request_data.extend_from_slice(&identity_hash); + } } if let Some(tag) = tag { request_data.extend_from_slice(&tag[..tag.len().min(16)]); @@ -536,10 +539,10 @@ impl TransportActor { pub(super) fn on_path_request(&mut self, destination_hash: [u8; 16]) { let now = now_f64(); - if let Some(last) = self.path_requests.get(&destination_hash) - && now - last < PATH_REQUEST_MI - { - return; + if let Some(last) = self.path_requests.get(&destination_hash) { + if now - last < PATH_REQUEST_MI { + return; + } } self.path_requests.insert(destination_hash, now); @@ -560,10 +563,10 @@ impl TransportActor { let mut request_data = Vec::with_capacity(48); request_data.extend_from_slice(&destination_hash); - if self.is_transport_enabled - && let Some(identity_hash) = self.transport_identity_hash - { - request_data.extend_from_slice(&identity_hash); + if self.is_transport_enabled { + if let Some(identity_hash) = self.transport_identity_hash { + request_data.extend_from_slice(&identity_hash); + } } request_data.extend_from_slice(&request_tag); @@ -661,16 +664,16 @@ impl TransportActor { } } - if !deprecated_paths.is_empty() - && let Some(tunnel) = self.tunnel_table.get_mut(tunnel_id) - { - for dest_hash in &deprecated_paths { - tunnel.tunnel_paths.remove(dest_hash); - debug!( - dest = hex::encode(dest_hash), - tunnel = hex::encode(&tunnel_id[..16]), - "removed deprecated path from tunnel" - ); + if !deprecated_paths.is_empty() { + if let Some(tunnel) = self.tunnel_table.get_mut(tunnel_id) { + for dest_hash in &deprecated_paths { + tunnel.tunnel_paths.remove(dest_hash); + debug!( + dest = hex::encode(dest_hash), + tunnel = hex::encode(&tunnel_id[..16]), + "removed deprecated path from tunnel" + ); + } } } } diff --git a/crates/rns-transport/src/discovery/blackhole_manifest.rs b/crates/rns-transport/src/discovery/blackhole_manifest.rs index ca3bfcb..b241194 100644 --- a/crates/rns-transport/src/discovery/blackhole_manifest.rs +++ b/crates/rns-transport/src/discovery/blackhole_manifest.rs @@ -215,18 +215,19 @@ pub fn apply_manifest( ) -> usize { let mut applied = 0usize; for (id_hash, entry) in manifest { - if let Some(until) = entry.until - && until <= now - { - continue; + if let Some(until) = entry.until { + if until <= now { + continue; + } } if let Some(existing) = table .iter_entries() .find(|(h, _)| h.as_bytes() == id_hash) .map(|(_, e)| e.clone()) - && existing.source.is_none() { - continue; + if existing.source.is_none() { + continue; + } } let ttl = entry.until.map(|u| (u - now).max(0.0)); diff --git a/crates/rns-transport/src/discovery/receiver.rs b/crates/rns-transport/src/discovery/receiver.rs index 517a83e..03b0abd 100644 --- a/crates/rns-transport/src/discovery/receiver.rs +++ b/crates/rns-transport/src/discovery/receiver.rs @@ -140,10 +140,10 @@ impl ReceiverConfig { }; let announced_identity = event.identity_hash.unwrap_or(info.transport_id); - if let Some(sources) = self.discovery_sources.as_ref() - && !sources.iter().any(|s| s == &announced_identity) - { - return Outcome::Rejected(Reason::UnauthorizedSource); + if let Some(sources) = self.discovery_sources.as_ref() { + if !sources.iter().any(|s| s == &announced_identity) { + return Outcome::Rejected(Reason::UnauthorizedSource); + } } let stamp_value = self.stamper.value(&infohash, stamp); diff --git a/crates/rns-transport/src/discovery/storage.rs b/crates/rns-transport/src/discovery/storage.rs index d1948fa..560910e 100644 --- a/crates/rns-transport/src/discovery/storage.rs +++ b/crates/rns-transport/src/discovery/storage.rs @@ -185,10 +185,10 @@ impl DiscoveryStore { let heard_delta = now.saturating_sub(rec.last_heard); let mut should_remove = heard_delta > THRESHOLD_REMOVE_SECS; - if let Some(sources) = discovery_sources - && !sources.iter().any(|s| s == &rec.network_id) - { - should_remove = true; + if let Some(sources) = discovery_sources { + if !sources.iter().any(|s| s == &rec.network_id) { + should_remove = true; + } } if should_remove { let _ = std::fs::remove_file(&path);