Merge branch 'clippy-fixes' into 'main'

Clippy fixes

See merge request veilid/veilid!195
This commit is contained in:
Christien Rioux 2023-09-19 00:43:41 +00:00
commit 563b80e31c
143 changed files with 3597 additions and 3320 deletions

View File

@ -76,7 +76,6 @@ impl ClientApiConnection {
};
if let Err(e) = reply_channel.send_async(response).await {
error!("failed to process reply: {}", e);
return;
}
}

View File

@ -248,7 +248,6 @@ Server Debug Commands:
_ => {
ui.add_node_event(Level::Error, format!("unknown flag: {}", flag));
ui.send_callback(callback);
return;
}
}
});
@ -271,7 +270,6 @@ Server Debug Commands:
_ => {
ui.add_node_event(Level::Error, format!("unknown flag: {}", flag));
ui.send_callback(callback);
return;
}
}
});
@ -399,12 +397,12 @@ Server Debug Commands:
}
pub fn update_route(&self, route: &json::JsonValue) {
let mut out = String::new();
if route["dead_routes"].len() != 0 {
if !route["dead_routes"].is_empty() {
out.push_str(&format!("Dead routes: {:?}", route["dead_routes"]));
}
if route["dead_routes"].len() != 0 {
if !route["dead_routes"].is_empty() {
if !out.is_empty() {
out.push_str("\n");
out.push('\n');
}
out.push_str(&format!(
"Dead remote routes: {:?}",
@ -460,7 +458,7 @@ Server Debug Commands:
};
let strmsg = if printable {
format!("\"{}\"", String::from_utf8_lossy(&message).to_string())
format!("\"{}\"", String::from_utf8_lossy(message))
} else {
hex::encode(message)
};
@ -498,7 +496,7 @@ Server Debug Commands:
};
let strmsg = if printable {
format!("\"{}\"", String::from_utf8_lossy(&message).to_string())
format!("\"{}\"", String::from_utf8_lossy(message))
} else {
hex::encode(message)
};

View File

@ -1,4 +1,5 @@
#![deny(clippy::all)]
#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)]
#![deny(unused_must_use)]
#![recursion_limit = "256"]
@ -58,7 +59,7 @@ fn main() -> Result<(), String> {
None
};
let mut settings = settings::Settings::new(settings_path.as_ref().map(|x| x.as_os_str()))
let mut settings = settings::Settings::new(settings_path.as_deref())
.map_err(|e| format!("configuration is invalid: {}", e))?;
// Set config from command line

View File

@ -58,7 +58,7 @@ impl TableViewItem<PeerTableColumn> for json::JsonValue {
PeerTableColumn::NodeId => self["node_ids"][0].to_string(),
PeerTableColumn::Address => self["peer_address"].to_string(),
PeerTableColumn::LatencyAvg => {
format!("{}", format_ts(&self["peer_stats"]["latency"]["average"]))
format_ts(&self["peer_stats"]["latency"]["average"]).to_string()
}
PeerTableColumn::TransferDownAvg => {
format_bps(&self["peer_stats"]["transfer"]["down"]["average"])

View File

@ -6,7 +6,7 @@ use std::net::{SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
pub fn load_default_config() -> Result<config::Config, config::ConfigError> {
let default_config = r###"---
let default_config = r#"---
address: "localhost:5959"
autoconnect: true
autoreconnect: true
@ -44,7 +44,7 @@ interface:
info : "white"
warn : "light yellow"
error : "light red"
"###
"#
.replace(
"%LOGGING_FILE_DIRECTORY%",
&Settings::get_default_log_directory().to_string_lossy(),

View File

@ -469,7 +469,7 @@ impl UI {
let color = *Self::inner_mut(s).log_colors.get(&Level::Warn).unwrap();
cursive_flexi_logger_view::parse_lines_to_log(
color.into(),
format!(">> Could not copy to clipboard"),
">> Could not copy to clipboard".to_string(),
);
}
} else {
@ -483,8 +483,8 @@ impl UI {
.as_bytes(),
)
.is_ok()
&& std::io::stdout().flush().is_ok()
{
if std::io::stdout().flush().is_ok() {
let color = *Self::inner_mut(s).log_colors.get(&Level::Info).unwrap();
cursive_flexi_logger_view::parse_lines_to_log(
color.into(),
@ -493,7 +493,6 @@ impl UI {
}
}
}
}
fn on_submit_peers_table_view(s: &mut Cursive, _row: usize, index: usize) {
let peers_table_view = UI::peers(s);
@ -523,7 +522,7 @@ impl UI {
let mut reset: bool = false;
match state {
ConnectionState::Disconnected => {
if inner.connection_dialog_state == None
if inner.connection_dialog_state.is_none()
|| inner
.connection_dialog_state
.as_ref()
@ -541,7 +540,7 @@ impl UI {
}
}
ConnectionState::Connected(_, _) => {
if inner.connection_dialog_state != None
if inner.connection_dialog_state.is_some()
&& !inner
.connection_dialog_state
.as_ref()
@ -552,7 +551,7 @@ impl UI {
}
}
ConnectionState::Retrying(_, _) => {
if inner.connection_dialog_state == None
if inner.connection_dialog_state.is_none()
|| inner
.connection_dialog_state
.as_ref()
@ -941,10 +940,12 @@ impl UI {
// }
}
type CallbackSink = Box<dyn FnOnce(&mut Cursive) + 'static + Send>;
#[derive(Clone)]
pub struct UISender {
inner: Arc<Mutex<UIInner>>,
cb_sink: Sender<Box<dyn FnOnce(&mut Cursive) + 'static + Send>>,
cb_sink: Sender<CallbackSink>,
}
impl UISender {
@ -1020,7 +1021,7 @@ impl UISender {
for l in 0..node_ids.len() {
let nid = &node_ids[l];
if !node_id_str.is_empty() {
node_id_str.push_str(" ");
node_id_str.push(' ');
}
node_id_str.push_str(nid.to_string().as_ref());
}

View File

@ -3,7 +3,7 @@ use std::process::{Command, Stdio};
fn search_file<T: AsRef<str>, P: AsRef<str>>(start: T, name: P) -> Option<PathBuf> {
let start_path = PathBuf::from(start.as_ref()).canonicalize().ok();
let mut path = start_path.as_ref().map(|x| x.as_path());
let mut path = start_path.as_deref();
while let Some(some_path) = path {
let file_path = some_path.join(name.as_ref());
if file_path.exists() {
@ -18,10 +18,7 @@ fn get_desired_capnp_version_string() -> String {
let capnp_path = search_file(env!("CARGO_MANIFEST_DIR"), ".capnp_version")
.expect("should find .capnp_version file");
std::fs::read_to_string(&capnp_path)
.expect(&format!(
"can't read .capnp_version file here: {:?}",
capnp_path
))
.unwrap_or_else(|_| panic!("can't read .capnp_version file here: {:?}", capnp_path))
.trim()
.to_owned()
}
@ -47,10 +44,7 @@ fn get_desired_protoc_version_string() -> String {
let protoc_path = search_file(env!("CARGO_MANIFEST_DIR"), ".protoc_version")
.expect("should find .protoc_version file");
std::fs::read_to_string(&protoc_path)
.expect(&format!(
"can't read .protoc_version file here: {:?}",
protoc_path
))
.unwrap_or_else(|_| panic!("can't read .protoc_version file here: {:?}", protoc_path))
.trim()
.to_owned()
}
@ -79,11 +73,18 @@ fn main() {
let protoc_version_string = get_protoc_version_string();
// Check capnp version
let desired_capnp_major_version =
usize::from_str_radix(desired_capnp_version_string.split_once(".").unwrap().0, 10)
let desired_capnp_major_version = desired_capnp_version_string
.split_once('.')
.unwrap()
.0
.parse::<usize>()
.expect("should be valid int");
if usize::from_str_radix(capnp_version_string.split_once(".").unwrap().0, 10)
if capnp_version_string
.split_once('.')
.unwrap()
.0
.parse::<usize>()
.expect("should be valid int")
!= desired_capnp_major_version
{
@ -99,10 +100,17 @@ fn main() {
}
// Check protoc version
let desired_protoc_major_version =
usize::from_str_radix(desired_protoc_version_string.split_once(".").unwrap().0, 10)
let desired_protoc_major_version = desired_protoc_version_string
.split_once('.')
.unwrap()
.0
.parse::<usize>()
.expect("should be valid int");
if usize::from_str_radix(protoc_version_string.split_once(".").unwrap().0, 10)
if protoc_version_string
.split_once('.')
.unwrap()
.0
.parse::<usize>()
.expect("should be valid int")
< desired_protoc_major_version
{

View File

@ -103,11 +103,11 @@ impl<S: Subscriber + for<'a> registry::LookupSpan<'a>> Layer<S> for ApiTracingLa
None
};
(inner.update_callback)(VeilidUpdate::Log(VeilidLog {
(inner.update_callback)(VeilidUpdate::Log(Box::new(VeilidLog {
log_level,
message,
backtrace,
}))
})))
}
}
}

View File

@ -168,7 +168,7 @@ impl AttachmentManager {
})
.unwrap_or(true);
if send_update {
Some((update_callback, Self::get_veilid_state_inner(&*inner)))
Some((update_callback, Self::get_veilid_state_inner(&inner)))
} else {
None
}
@ -197,11 +197,11 @@ impl AttachmentManager {
};
if let Some(update_callback) = update_callback {
update_callback(VeilidUpdate::Attachment(VeilidStateAttachment {
update_callback(VeilidUpdate::Attachment(Box::new(VeilidStateAttachment {
state,
public_internet_ready: false,
local_network_ready: false,
}))
})))
}
}
@ -325,8 +325,8 @@ impl AttachmentManager {
// self.inner.lock().last_attachment_state
// }
fn get_veilid_state_inner(inner: &AttachmentManagerInner) -> VeilidStateAttachment {
VeilidStateAttachment {
fn get_veilid_state_inner(inner: &AttachmentManagerInner) -> Box<VeilidStateAttachment> {
Box::new(VeilidStateAttachment {
state: inner.last_attachment_state,
public_internet_ready: inner
.last_routing_table_health
@ -338,11 +338,11 @@ impl AttachmentManager {
.as_ref()
.map(|x| x.local_network_ready)
.unwrap_or(false),
}
})
}
pub fn get_veilid_state(&self) -> VeilidStateAttachment {
pub fn get_veilid_state(&self) -> Box<VeilidStateAttachment> {
let inner = self.inner.lock();
Self::get_veilid_state_inner(&*inner)
Self::get_veilid_state_inner(&inner)
}
}

View File

@ -236,7 +236,7 @@ impl Envelope {
}
// Compress body
let body = compress_prepend_size(&body);
let body = compress_prepend_size(body);
// Ensure body isn't too long
let envelope_size: usize = body.len() + MIN_ENVELOPE_SIZE;

View File

@ -8,10 +8,10 @@ use crate::tests::common::test_veilid_config::*;
async fn crypto_tests_startup() -> VeilidAPI {
trace!("crypto_tests: starting");
let (update_callback, config_callback) = setup_veilid_core();
let api = api_startup(update_callback, config_callback)
api_startup(update_callback, config_callback)
.await
.expect("startup failed");
api
.expect("startup failed")
}
async fn crypto_tests_shutdown(api: VeilidAPI) {

View File

@ -1,5 +1,3 @@
#![allow(clippy::bool_assert_comparison)]
use super::*;
use core::convert::TryFrom;
@ -228,7 +226,7 @@ pub async fn test_encode_decode(vcrypto: CryptoSystemVersion) {
pub async fn test_typed_convert(vcrypto: CryptoSystemVersion) {
let tks1 = format!(
"{}:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",
vcrypto.kind().to_string()
vcrypto.kind()
);
let tk1 = TypedKey::from_str(&tks1).expect("failed");
let tks1x = tk1.to_string();
@ -236,22 +234,22 @@ pub async fn test_typed_convert(vcrypto: CryptoSystemVersion) {
let tks2 = format!(
"{}:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd",
vcrypto.kind().to_string()
vcrypto.kind()
);
let _tk2 = TypedKey::from_str(&tks2).expect_err("succeeded when it shouldnt have");
let tks3 = format!("XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",);
let tks3 = "XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string();
let tk3 = TypedKey::from_str(&tks3).expect("failed");
let tks3x = tk3.to_string();
assert_eq!(tks3, tks3x);
let tks4 = format!("XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd",);
let tks4 = "XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd".to_string();
let _tk4 = TypedKey::from_str(&tks4).expect_err("succeeded when it shouldnt have");
let tks5 = format!("XXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",);
let tks5 = "XXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string();
let _tk5 = TypedKey::from_str(&tks5).expect_err("succeeded when it shouldnt have");
let tks6 = format!("7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",);
let tks6 = "7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string();
let tk6 = TypedKey::from_str(&tks6).expect("failed");
let tks6x = tk6.to_string();
assert!(tks6x.ends_with(&tks6));
@ -338,14 +336,14 @@ async fn test_operations(vcrypto: CryptoSystemVersion) {
assert_eq!(d4.first_nonzero_nibble(), Some((0, 0x9u8)));
// Verify bits
assert_eq!(d1.bit(0), true);
assert_eq!(d1.bit(1), false);
assert_eq!(d1.bit(7), false);
assert_eq!(d1.bit(8), false);
assert_eq!(d1.bit(14), true);
assert_eq!(d1.bit(15), false);
assert_eq!(d1.bit(254), true);
assert_eq!(d1.bit(255), false);
assert!(d1.bit(0));
assert!(!d1.bit(1));
assert!(!d1.bit(7));
assert!(!d1.bit(8));
assert!(d1.bit(14));
assert!(!d1.bit(15));
assert!(d1.bit(254));
assert!(!d1.bit(255));
assert_eq!(d1.first_nonzero_bit(), Some(0));
assert_eq!(d2.first_nonzero_bit(), Some(0));

View File

@ -77,7 +77,7 @@ where
macro_rules! byte_array_type {
($name:ident, $size:expr, $encoded_size:expr) => {
#[derive(Clone, Copy, Hash)]
#[derive(Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify), tsify(into_wasm_abi))]
pub struct $name {
pub bytes: [u8; $size],
@ -114,32 +114,6 @@ macro_rules! byte_array_type {
}
}
impl PartialOrd for $name {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for $name {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
for n in 0..$size {
let c = self.bytes[n].cmp(&other.bytes[n]);
if c != core::cmp::Ordering::Equal {
return c;
}
}
core::cmp::Ordering::Equal
}
}
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
}
impl Eq for $name {}
impl $name {
pub fn new(bytes: [u8; $size]) -> Self {
Self { bytes }

View File

@ -93,16 +93,13 @@ where
}
/// Return preferred typed key of our supported crypto kinds
pub fn best(&self) -> Option<CryptoTyped<K>> {
match self.items.first().copied() {
None => None,
Some(k) => {
if !VALID_CRYPTO_KINDS.contains(&k.kind) {
None
} else {
Some(k)
}
}
self.items
.first()
.copied()
.filter(|k| VALID_CRYPTO_KINDS.contains(&k.kind))
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn len(&self) -> usize {
self.items.len()
@ -204,7 +201,7 @@ where
if &s[0..1] != "[" || &s[(s.len() - 1)..] != "]" {
apibail_parse_error!("invalid format", s);
}
for x in s[1..s.len() - 1].split(",") {
for x in s[1..s.len() - 1].split(',') {
let tk = CryptoTyped::<K>::from_str(x.trim())?;
items.push(tk);
}
@ -272,7 +269,7 @@ where
tks
}
}
impl<K> Into<Vec<CryptoTyped<K>>> for CryptoTypedGroup<K>
impl<K> From<CryptoTypedGroup<K>> for Vec<CryptoTyped<K>>
where
K: Clone
+ Copy
@ -286,7 +283,7 @@ where
+ Hash
+ Encodable,
{
fn into(self) -> Vec<CryptoTyped<K>> {
self.items
fn from(val: CryptoTypedGroup<K>) -> Self {
val.items
}
}

View File

@ -96,7 +96,7 @@ impl<'de> serde::Deserialize<'de> for KeyPair {
D: serde::Deserializer<'de>,
{
let s = <String as serde::Deserialize>::deserialize(deserializer)?;
if s == "" {
if s.is_empty() {
return Ok(KeyPair::default());
}
KeyPair::try_decode(s.as_str()).map_err(serde::de::Error::custom)

View File

@ -134,8 +134,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
SharedSecret::new(s)
}
fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult<SharedSecret> {
let pk_xd = public_to_x25519_pk(&key)?;
let sk_xd = secret_to_x25519_sk(&secret)?;
let pk_xd = public_to_x25519_pk(key)?;
let sk_xd = secret_to_x25519_sk(secret)?;
let dh_bytes = sk_xd.diffie_hellman(&pk_xd).to_bytes();
@ -188,9 +188,9 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn distance(&self, key1: &PublicKey, key2: &PublicKey) -> CryptoKeyDistance {
let mut bytes = [0u8; CRYPTO_KEY_LENGTH];
for n in 0..CRYPTO_KEY_LENGTH {
(0..CRYPTO_KEY_LENGTH).for_each(|n| {
bytes[n] = key1.bytes[n] ^ key2.bytes[n];
}
});
CryptoKeyDistance::new(bytes)
}
@ -219,7 +219,7 @@ impl CryptoSystem for CryptoSystemVLD0 {
let sig = Signature::new(sig_bytes.to_bytes());
self.verify(dht_key, &data, &sig)?;
self.verify(dht_key, data, &sig)?;
Ok(sig)
}

View File

@ -9,4 +9,4 @@ mod native;
#[cfg(not(target_arch = "wasm32"))]
pub use native::*;
pub static KNOWN_PROTECTED_STORE_KEYS: [&'static str; 2] = ["device_encryption_key", "_test_key"];
pub static KNOWN_PROTECTED_STORE_KEYS: [&str; 2] = ["device_encryption_key", "_test_key"];

View File

@ -324,7 +324,7 @@ impl PlatformSupportApple {
let intf_index = unsafe { (*rt).rtm_index } as u32;
// Fill in sockaddr table
for i in 0..(RTAX_MAX as usize) {
(0..(RTAX_MAX as usize)).for_each(|i| {
if rtm_addrs & (1 << i) != 0 {
sa_tab[i] = sa;
sa = unsafe {
@ -333,7 +333,7 @@ impl PlatformSupportApple {
sa
};
}
}
});
// Look for gateways
if rtm_addrs & (RTA_DST | RTA_GATEWAY) == (RTA_DST | RTA_GATEWAY) {
@ -373,7 +373,7 @@ impl PlatformSupportApple {
}
fn get_address_flags(ifname: &str, addr: sockaddr_in6) -> EyreResult<AddressFlags> {
let mut req = in6_ifreq::from_name(&ifname).unwrap();
let mut req = in6_ifreq::from_name(ifname).unwrap();
req.set_addr(addr);
let sock = unsafe { socket(AF_INET6, SOCK_DGRAM, 0) };

View File

@ -359,7 +359,7 @@ impl NetworkInterfaces {
let old_best_addresses = inner.interface_address_cache.clone();
// redo the address cache
Self::cache_best_addresses(&mut *inner);
Self::cache_best_addresses(&mut inner);
// See if our best addresses have changed
if old_best_addresses != inner.interface_address_cache {

View File

@ -69,14 +69,11 @@ impl ProtectedStore {
let vkey = self.browser_key_name(key.as_ref());
let prev = match ls
let prev = ls
.get_item(&vkey)
.map_err(map_jsvalue_error)
.wrap_err("exception_thrown")?
{
Some(_) => true,
None => false,
};
.is_some();
ls.set_item(&vkey, value.as_ref())
.map_err(map_jsvalue_error)

View File

@ -22,6 +22,7 @@
//!
#![deny(clippy::all)]
#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)]
#![deny(unused_must_use)]
#![recursion_limit = "256"]

View File

@ -244,12 +244,12 @@ impl AddressFilter {
self.unlocked_inner.max_connections_per_ip6_prefix_size,
addr,
);
self.is_ip_addr_punished_inner(&*inner, ipblock)
self.is_ip_addr_punished_inner(&inner, ipblock)
}
pub fn get_dial_info_failed_ts(&self, dial_info: &DialInfo) -> Option<Timestamp> {
let inner = self.inner.lock();
self.get_dial_info_failed_ts_inner(&*inner, dial_info)
self.get_dial_info_failed_ts_inner(&inner, dial_info)
}
pub fn set_dial_info_failed(&self, dial_info: DialInfo) {
@ -301,7 +301,7 @@ impl AddressFilter {
pub fn is_node_id_punished(&self, node_id: TypedKey) -> bool {
let inner = self.inner.lock();
self.is_node_id_punished_inner(&*inner, node_id)
self.is_node_id_punished_inner(&inner, node_id)
}
pub fn punish_node_id(&self, node_id: TypedKey) {
@ -333,8 +333,8 @@ impl AddressFilter {
) -> EyreResult<()> {
//
let mut inner = self.inner.lock();
self.purge_old_timestamps(&mut *inner, cur_ts);
self.purge_old_punishments(&mut *inner, cur_ts);
self.purge_old_timestamps(&mut inner, cur_ts);
self.purge_old_punishments(&mut inner, cur_ts);
Ok(())
}
@ -411,7 +411,7 @@ impl AddressFilter {
);
let ts = get_aligned_timestamp();
self.purge_old_timestamps(&mut *inner, ts);
self.purge_old_timestamps(&mut inner, ts);
match ipblock {
IpAddr::V4(v4) => {

View File

@ -31,7 +31,7 @@ impl ConnectionHandle {
}
pub fn connection_descriptor(&self) -> ConnectionDescriptor {
self.descriptor.clone()
self.descriptor
}
#[cfg_attr(feature="verbose-tracing", instrument(level="trace", skip(self, message), fields(message.len = message.len())))]

View File

@ -117,13 +117,12 @@ impl ConnectionManager {
// Remove the inner from the lock
let mut inner = {
let mut inner_lock = self.arc.inner.lock();
let inner = match inner_lock.take() {
match inner_lock.take() {
Some(v) => v,
None => {
panic!("not started");
}
};
inner
}
};
// Stop all the connections and the async processor
@ -250,8 +249,8 @@ impl ConnectionManager {
&self,
dial_info: DialInfo,
) -> EyreResult<NetworkResult<ConnectionHandle>> {
let peer_address = dial_info.to_peer_address();
let remote_addr = peer_address.to_socket_addr();
let peer_address = dial_info.peer_address();
let remote_addr = peer_address.socket_addr();
let mut preferred_local_address = self
.network_manager()
.net()
@ -302,26 +301,6 @@ impl ConnectionManager {
.await;
match result_net_res {
Ok(net_res) => {
// // If the connection 'already exists', then try one last time to return a connection from the table, in case
// // an 'accept' happened at literally the same time as our connect. A preferred local address must have been
// // specified otherwise we would have picked a different ephemeral port and this could not have happened
// if net_res.is_already_exists() && preferred_local_address.is_some() {
// // Make 'already existing' connection descriptor
// let conn_desc = ConnectionDescriptor::new(
// dial_info.to_peer_address(),
// SocketAddress::from_socket_addr(preferred_local_address.unwrap()),
// );
// // Return the connection for this if we have it
// if let Some(conn) = self
// .arc
// .connection_table
// .get_connection_by_descriptor(conn_desc)
// {
// // Should not really happen, lets make sure we see this if it does
// log_net!(warn "== Returning existing connection in race: {:?}", conn_desc);
// return Ok(NetworkResult::Value(conn));
// }
// }
if net_res.is_value() || retry_count == 0 {
// Successful new connection, return it
break net_res;

View File

@ -164,7 +164,7 @@ impl ConnectionTable {
}
// Filter by ip for connection limits
let ip_addr = descriptor.remote_address().to_ip_addr();
let ip_addr = descriptor.remote_address().ip_addr();
match inner.address_filter.add_connection(ip_addr) {
Ok(()) => {}
Err(e) => {
@ -196,7 +196,7 @@ impl ConnectionTable {
}
log_net!(debug "== LRU Connection Killed: {} -> {}", lruk, lru_conn.debug_print(get_aligned_timestamp()));
out_conn = Some(Self::remove_connection_records(&mut *inner, lruk));
out_conn = Some(Self::remove_connection_records(&mut inner, lruk));
break;
}
}
@ -237,11 +237,11 @@ impl ConnectionTable {
best_port: Option<u16>,
remote: PeerAddress,
) -> Option<ConnectionHandle> {
let mut inner = self.inner.lock();
let inner = &mut *self.inner.lock();
let all_ids_by_remote = inner.ids_by_remote.get(&remote)?;
let protocol_index = Self::protocol_to_index(remote.protocol_type());
if all_ids_by_remote.len() == 0 {
if all_ids_by_remote.is_empty() {
// no connections
return None;
}
@ -253,11 +253,11 @@ impl ConnectionTable {
}
// multiple connections, find the one that matches the best port, or the most recent
if let Some(best_port) = best_port {
for id in all_ids_by_remote.iter().copied() {
let nc = inner.conn_by_id[protocol_index].peek(&id).unwrap();
for id in all_ids_by_remote {
let nc = inner.conn_by_id[protocol_index].peek(id).unwrap();
if let Some(local_addr) = nc.connection_descriptor().local() {
if local_addr.port() == best_port {
let nc = inner.conn_by_id[protocol_index].get(&id).unwrap();
let nc = inner.conn_by_id[protocol_index].get(id).unwrap();
return Some(nc.get_handle());
}
}
@ -331,7 +331,7 @@ impl ConnectionTable {
}
}
// address_filter
let ip_addr = remote.to_socket_addr().ip();
let ip_addr = remote.socket_addr().ip();
inner
.address_filter
.remove_connection(ip_addr)
@ -347,7 +347,7 @@ impl ConnectionTable {
if !inner.conn_by_id[protocol_index].contains_key(&id) {
return None;
}
let conn = Self::remove_connection_records(&mut *inner, id);
let conn = Self::remove_connection_records(&mut inner, id);
Some(conn)
}
@ -358,7 +358,7 @@ impl ConnectionTable {
for t in 0..inner.conn_by_id.len() {
out += &format!(
" {} Connections: ({}/{})\n",
Self::index_to_protocol(t).to_string(),
Self::index_to_protocol(t),
inner.conn_by_id[t].len(),
inner.max_connections[t]
);

View File

@ -46,7 +46,7 @@ use storage_manager::*;
#[cfg(target_arch = "wasm32")]
use wasm::*;
#[cfg(target_arch = "wasm32")]
pub use wasm::{LOCAL_NETWORK_CAPABILITIES, MAX_CAPABILITIES, PUBLIC_INTERNET_CAPABILITIES};
pub use wasm::{/* LOCAL_NETWORK_CAPABILITIES, */ MAX_CAPABILITIES, PUBLIC_INTERNET_CAPABILITIES,};
////////////////////////////////////////////////////////////////////////////////////////
@ -61,7 +61,7 @@ pub const PUBLIC_ADDRESS_CHECK_TASK_INTERVAL_SECS: u32 = 60;
pub const PUBLIC_ADDRESS_INCONSISTENCY_TIMEOUT_US: TimestampDuration =
TimestampDuration::new(300_000_000u64); // 5 minutes
pub const PUBLIC_ADDRESS_INCONSISTENCY_PUNISHMENT_TIMEOUT_US: TimestampDuration =
TimestampDuration::new(3600_000_000u64); // 60 minutes
TimestampDuration::new(3_600_000_000_u64); // 60 minutes
pub const ADDRESS_FILTER_TASK_INTERVAL_SECS: u32 = 60;
pub const BOOT_MAGIC: &[u8; 4] = b"BOOT";
@ -261,7 +261,7 @@ impl NetworkManager {
where
F: FnOnce(&VeilidConfigInner) -> R,
{
f(&*self.unlocked_inner.config.get())
f(&self.unlocked_inner.config.get())
}
pub fn storage_manager(&self) -> StorageManager {
self.unlocked_inner.storage_manager.clone()
@ -892,7 +892,7 @@ impl NetworkManager {
data.len(),
connection_descriptor
);
let remote_addr = connection_descriptor.remote_address().to_ip_addr();
let remote_addr = connection_descriptor.remote_address().ip_addr();
// Network accounting
self.stats_packet_rcvd(remote_addr, ByteCount::new(data.len() as u64));
@ -900,7 +900,7 @@ impl NetworkManager {
// If this is a zero length packet, just drop it, because these are used for hole punching
// and possibly other low-level network connectivity tasks and will never require
// more processing or forwarding
if data.len() == 0 {
if data.is_empty() {
return Ok(true);
}

View File

@ -141,10 +141,8 @@ impl DiscoveryContext {
let dial_info_filter = DialInfoFilter::all()
.with_protocol_type(protocol_type)
.with_address_type(address_type);
let inbound_dial_info_entry_filter = RoutingTable::make_inbound_dial_info_entry_filter(
routing_domain,
dial_info_filter.clone(),
);
let inbound_dial_info_entry_filter =
RoutingTable::make_inbound_dial_info_entry_filter(routing_domain, dial_info_filter);
let disallow_relays_filter = Box::new(
move |rti: &RoutingTableInner, v: Option<Arc<BucketEntry>>| {
let v = v.unwrap();
@ -199,7 +197,7 @@ impl DiscoveryContext {
let node = node.filtered_clone(
NodeRefFilter::new()
.with_routing_domain(routing_domain)
.with_dial_info_filter(dial_info_filter.clone()),
.with_dial_info_filter(dial_info_filter),
);
async move {
if let Some(address) = this.request_public_address(node.clone()).await {
@ -219,9 +217,7 @@ impl DiscoveryContext {
let mut external_address_infos = Vec::new();
for ni in 0..nodes.len() - 1 {
let node = nodes[ni].clone();
for node in nodes.iter().take(nodes.len() - 1).cloned() {
let gpa_future = get_public_address_func(node);
unord.push(gpa_future);
@ -277,15 +273,15 @@ impl DiscoveryContext {
node_ref.set_filter(None);
// ask the node to send us a dial info validation receipt
let out = rpc_processor
rpc_processor
.rpc_call_validate_dial_info(node_ref.clone(), dial_info, redirect)
.await
.map_err(logthru_net!(
"failed to send validate_dial_info to {:?}",
node_ref
))
.unwrap_or(false);
out
.unwrap_or(false)
}
#[instrument(level = "trace", skip(self), ret)]
@ -307,9 +303,14 @@ impl DiscoveryContext {
// Attempt a port mapping. If this doesn't succeed, it's not going to
let Some(mapped_external_address) = igd_manager
.map_any_port(low_level_protocol_type, address_type, local_port, Some(external_1.address.to_ip_addr()))
.await else
{
.map_any_port(
low_level_protocol_type,
address_type,
local_port,
Some(external_1.address.ip_addr()),
)
.await
else {
return None;
};

View File

@ -184,7 +184,7 @@ impl IGDManager {
let mut found = None;
for (pmk, pmv) in &inner.port_maps {
if pmk.llpt == llpt && pmk.at == at && pmv.mapped_port == mapped_port {
found = Some(pmk.clone());
found = Some(*pmk);
break;
}
}
@ -192,7 +192,7 @@ impl IGDManager {
let _pmv = inner.port_maps.remove(&pmk).expect("key found but remove failed");
// Find gateway
let gw = Self::find_gateway(&mut *inner, at)?;
let gw = Self::find_gateway(&mut inner, at)?;
// Unmap port
match gw.remove_port(convert_llpt(llpt), mapped_port) {
@ -230,10 +230,10 @@ impl IGDManager {
}
// Get local ip address
let local_ip = Self::find_local_ip(&mut *inner, at)?;
let local_ip = Self::find_local_ip(&mut inner, at)?;
// Find gateway
let gw = Self::find_gateway(&mut *inner, at)?;
let gw = Self::find_gateway(&mut inner, at)?;
// Get external address
let ext_ip = match gw.get_external_ip() {
@ -245,17 +245,13 @@ impl IGDManager {
};
// Ensure external IP matches address type
if ext_ip.is_ipv4() {
if at != AddressType::IPV4 {
if ext_ip.is_ipv4() && at != AddressType::IPV4 {
log_net!(debug "mismatched ip address type from igd, wanted v4, got v6");
return None;
}
} else if ext_ip.is_ipv6() {
if at != AddressType::IPV6 {
} else if ext_ip.is_ipv6() && at != AddressType::IPV6 {
log_net!(debug "mismatched ip address type from igd, wanted v6, got v4");
return None;
}
}
if let Some(expected_external_address) = expected_external_address {
if ext_ip != expected_external_address {

View File

@ -421,7 +421,7 @@ impl Network {
if self
.network_manager()
.address_filter()
.is_ip_addr_punished(dial_info.address().to_ip_addr())
.is_ip_addr_punished(dial_info.address().ip_addr())
{
return Ok(NetworkResult::no_connection_other("punished"));
}
@ -462,7 +462,7 @@ impl Network {
}
// Network accounting
self.network_manager()
.stats_packet_sent(dial_info.to_ip_addr(), ByteCount::new(data_len as u64));
.stats_packet_sent(dial_info.ip_addr(), ByteCount::new(data_len as u64));
Ok(NetworkResult::Value(()))
})
@ -491,7 +491,7 @@ impl Network {
if self
.network_manager()
.address_filter()
.is_ip_addr_punished(dial_info.address().to_ip_addr())
.is_ip_addr_punished(dial_info.address().ip_addr())
{
return Ok(NetworkResult::no_connection_other("punished"));
}
@ -507,7 +507,7 @@ impl Network {
.await
.wrap_err("send message failure")?);
self.network_manager()
.stats_packet_sent(dial_info.to_ip_addr(), ByteCount::new(data_len as u64));
.stats_packet_sent(dial_info.ip_addr(), ByteCount::new(data_len as u64));
// receive single response
let mut out = vec![0u8; MAX_MESSAGE_SIZE];
@ -519,7 +519,7 @@ impl Network {
.into_network_result())
.wrap_err("recv_message failure")?;
let recv_socket_addr = recv_addr.remote_address().to_socket_addr();
let recv_socket_addr = recv_addr.remote_address().socket_addr();
self.network_manager()
.stats_packet_rcvd(recv_socket_addr.ip(), ByteCount::new(recv_len as u64));
@ -552,7 +552,7 @@ impl Network {
network_result_try!(pnc.send(data).await.wrap_err("send failure")?);
self.network_manager()
.stats_packet_sent(dial_info.to_ip_addr(), ByteCount::new(data_len as u64));
.stats_packet_sent(dial_info.ip_addr(), ByteCount::new(data_len as u64));
let out =
network_result_try!(network_result_try!(timeout(timeout_ms, pnc.recv())
@ -560,10 +560,8 @@ impl Network {
.into_network_result())
.wrap_err("recv failure")?);
self.network_manager().stats_packet_rcvd(
dial_info.to_ip_addr(),
ByteCount::new(out.len() as u64),
);
self.network_manager()
.stats_packet_rcvd(dial_info.ip_addr(), ByteCount::new(out.len() as u64));
Ok(NetworkResult::Value(out))
}
@ -583,10 +581,10 @@ impl Network {
// Handle connectionless protocol
if descriptor.protocol_type() == ProtocolType::UDP {
// send over the best udp socket we have bound since UDP is not connection oriented
let peer_socket_addr = descriptor.remote().to_socket_addr();
let peer_socket_addr = descriptor.remote().socket_addr();
if let Some(ph) = self.find_best_udp_protocol_handler(
&peer_socket_addr,
&descriptor.local().map(|sa| sa.to_socket_addr()),
&descriptor.local().map(|sa| sa.socket_addr()),
) {
network_result_value_or_log!(ph.clone()
.send_message(data.clone(), peer_socket_addr)
@ -612,7 +610,7 @@ impl Network {
ConnectionHandleSendResult::Sent => {
// Network accounting
self.network_manager().stats_packet_sent(
descriptor.remote().to_socket_addr().ip(),
descriptor.remote().socket_addr().ip(),
ByteCount::new(data_len as u64),
);
@ -676,7 +674,7 @@ impl Network {
// Network accounting
self.network_manager()
.stats_packet_sent(dial_info.to_ip_addr(), ByteCount::new(data_len as u64));
.stats_packet_sent(dial_info.ip_addr(), ByteCount::new(data_len as u64));
Ok(NetworkResult::value(connection_descriptor))
})
@ -701,7 +699,7 @@ impl Network {
.with_interfaces(|interfaces| {
trace!("interfaces: {:#?}", interfaces);
for (_name, intf) in interfaces {
for intf in interfaces.values() {
// Skip networks that we should never encounter
if intf.is_loopback() || !intf.is_running() {
continue;

View File

@ -68,7 +68,7 @@ impl Network {
Ok(Ok((size, descriptor))) => {
// Network accounting
network_manager.stats_packet_rcvd(
descriptor.remote_address().to_ip_addr(),
descriptor.remote_address().ip_addr(),
ByteCount::new(size as u64),
);

View File

@ -24,7 +24,7 @@ impl ProtocolNetworkConnection {
timeout_ms: u32,
address_filter: AddressFilter,
) -> io::Result<NetworkResult<ProtocolNetworkConnection>> {
if address_filter.is_ip_addr_punished(dial_info.address().to_ip_addr()) {
if address_filter.is_ip_addr_punished(dial_info.address().ip_addr()) {
return Ok(NetworkResult::no_connection_other("punished"));
}
match dial_info.protocol_type() {

View File

@ -19,7 +19,7 @@ impl RawTcpNetworkConnection {
}
pub fn descriptor(&self) -> ConnectionDescriptor {
self.descriptor.clone()
self.descriptor
}
// #[instrument(level = "trace", err, skip(self))]
@ -132,11 +132,12 @@ impl RawTcpProtocolHandler {
) -> io::Result<Option<ProtocolNetworkConnection>> {
log_net!("TCP: on_accept_async: enter");
let mut peekbuf: [u8; PEEK_DETECT_LEN] = [0u8; PEEK_DETECT_LEN];
if let Err(_) = timeout(
if (timeout(
self.connection_initial_timeout_ms,
ps.peek_exact(&mut peekbuf),
)
.await
.await)
.is_err()
{
return Ok(None);
}

View File

@ -79,9 +79,9 @@ impl RawUdpProtocolHandler {
};
#[cfg(feature = "verbose-tracing")]
tracing::Span::current().record("ret.len", &message_len);
tracing::Span::current().record("ret.len", message_len);
#[cfg(feature = "verbose-tracing")]
tracing::Span::current().record("ret.descriptor", &format!("{:?}", descriptor).as_str());
tracing::Span::current().record("ret.descriptor", format!("{:?}", descriptor).as_str());
Ok((message_len, descriptor))
}
@ -134,7 +134,7 @@ impl RawUdpProtocolHandler {
);
#[cfg(feature = "verbose-tracing")]
tracing::Span::current().record("ret.descriptor", &format!("{:?}", descriptor).as_str());
tracing::Span::current().record("ret.descriptor", format!("{:?}", descriptor).as_str());
Ok(NetworkResult::value(descriptor))
}
@ -143,7 +143,7 @@ impl RawUdpProtocolHandler {
socket_addr: &SocketAddr,
) -> io::Result<RawUdpProtocolHandler> {
// get local wildcard address for bind
let local_socket_addr = compatible_unspecified_socket_addr(&socket_addr);
let local_socket_addr = compatible_unspecified_socket_addr(socket_addr);
let socket = UdpSocket::bind(local_socket_addr).await?;
Ok(RawUdpProtocolHandler::new(Arc::new(socket), None))
}

View File

@ -74,7 +74,7 @@ where
}
pub fn descriptor(&self) -> ConnectionDescriptor {
self.descriptor.clone()
self.descriptor
}
// #[instrument(level = "trace", err, skip(self))]
@ -232,7 +232,7 @@ impl WebsocketProtocolHandler {
// This check could be loosened if necessary, but until we have a reason to do so
// a stricter interpretation of HTTP is possible and desirable to reduce attack surface
if peek_buf.windows(4).position(|w| w == b"\r\n\r\n").is_none() {
if !peek_buf.windows(4).any(|w| w == b"\r\n\r\n") {
return Ok(None);
}
@ -306,7 +306,7 @@ impl WebsocketProtocolHandler {
// Make our connection descriptor
let descriptor = ConnectionDescriptor::new(
dial_info.to_peer_address(),
dial_info.peer_address(),
SocketAddress::from_socket_addr(actual_local_addr),
);
@ -339,8 +339,7 @@ impl Callback for WebsocketProtocolHandler {
|| request
.headers()
.iter()
.find(|h| (h.0.as_str().len() + h.1.as_bytes().len()) > MAX_WS_HEADER_LENGTH)
.is_some()
.any(|h| (h.0.as_str().len() + h.1.as_bytes().len()) > MAX_WS_HEADER_LENGTH)
{
let mut error_response = ErrorResponse::new(None);
*error_response.status_mut() = StatusCode::NOT_FOUND;

View File

@ -312,7 +312,7 @@ impl Network {
// if no other public address is specified
if !detect_address_changes
&& public_address.is_none()
&& routing_table.ensure_dial_info_is_valid(RoutingDomain::PublicInternet, &di)
&& routing_table.ensure_dial_info_is_valid(RoutingDomain::PublicInternet, di)
{
editor_public_internet.register_dial_info(di.clone(), DialInfoClass::Direct)?;
static_public = true;
@ -449,7 +449,7 @@ impl Network {
for socket_address in socket_addresses {
// Skip addresses we already did
if registered_addresses.contains(&socket_address.to_ip_addr()) {
if registered_addresses.contains(&socket_address.ip_addr()) {
continue;
}
// Build dial info request url
@ -628,7 +628,7 @@ impl Network {
}
// Register interface dial info
editor_local_network.register_dial_info(di.clone(), DialInfoClass::Direct)?;
registered_addresses.insert(socket_address.to_ip_addr());
registered_addresses.insert(socket_address.ip_addr());
}
// Add static public dialinfo if it's configured

View File

@ -52,7 +52,7 @@ pub struct DummyNetworkConnection {
impl DummyNetworkConnection {
pub fn descriptor(&self) -> ConnectionDescriptor {
self.descriptor.clone()
self.descriptor
}
// pub fn close(&self) -> io::Result<()> {
// Ok(())
@ -144,7 +144,7 @@ impl NetworkConnection {
local_stop_token,
manager_stop_token,
connection_id,
descriptor.clone(),
descriptor,
receiver,
protocol_connection,
stats.clone(),
@ -168,11 +168,11 @@ impl NetworkConnection {
}
pub fn connection_descriptor(&self) -> ConnectionDescriptor {
self.descriptor.clone()
self.descriptor
}
pub fn get_handle(&self) -> ConnectionHandle {
ConnectionHandle::new(self.connection_id, self.descriptor.clone(), self.sender.clone())
ConnectionHandle::new(self.connection_id, self.descriptor, self.sender.clone())
}
pub fn is_protected(&self) -> bool {
@ -197,12 +197,12 @@ impl NetworkConnection {
message: Vec<u8>,
) -> io::Result<NetworkResult<()>> {
let ts = get_aligned_timestamp();
let out = network_result_try!(protocol_connection.send(message).await?);
network_result_try!(protocol_connection.send(message).await?);
let mut stats = stats.lock();
stats.last_message_sent_time.max_assign(Some(ts));
Ok(NetworkResult::Value(out))
Ok(NetworkResult::Value(()))
}
#[cfg_attr(feature="verbose-tracing", instrument(level="trace", skip(stats), fields(ret.len)))]
@ -234,6 +234,7 @@ impl NetworkConnection {
}
// Connection receiver loop
#[allow(clippy::too_many_arguments)]
fn process_connection(
connection_manager: ConnectionManager,
local_stop_token: StopToken,
@ -316,19 +317,19 @@ impl NetworkConnection {
let peer_address = protocol_connection.descriptor().remote();
// Check to see if it is punished
if address_filter.is_ip_addr_punished(peer_address.to_socket_addr().ip()) {
if address_filter.is_ip_addr_punished(peer_address.socket_addr().ip()) {
return RecvLoopAction::Finish;
}
// Check for connection close
if v.is_no_connection() {
log_net!(debug "Connection closed from: {} ({})", peer_address.to_socket_addr(), peer_address.protocol_type());
log_net!(debug "Connection closed from: {} ({})", peer_address.socket_addr(), peer_address.protocol_type());
return RecvLoopAction::Finish;
}
// Punish invalid framing (tcp framing or websocket framing)
if v.is_invalid_message() {
address_filter.punish_ip_addr(peer_address.to_socket_addr().ip());
address_filter.punish_ip_addr(peer_address.socket_addr().ip());
return RecvLoopAction::Finish;
}

View File

@ -338,7 +338,7 @@ impl NetworkManager {
let routing_table = self.routing_table();
// If a node is punished, then don't try to contact it
if target_node_ref.node_ids().iter().find(|nid| self.address_filter().is_node_id_punished(**nid)).is_some() {
if target_node_ref.node_ids().iter().any(|nid| self.address_filter().is_node_id_punished(*nid)) {
return Ok(NodeContactMethod::Unreachable);
}
@ -396,7 +396,7 @@ impl NetworkManager {
dial_info_failures_map.insert(did.dial_info, ts);
}
}
let dif_sort: Option<Arc<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>> = if dial_info_failures_map.is_empty() {
let dif_sort: Option<Arc<DialInfoDetailSort>> = if dial_info_failures_map.is_empty() {
None
} else {
Some(Arc::new(move |a: &DialInfoDetail, b: &DialInfoDetail| {

View File

@ -73,7 +73,7 @@ impl NetworkManager {
inner.stats.clone()
}
pub fn get_veilid_state(&self) -> VeilidStateNetwork {
pub fn get_veilid_state(&self) -> Box<VeilidStateNetwork> {
let has_state = self
.unlocked_inner
.components
@ -83,12 +83,12 @@ impl NetworkManager {
.unwrap_or(false);
if !has_state {
return VeilidStateNetwork {
return Box::new(VeilidStateNetwork {
started: false,
bps_down: 0.into(),
bps_up: 0.into(),
peers: Vec::new(),
};
});
}
let routing_table = self.routing_table();
@ -100,7 +100,7 @@ impl NetworkManager {
)
};
VeilidStateNetwork {
Box::new(VeilidStateNetwork {
started: true,
bps_down,
bps_up,
@ -119,7 +119,7 @@ impl NetworkManager {
}
out
},
}
})
}
pub(super) fn send_network_update(&self) {

View File

@ -11,7 +11,7 @@ impl NetworkManager {
) -> EyreResult<()> {
// go through public_address_inconsistencies_table and time out things that have expired
let mut inner = self.inner.lock();
for (_, pait_v) in &mut inner.public_address_inconsistencies_table {
for pait_v in inner.public_address_inconsistencies_table.values_mut() {
let mut expired = Vec::new();
for (addr, exp_ts) in pait_v.iter() {
if *exp_ts <= cur_ts {
@ -79,7 +79,7 @@ impl NetworkManager {
// Get the ip(block) this report is coming from
let reporting_ipblock = ip_to_ipblock(
ip6_prefix_size,
connection_descriptor.remote_address().to_ip_addr(),
connection_descriptor.remote_address().ip_addr(),
);
// Reject public address reports from nodes that we know are behind symmetric nat or
@ -94,7 +94,7 @@ impl NetworkManager {
// If the socket address reported is the same as the reporter, then this is coming through a relay
// or it should be ignored due to local proximity (nodes on the same network block should not be trusted as
// public ip address reporters, only disinterested parties)
if reporting_ipblock == ip_to_ipblock(ip6_prefix_size, socket_address.to_ip_addr()) {
if reporting_ipblock == ip_to_ipblock(ip6_prefix_size, socket_address.ip_addr()) {
return;
}
@ -192,7 +192,7 @@ impl NetworkManager {
let pait = inner
.public_address_inconsistencies_table
.entry(addr_proto_type_key)
.or_insert_with(|| HashMap::new());
.or_insert_with(HashMap::new);
for i in &inconsistencies {
pait.insert(*i, exp_ts);
}
@ -204,7 +204,7 @@ impl NetworkManager {
let pait = inner
.public_address_inconsistencies_table
.entry(addr_proto_type_key)
.or_insert_with(|| HashMap::new());
.or_insert_with(HashMap::new);
let exp_ts = get_aligned_timestamp()
+ PUBLIC_ADDRESS_INCONSISTENCY_PUNISHMENT_TIMEOUT_US;
for i in inconsistencies {

View File

@ -71,16 +71,16 @@ impl Address {
}
}
}
pub fn to_ip_addr(&self) -> IpAddr {
pub fn ip_addr(&self) -> IpAddr {
match self {
Self::IPV4(a) => IpAddr::V4(*a),
Self::IPV6(a) => IpAddr::V6(*a),
}
}
pub fn to_socket_addr(&self, port: u16) -> SocketAddr {
SocketAddr::new(self.to_ip_addr(), port)
pub fn socket_addr(&self, port: u16) -> SocketAddr {
SocketAddr::new(self.ip_addr(), port)
}
pub fn to_canonical(&self) -> Address {
pub fn canonical(&self) -> Address {
match self {
Address::IPV4(v4) => Address::IPV4(*v4),
Address::IPV6(v6) => match v6.to_ipv4() {

View File

@ -1,7 +1,7 @@
#![allow(non_snake_case)]
use super::*;
#[allow(clippy::derive_hash_xor_eq)]
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Debug, PartialOrd, Ord, Hash, Serialize, Deserialize, EnumSetType)]
#[enumset(repr = "u8")]
pub enum AddressType {

View File

@ -36,10 +36,10 @@ impl fmt::Display for DialInfo {
let split_url = SplitUrl::from_str(&url).unwrap();
match split_url.host {
SplitUrlHost::Hostname(_) => {
write!(f, "ws|{}|{}", di.socket_address.to_ip_addr(), di.request)
write!(f, "ws|{}|{}", di.socket_address.ip_addr(), di.request)
}
SplitUrlHost::IpAddr(a) => {
if di.socket_address.to_ip_addr() == a {
if di.socket_address.ip_addr() == a {
write!(f, "ws|{}", di.request)
} else {
panic!("resolved address does not match url: {}", di.request);
@ -52,7 +52,7 @@ impl fmt::Display for DialInfo {
let split_url = SplitUrl::from_str(&url).unwrap();
match split_url.host {
SplitUrlHost::Hostname(_) => {
write!(f, "wss|{}|{}", di.socket_address.to_ip_addr(), di.request)
write!(f, "wss|{}|{}", di.socket_address.ip_addr(), di.request)
}
SplitUrlHost::IpAddr(_) => {
panic!(
@ -143,22 +143,22 @@ impl FromStr for DialInfo {
impl DialInfo {
pub fn udp_from_socketaddr(socket_addr: SocketAddr) -> Self {
Self::UDP(DialInfoUDP {
socket_address: SocketAddress::from_socket_addr(socket_addr).to_canonical(),
socket_address: SocketAddress::from_socket_addr(socket_addr).canonical(),
})
}
pub fn tcp_from_socketaddr(socket_addr: SocketAddr) -> Self {
Self::TCP(DialInfoTCP {
socket_address: SocketAddress::from_socket_addr(socket_addr).to_canonical(),
socket_address: SocketAddress::from_socket_addr(socket_addr).canonical(),
})
}
pub fn udp(socket_address: SocketAddress) -> Self {
Self::UDP(DialInfoUDP {
socket_address: socket_address.to_canonical(),
socket_address: socket_address.canonical(),
})
}
pub fn tcp(socket_address: SocketAddress) -> Self {
Self::TCP(DialInfoTCP {
socket_address: socket_address.to_canonical(),
socket_address: socket_address.canonical(),
})
}
pub fn try_ws(socket_address: SocketAddress, url: String) -> VeilidAPIResult<Self> {
@ -173,7 +173,7 @@ impl DialInfo {
apibail_parse_error!("socket address port doesn't match url port", url);
}
if let SplitUrlHost::IpAddr(a) = split_url.host {
if socket_address.to_ip_addr() != a {
if socket_address.ip_addr() != a {
apibail_parse_error!(
format!("request address does not match socket address: {}", a),
socket_address
@ -181,7 +181,7 @@ impl DialInfo {
}
}
Ok(Self::WS(DialInfoWS {
socket_address: socket_address.to_canonical(),
socket_address: socket_address.canonical(),
request: url[5..].to_string(),
}))
}
@ -203,7 +203,7 @@ impl DialInfo {
);
}
Ok(Self::WSS(DialInfoWSS {
socket_address: socket_address.to_canonical(),
socket_address: socket_address.canonical(),
request: url[6..].to_string(),
}))
}
@ -242,12 +242,12 @@ impl DialInfo {
Self::WSS(di) => di.socket_address,
}
}
pub fn to_ip_addr(&self) -> IpAddr {
pub fn ip_addr(&self) -> IpAddr {
match self {
Self::UDP(di) => di.socket_address.to_ip_addr(),
Self::TCP(di) => di.socket_address.to_ip_addr(),
Self::WS(di) => di.socket_address.to_ip_addr(),
Self::WSS(di) => di.socket_address.to_ip_addr(),
Self::UDP(di) => di.socket_address.ip_addr(),
Self::TCP(di) => di.socket_address.ip_addr(),
Self::WS(di) => di.socket_address.ip_addr(),
Self::WSS(di) => di.socket_address.ip_addr(),
}
}
pub fn port(&self) -> u16 {
@ -268,13 +268,13 @@ impl DialInfo {
}
pub fn to_socket_addr(&self) -> SocketAddr {
match self {
Self::UDP(di) => di.socket_address.to_socket_addr(),
Self::TCP(di) => di.socket_address.to_socket_addr(),
Self::WS(di) => di.socket_address.to_socket_addr(),
Self::WSS(di) => di.socket_address.to_socket_addr(),
Self::UDP(di) => di.socket_address.socket_addr(),
Self::TCP(di) => di.socket_address.socket_addr(),
Self::WS(di) => di.socket_address.socket_addr(),
Self::WSS(di) => di.socket_address.socket_addr(),
}
}
pub fn to_peer_address(&self) -> PeerAddress {
pub fn peer_address(&self) -> PeerAddress {
match self {
Self::UDP(di) => PeerAddress::new(di.socket_address, ProtocolType::UDP),
Self::TCP(di) => PeerAddress::new(di.socket_address, ProtocolType::TCP),
@ -376,11 +376,11 @@ impl DialInfo {
"udp" => Self::udp_from_socketaddr(sa),
"tcp" => Self::tcp_from_socketaddr(sa),
"ws" => Self::try_ws(
SocketAddress::from_socket_addr(sa).to_canonical(),
SocketAddress::from_socket_addr(sa).canonical(),
url.to_string(),
)?,
"wss" => Self::try_wss(
SocketAddress::from_socket_addr(sa).to_canonical(),
SocketAddress::from_socket_addr(sa).canonical(),
url.to_string(),
)?,
_ => {
@ -395,13 +395,13 @@ impl DialInfo {
match self {
DialInfo::UDP(di) => (
format!("U{}", di.socket_address.port()),
intf::ptr_lookup(di.socket_address.to_ip_addr())
intf::ptr_lookup(di.socket_address.ip_addr())
.await
.unwrap_or_else(|_| di.socket_address.to_string()),
),
DialInfo::TCP(di) => (
format!("T{}", di.socket_address.port()),
intf::ptr_lookup(di.socket_address.to_ip_addr())
intf::ptr_lookup(di.socket_address.ip_addr())
.await
.unwrap_or_else(|_| di.socket_address.to_string()),
),
@ -447,11 +447,11 @@ impl DialInfo {
}
pub async fn to_url(&self) -> String {
match self {
DialInfo::UDP(di) => intf::ptr_lookup(di.socket_address.to_ip_addr())
DialInfo::UDP(di) => intf::ptr_lookup(di.socket_address.ip_addr())
.await
.map(|h| format!("udp://{}:{}", h, di.socket_address.port()))
.unwrap_or_else(|_| format!("udp://{}", di.socket_address)),
DialInfo::TCP(di) => intf::ptr_lookup(di.socket_address.to_ip_addr())
DialInfo::TCP(di) => intf::ptr_lookup(di.socket_address.ip_addr())
.await
.map(|h| format!("tcp://{}:{}", h, di.socket_address.port()))
.unwrap_or_else(|_| format!("tcp://{}", di.socket_address)),

View File

@ -4,7 +4,7 @@ use super::*;
// Keep member order appropriate for sorting < preference
// Must match DialInfo order
#[allow(clippy::derive_hash_xor_eq)]
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Debug, PartialOrd, Ord, Hash, EnumSetType, Serialize, Deserialize)]
#[enumset(repr = "u8")]
pub enum LowLevelProtocolType {

View File

@ -10,7 +10,7 @@ pub struct PeerAddress {
impl PeerAddress {
pub fn new(socket_address: SocketAddress, protocol_type: ProtocolType) -> Self {
Self {
socket_address: socket_address.to_canonical(),
socket_address: socket_address.canonical(),
protocol_type,
}
}
@ -23,8 +23,8 @@ impl PeerAddress {
self.protocol_type
}
pub fn to_socket_addr(&self) -> SocketAddr {
self.socket_address.to_socket_addr()
pub fn socket_addr(&self) -> SocketAddr {
self.socket_address.socket_addr()
}
pub fn address_type(&self) -> AddressType {
@ -42,7 +42,10 @@ impl FromStr for PeerAddress {
type Err = VeilidAPIError;
fn from_str(s: &str) -> VeilidAPIResult<PeerAddress> {
let Some((first, second)) = s.split_once(':') else {
return Err(VeilidAPIError::parse_error("PeerAddress is missing a colon: {}", s));
return Err(VeilidAPIError::parse_error(
"PeerAddress is missing a colon: {}",
s,
));
};
let protocol_type = ProtocolType::from_str(first)?;
let socket_address = SocketAddress::from_str(second)?;

View File

@ -3,7 +3,7 @@ use super::*;
// Keep member order appropriate for sorting < preference
// Must match DialInfo order
#[allow(clippy::derive_hash_xor_eq)]
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Debug, PartialOrd, Ord, Hash, EnumSetType, Serialize, Deserialize)]
#[enumset(repr = "u8")]
pub enum ProtocolType {

View File

@ -34,27 +34,27 @@ impl SocketAddress {
self.port = port
}
pub fn with_port(&self, port: u16) -> Self {
let mut sa = self.clone();
let mut sa = *self;
sa.port = port;
sa
}
pub fn to_canonical(&self) -> SocketAddress {
pub fn canonical(&self) -> SocketAddress {
SocketAddress {
address: self.address.to_canonical(),
address: self.address.canonical(),
port: self.port,
}
}
pub fn to_ip_addr(&self) -> IpAddr {
self.address.to_ip_addr()
pub fn ip_addr(&self) -> IpAddr {
self.address.ip_addr()
}
pub fn to_socket_addr(&self) -> SocketAddr {
self.address.to_socket_addr(self.port)
pub fn socket_addr(&self) -> SocketAddr {
self.address.socket_addr(self.port)
}
}
impl fmt::Display for SocketAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_socket_addr())
write!(f, "{}", self.socket_addr())
}
}

View File

@ -32,18 +32,18 @@ pub const PUBLIC_INTERNET_CAPABILITIES: [Capability; PUBLIC_INTERNET_CAPABILITIE
CAP_BLOCKSTORE,
];
#[cfg(feature = "unstable-blockstore")]
const LOCAL_NETWORK_CAPABILITIES_LEN: usize = 3;
#[cfg(not(feature = "unstable-blockstore"))]
const LOCAL_NETWORK_CAPABILITIES_LEN: usize = 2;
// #[cfg(feature = "unstable-blockstore")]
// const LOCAL_NETWORK_CAPABILITIES_LEN: usize = 3;
// #[cfg(not(feature = "unstable-blockstore"))]
// const LOCAL_NETWORK_CAPABILITIES_LEN: usize = 2;
pub const LOCAL_NETWORK_CAPABILITIES: [Capability; LOCAL_NETWORK_CAPABILITIES_LEN] = [
//CAP_RELAY,
CAP_DHT,
CAP_APPMESSAGE,
#[cfg(feature = "unstable-blockstore")]
CAP_BLOCKSTORE,
];
// pub const LOCAL_NETWORK_CAPABILITIES: [Capability; LOCAL_NETWORK_CAPABILITIES_LEN] = [
// //CAP_RELAY,
// CAP_DHT,
// CAP_APPMESSAGE,
// #[cfg(feature = "unstable-blockstore")]
// CAP_BLOCKSTORE,
// ];
pub const MAX_CAPABILITIES: usize = 64;
@ -149,7 +149,7 @@ impl Network {
if self
.network_manager()
.address_filter()
.is_ip_addr_punished(dial_info.address().to_ip_addr())
.is_ip_addr_punished(dial_info.address().ip_addr())
{
return Ok(NetworkResult::no_connection_other("punished"));
}
@ -173,7 +173,7 @@ impl Network {
// Network accounting
self.network_manager()
.stats_packet_sent(dial_info.to_ip_addr(), ByteCount::new(data_len as u64));
.stats_packet_sent(dial_info.ip_addr(), ByteCount::new(data_len as u64));
Ok(NetworkResult::Value(()))
})
@ -202,7 +202,7 @@ impl Network {
if self
.network_manager()
.address_filter()
.is_ip_addr_punished(dial_info.address().to_ip_addr())
.is_ip_addr_punished(dial_info.address().ip_addr())
{
return Ok(NetworkResult::no_connection_other("punished"));
}
@ -227,7 +227,7 @@ impl Network {
network_result_try!(pnc.send(data).await.wrap_err("send failure")?);
self.network_manager()
.stats_packet_sent(dial_info.to_ip_addr(), ByteCount::new(data_len as u64));
.stats_packet_sent(dial_info.ip_addr(), ByteCount::new(data_len as u64));
let out =
network_result_try!(network_result_try!(timeout(timeout_ms, pnc.recv())
@ -235,10 +235,8 @@ impl Network {
.into_network_result())
.wrap_err("recv failure")?);
self.network_manager().stats_packet_rcvd(
dial_info.to_ip_addr(),
ByteCount::new(out.len() as u64),
);
self.network_manager()
.stats_packet_rcvd(dial_info.ip_addr(), ByteCount::new(out.len() as u64));
Ok(NetworkResult::Value(out))
}
@ -273,7 +271,7 @@ impl Network {
ConnectionHandleSendResult::Sent => {
// Network accounting
self.network_manager().stats_packet_sent(
descriptor.remote().to_socket_addr().ip(),
descriptor.remote().socket_addr().ip(),
ByteCount::new(data_len as u64),
);
@ -324,7 +322,7 @@ impl Network {
// Network accounting
self.network_manager()
.stats_packet_sent(dial_info.to_ip_addr(), ByteCount::new(data_len as u64));
.stats_packet_sent(dial_info.ip_addr(), ByteCount::new(data_len as u64));
Ok(NetworkResult::value(connection_descriptor))
})
@ -434,11 +432,11 @@ impl Network {
Vec::new()
}
pub fn get_local_port(&self, protocol_type: ProtocolType) -> Option<u16> {
pub fn get_local_port(&self, _protocol_type: ProtocolType) -> Option<u16> {
None
}
pub fn get_preferred_local_address(&self, dial_info: &DialInfo) -> Option<SocketAddr> {
pub fn get_preferred_local_address(&self, _dial_info: &DialInfo) -> Option<SocketAddr> {
None
}
@ -456,7 +454,7 @@ impl Network {
}
pub fn get_protocol_config(&self) -> ProtocolConfig {
self.inner.lock().protocol_config.clone()
self.inner.lock().protocol_config
}
//////////////////////////////////////////

View File

@ -19,7 +19,7 @@ impl ProtocolNetworkConnection {
timeout_ms: u32,
address_filter: AddressFilter,
) -> io::Result<NetworkResult<ProtocolNetworkConnection>> {
if address_filter.is_ip_addr_punished(dial_info.address().to_ip_addr()) {
if address_filter.is_ip_addr_punished(dial_info.address().ip_addr()) {
return Ok(NetworkResult::no_connection_other("punished"));
}
match dial_info.protocol_type() {

View File

@ -56,7 +56,7 @@ impl WebsocketNetworkConnection {
}
pub fn descriptor(&self) -> ConnectionDescriptor {
self.descriptor.clone()
self.descriptor
}
// #[instrument(level = "trace", err, skip(self))]
@ -144,7 +144,7 @@ impl WebsocketProtocolHandler {
// Make our connection descriptor
let wnc = WebsocketNetworkConnection::new(
ConnectionDescriptor::new_no_local(dial_info.to_peer_address()),
ConnectionDescriptor::new_no_local(dial_info.peer_address()),
wsmeta,
wsio,
);

View File

@ -261,9 +261,8 @@ impl ReceiptManager {
// Wait on all the multi-call callbacks
loop {
match callbacks.next().timeout_at(stop_token.clone()).await {
Ok(Some(_)) => {}
Ok(None) | Err(_) => break,
if let Ok(None) | Err(_) = callbacks.next().timeout_at(stop_token.clone()).await {
break;
}
}
}
@ -307,7 +306,7 @@ impl ReceiptManager {
// Wait for everything to stop
debug!("waiting for timeout task to stop");
if !timeout_task.join().await.is_ok() {
if timeout_task.join().await.is_err() {
panic!("joining timeout task failed");
}
@ -333,7 +332,7 @@ impl ReceiptManager {
let mut inner = self.inner.lock();
inner.records_by_nonce.insert(receipt_nonce, record);
Self::update_next_oldest_timestamp(&mut *inner);
Self::update_next_oldest_timestamp(&mut inner);
}
pub fn record_single_shot_receipt(
@ -351,7 +350,7 @@ impl ReceiptManager {
let mut inner = self.inner.lock();
inner.records_by_nonce.insert(receipt_nonce, record);
Self::update_next_oldest_timestamp(&mut *inner);
Self::update_next_oldest_timestamp(&mut inner);
}
fn update_next_oldest_timestamp(inner: &mut ReceiptManagerInner) {
@ -382,7 +381,7 @@ impl ReceiptManager {
bail!("receipt not recorded");
}
};
Self::update_next_oldest_timestamp(&mut *inner);
Self::update_next_oldest_timestamp(&mut inner);
record
};
@ -448,14 +447,12 @@ impl ReceiptManager {
let receipt_event = match receipt_returned {
ReceiptReturned::OutOfBand => ReceiptEvent::ReturnedOutOfBand,
ReceiptReturned::Safety => ReceiptEvent::ReturnedSafety,
ReceiptReturned::InBand {
ref inbound_noderef,
} => ReceiptEvent::ReturnedInBand {
inbound_noderef: inbound_noderef.clone(),
},
ReceiptReturned::Private { ref private_route } => ReceiptEvent::ReturnedPrivate {
private_route: private_route.clone(),
},
ReceiptReturned::InBand { inbound_noderef } => {
ReceiptEvent::ReturnedInBand { inbound_noderef }
}
ReceiptReturned::Private { private_route } => {
ReceiptEvent::ReturnedPrivate { private_route }
}
};
let callback_future = Self::perform_callback(receipt_event, &mut record_mut);
@ -464,7 +461,7 @@ impl ReceiptManager {
if record_mut.returns_so_far == record_mut.expected_returns {
inner.records_by_nonce.remove(&receipt_nonce);
Self::update_next_oldest_timestamp(&mut *inner);
Self::update_next_oldest_timestamp(&mut inner);
}
(callback_future, stop_token)
};

View File

@ -75,8 +75,8 @@ impl Bucket {
});
}
let bucket_data = SerializedBucketData { entries };
let out = serialize_json_bytes(&bucket_data);
out
serialize_json_bytes(bucket_data)
}
/// Create a new entry with a node_id of this crypto kind and return it
@ -129,11 +129,8 @@ impl Bucket {
let mut extra_entries = bucket_len - bucket_depth;
// Get the sorted list of entries by their kick order
let mut sorted_entries: Vec<(PublicKey, Arc<BucketEntry>)> = self
.entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let mut sorted_entries: Vec<(PublicKey, Arc<BucketEntry>)> =
self.entries.iter().map(|(k, v)| (*k, v.clone())).collect();
let cur_ts = get_aligned_timestamp();
sorted_entries.sort_by(|a, b| -> core::cmp::Ordering {
if a.0 == b.0 {

View File

@ -223,7 +223,7 @@ impl BucketEntryInner {
// Lower timestamp to the front, recent or no timestamp is at the end
if let Some(e1_ts) = &e1.peer_stats.rpc_stats.first_consecutive_seen_ts {
if let Some(e2_ts) = &e2.peer_stats.rpc_stats.first_consecutive_seen_ts {
e1_ts.cmp(&e2_ts)
e1_ts.cmp(e2_ts)
} else {
std::cmp::Ordering::Less
}
@ -437,7 +437,7 @@ impl BucketEntryInner {
// Clears the table of last connections except the most recent one
pub fn clear_last_connections_except_latest(&mut self) {
if self.last_connections.len() == 0 {
if self.last_connections.is_empty() {
// No last_connections
return;
}
@ -454,7 +454,7 @@ impl BucketEntryInner {
let Some(most_recent_connection) = most_recent_connection else {
return;
};
for (k, _) in &self.last_connections {
for k in self.last_connections.keys() {
if k != most_recent_connection {
dead_keys.push(k.clone());
}
@ -492,7 +492,7 @@ impl BucketEntryInner {
}
if !only_live {
return Some(v.clone());
return Some(*v);
}
// Check if the connection is still considered live
@ -509,7 +509,7 @@ impl BucketEntryInner {
};
if alive {
Some(v.clone())
Some(*v)
} else {
None
}
@ -583,13 +583,11 @@ impl BucketEntryInner {
RoutingDomain::LocalNetwork => self
.local_network
.node_status
.as_ref()
.map(|ns| ns.clone()),
.as_ref().cloned(),
RoutingDomain::PublicInternet => self
.public_internet
.node_status
.as_ref()
.map(|ns| ns.clone()),
.as_ref().cloned()
}
}
@ -892,7 +890,7 @@ impl BucketEntry {
F: FnOnce(&RoutingTableInner, &BucketEntryInner) -> R,
{
let inner = self.inner.read();
f(rti, &*inner)
f(rti, &inner)
}
// Note, that this requires -also- holding the RoutingTable write lock, as a
@ -902,7 +900,7 @@ impl BucketEntry {
F: FnOnce(&mut RoutingTableInner, &mut BucketEntryInner) -> R,
{
let mut inner = self.inner.write();
f(rti, &mut *inner)
f(rti, &mut inner)
}
// Internal inner access for RoutingTableInner only
@ -911,7 +909,7 @@ impl BucketEntry {
F: FnOnce(&BucketEntryInner) -> R,
{
let inner = self.inner.read();
f(&*inner)
f(&inner)
}
// Internal inner access for RoutingTableInner only
@ -920,7 +918,7 @@ impl BucketEntry {
F: FnOnce(&mut BucketEntryInner) -> R,
{
let mut inner = self.inner.write();
f(&mut *inner)
f(&mut inner)
}
}

View File

@ -112,7 +112,7 @@ impl RoutingTable {
let mut out = String::new();
out += &format!("Entries: {}\n", inner.bucket_entry_count());
out += &format!(" Live:\n");
out += " Live:\n";
for ec in inner.cached_entry_counts() {
let routing_domain = ec.0 .0;
let crypto_kind = ec.0 .1;

View File

@ -129,7 +129,7 @@ impl RoutingTableUnlockedInner {
where
F: FnOnce(&VeilidConfigInner) -> R,
{
f(&*self.config.get())
f(&self.config.get())
}
pub fn node_id(&self, kind: CryptoKind) -> TypedKey {
@ -388,11 +388,15 @@ impl RoutingTable {
}
// Caches valid, load saved routing table
let Some(serialized_bucket_map): Option<SerializedBucketMap> = db.load_json(0, SERIALIZED_BUCKET_MAP).await? else {
let Some(serialized_bucket_map): Option<SerializedBucketMap> =
db.load_json(0, SERIALIZED_BUCKET_MAP).await?
else {
log_rtab!(debug "no bucket map in saved routing table");
return Ok(());
};
let Some(all_entry_bytes): Option<SerializedBuckets> = db.load_json(0, ALL_ENTRY_BYTES).await? else {
let Some(all_entry_bytes): Option<SerializedBuckets> =
db.load_json(0, ALL_ENTRY_BYTES).await?
else {
log_rtab!(debug "no all_entry_bytes in saved routing table");
return Ok(());
};
@ -537,7 +541,7 @@ impl RoutingTable {
peer_b: &PeerInfo,
dial_info_filter: DialInfoFilter,
sequencing: Sequencing,
dif_sort: Option<Arc<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>>,
dif_sort: Option<Arc<DialInfoDetailSort>>,
) -> ContactMethod {
self.inner.read().get_contact_method(
routing_domain,
@ -881,7 +885,7 @@ impl RoutingTable {
crypto_kind: CryptoKind,
max_per_type: usize,
) -> Vec<NodeRef> {
let protocol_types = vec![
let protocol_types = [
ProtocolType::UDP,
ProtocolType::TCP,
ProtocolType::WS,
@ -889,8 +893,8 @@ impl RoutingTable {
];
let protocol_types_len = protocol_types.len();
let mut nodes_proto_v4 = vec![0usize, 0usize, 0usize, 0usize];
let mut nodes_proto_v6 = vec![0usize, 0usize, 0usize, 0usize];
let mut nodes_proto_v4 = [0usize, 0usize, 0usize, 0usize];
let mut nodes_proto_v6 = [0usize, 0usize, 0usize, 0usize];
let filter = Box::new(
move |rti: &RoutingTableInner, entry: Option<Arc<BucketEntry>>| {

View File

@ -85,7 +85,7 @@ pub trait NodeRefBase: Sized {
self.common()
.filter
.as_ref()
.map(|f| f.dial_info_filter.clone())
.map(|f| f.dial_info_filter)
.unwrap_or(DialInfoFilter::all())
}
@ -283,7 +283,7 @@ pub trait NodeRefBase: Sized {
self.operate(|rti, e| {
// apply sequencing to filter and get sort
let sequencing = self.common().sequencing;
let filter = self.common().filter.clone().unwrap_or_default();
let filter = self.common().filter.unwrap_or_default();
let (ordered, filter) = filter.with_sequencing(sequencing);
let mut last_connections = e.last_connections(rti, true, filter);
@ -444,7 +444,7 @@ impl Clone for NodeRef {
common: NodeRefBaseCommon {
routing_table: self.common.routing_table.clone(),
entry: self.common.entry.clone(),
filter: self.common.filter.clone(),
filter: self.common.filter,
sequencing: self.common.sequencing,
#[cfg(feature = "tracking")]
track_id: self.common.entry.write().track(),

View File

@ -18,7 +18,7 @@ pub enum RouteNode {
/// Route node is optimized, no contact method information as this node id has been seen before
NodeId(PublicKey),
/// Route node with full contact method information to ensure the peer is reachable
PeerInfo(PeerInfo),
PeerInfo(Box<PeerInfo>),
}
impl RouteNode {
@ -41,7 +41,7 @@ impl RouteNode {
Ok(nr) => nr,
Err(e) => {
log_rtab!(debug "failed to look up route node: {}", e);
return None;
None
}
}
}
@ -49,13 +49,13 @@ impl RouteNode {
//
match routing_table.register_node_with_peer_info(
RoutingDomain::PublicInternet,
pi.clone(),
*pi.clone(),
false,
) {
Ok(nr) => Some(nr),
Err(e) => {
log_rtab!(debug "failed to register route node: {}", e);
return None;
None
}
}
}
@ -95,7 +95,7 @@ impl RouteHop {
#[derive(Clone, Debug)]
pub enum PrivateRouteHops {
/// The first hop of a private route, unencrypted, route_hops == total hop count
FirstHop(RouteHop),
FirstHop(Box<RouteHop>),
/// Private route internal node. Has > 0 private route hops left but < total hop count
Data(RouteHopData),
/// Private route has ended (hop count = 0)
@ -134,10 +134,10 @@ impl PrivateRoute {
Self {
public_key,
hop_count: 1,
hops: PrivateRouteHops::FirstHop(RouteHop {
hops: PrivateRouteHops::FirstHop(Box::new(RouteHop {
node,
next_hop: None,
}),
})),
}
}
@ -177,10 +177,10 @@ impl PrivateRoute {
None => PrivateRouteHops::Empty,
};
return Some(first_hop_node);
Some(first_hop_node)
}
PrivateRouteHops::Data(_) => return None,
PrivateRouteHops::Empty => return None,
PrivateRouteHops::Data(_) => None,
PrivateRouteHops::Empty => None,
}
}

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,7 @@ fn _get_route_permutation_count(hop_count: usize) -> usize {
// more than two nodes has factorial permutation
// hop_count = 3 -> 2! -> 2
// hop_count = 4 -> 3! -> 6
(3..hop_count).into_iter().fold(2usize, |acc, x| acc * x)
(3..hop_count).fold(2usize, |acc, x| acc * x)
}
pub type PermReturnType = (Vec<usize>, bool);
pub type PermFunc<'t> = Box<dyn FnMut(&[usize]) -> Option<PermReturnType> + Send + 't>;
@ -47,7 +47,7 @@ pub fn with_route_permutations(
f: &mut PermFunc,
) -> Option<PermReturnType> {
if size == 1 {
return f(&permutation);
return f(permutation);
}
for i in 0..size {

View File

@ -112,7 +112,7 @@ impl RouteSetSpecDetail {
}
pub fn contains_nodes(&self, nodes: &[TypedKey]) -> bool {
for tk in nodes {
for (_pk, rsd) in &self.route_set {
for rsd in self.route_set.values() {
if rsd.crypto_kind == tk.kind && rsd.hops.contains(&tk.value) {
return true;
}

View File

@ -144,7 +144,7 @@ impl RouteSpecStoreCache {
// also store in id by key table
for private_route in rprinfo.get_private_routes() {
self.remote_private_routes_by_key
.insert(private_route.public_key.value, id.clone());
.insert(private_route.public_key.value, id);
}
let mut dead = None;

View File

@ -29,18 +29,20 @@ impl RouteSpecStoreContent {
for (rsid, rssd) in content.details.iter_mut() {
// Get best route since they all should resolve
let Some(pk) = rssd.get_best_route_set_key() else {
dead_ids.push(rsid.clone());
dead_ids.push(*rsid);
continue;
};
let Some(rsd) = rssd.get_route_by_key(&pk) else {
dead_ids.push(rsid.clone());
dead_ids.push(*rsid);
continue;
};
// Go through best route and resolve noderefs
let mut hop_node_refs = Vec::with_capacity(rsd.hops.len());
for h in &rsd.hops {
let Ok(Some(nr)) = routing_table.lookup_node_ref(TypedKey::new(rsd.crypto_kind, *h)) else {
dead_ids.push(rsid.clone());
let Ok(Some(nr)) =
routing_table.lookup_node_ref(TypedKey::new(rsd.crypto_kind, *h))
else {
dead_ids.push(*rsid);
break;
};
hop_node_refs.push(nr);
@ -72,14 +74,14 @@ impl RouteSpecStoreContent {
// also store in id by key table
for (pk, _) in detail.iter_route_set() {
self.id_by_key.insert(*pk, id.clone());
self.id_by_key.insert(*pk, id);
}
self.details.insert(id.clone(), detail);
self.details.insert(id, detail);
}
pub fn remove_detail(&mut self, id: &RouteId) -> Option<RouteSetSpecDetail> {
let detail = self.details.remove(id)?;
for (pk, _) in detail.iter_route_set() {
self.id_by_key.remove(&pk).unwrap();
self.id_by_key.remove(pk).unwrap();
}
Some(detail)
}
@ -106,7 +108,7 @@ impl RouteSpecStoreContent {
/// Resets publication status and statistics for when our node info changes
/// Routes must be republished
pub fn reset_details(&mut self) {
for (_k, v) in &mut self.details {
for v in self.details.values_mut() {
// Must republish route now
v.set_published(false);
// Restart stats for routes so we test the route again

View File

@ -258,11 +258,9 @@ impl RoutingDomainEditor {
}
}
// Clear the routespecstore cache if our PublicInternet dial info has changed
if changed {
if self.routing_domain == RoutingDomain::PublicInternet {
if changed && self.routing_domain == RoutingDomain::PublicInternet {
let rss = self.routing_table.route_spec_store();
rss.reset();
}
}
}
}

View File

@ -250,7 +250,7 @@ pub trait RoutingDomainDetail {
peer_b: &PeerInfo,
dial_info_filter: DialInfoFilter,
sequencing: Sequencing,
dif_sort: Option<Arc<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>>,
dif_sort: Option<Arc<DialInfoDetailSort>>,
) -> ContactMethod;
}
@ -276,9 +276,9 @@ fn first_filtered_dial_info_detail_between_nodes(
to_node: &NodeInfo,
dial_info_filter: &DialInfoFilter,
sequencing: Sequencing,
dif_sort: Option<Arc<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>>
dif_sort: Option<Arc<DialInfoDetailSort>>
) -> Option<DialInfoDetail> {
let dial_info_filter = dial_info_filter.clone().filtered(
let dial_info_filter = (*dial_info_filter).filtered(
&DialInfoFilter::all()
.with_address_type_set(from_node.address_types())
.with_protocol_type_set(from_node.outbound_protocols()),
@ -289,7 +289,7 @@ fn first_filtered_dial_info_detail_between_nodes(
// based on an external preference table, for example the one kept by
// AddressFilter to deprioritize dialinfo that have recently failed to connect
let (ordered, dial_info_filter) = dial_info_filter.with_sequencing(sequencing);
let sort: Option<Box<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>> = if ordered {
let sort: Option<Box<DialInfoDetailSort>> = if ordered {
if let Some(dif_sort) = dif_sort {
Some(Box::new(move |a, b| {
let mut ord = dif_sort(a,b);
@ -301,12 +301,10 @@ fn first_filtered_dial_info_detail_between_nodes(
} else {
Some(Box::new(move |a,b| { DialInfoDetail::ordered_sequencing_sort(a,b) }))
}
} else {
if let Some(dif_sort) = dif_sort {
} else if let Some(dif_sort) = dif_sort {
Some(Box::new(move |a,b| { dif_sort(a,b) }))
} else {
None
}
};
// If the filter is dead then we won't be able to connect
@ -336,7 +334,7 @@ impl RoutingDomainDetail for PublicInternetRoutingDomainDetail {
peer_b: &PeerInfo,
dial_info_filter: DialInfoFilter,
sequencing: Sequencing,
dif_sort: Option<Arc<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>>,
dif_sort: Option<Arc<DialInfoDetailSort>>,
) -> ContactMethod {
// Get the nodeinfos for convenience
let node_a = peer_a.signed_node_info().node_info();
@ -401,8 +399,8 @@ impl RoutingDomainDetail for PublicInternetRoutingDomainDetail {
dif_sort.clone()
) {
// Ensure we aren't on the same public IP address (no hairpin nat)
if reverse_did.dial_info.to_ip_addr()
!= target_did.dial_info.to_ip_addr()
if reverse_did.dial_info.ip_addr()
!= target_did.dial_info.ip_addr()
{
// Can we receive a direct reverse connection?
if !reverse_did.class.requires_signal() {
@ -418,7 +416,6 @@ impl RoutingDomainDetail for PublicInternetRoutingDomainDetail {
// Does node B have a direct udp dialinfo node A can reach?
let udp_dial_info_filter = dial_info_filter
.clone()
.filtered(&DialInfoFilter::all().with_protocol_type(ProtocolType::UDP));
if let Some(target_udp_did) = first_filtered_dial_info_detail_between_nodes(
node_a,
@ -436,8 +433,8 @@ impl RoutingDomainDetail for PublicInternetRoutingDomainDetail {
dif_sort.clone(),
) {
// Ensure we aren't on the same public IP address (no hairpin nat)
if reverse_udp_did.dial_info.to_ip_addr()
!= target_udp_did.dial_info.to_ip_addr()
if reverse_udp_did.dial_info.ip_addr()
!= target_udp_did.dial_info.ip_addr()
{
// The target and ourselves have a udp dialinfo that they can reach
return ContactMethod::SignalHolePunch(
@ -473,7 +470,7 @@ impl RoutingDomainDetail for PublicInternetRoutingDomainDetail {
// Can we reach the inbound relay?
if first_filtered_dial_info_detail_between_nodes(
node_a,
&node_b_relay,
node_b_relay,
&dial_info_filter,
sequencing,
dif_sort.clone()
@ -554,7 +551,7 @@ impl RoutingDomainDetail for LocalNetworkRoutingDomainDetail {
&mut self.common
}
fn can_contain_address(&self, address: Address) -> bool {
let ip = address.to_ip_addr();
let ip = address.ip_addr();
for localnet in &self.local_networks {
if ipaddr_in_network(ip, localnet.0, localnet.1) {
return true;
@ -570,7 +567,7 @@ impl RoutingDomainDetail for LocalNetworkRoutingDomainDetail {
peer_b: &PeerInfo,
dial_info_filter: DialInfoFilter,
sequencing: Sequencing,
dif_sort: Option<Arc<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>>,
dif_sort: Option<Arc<DialInfoDetailSort>>,
) -> ContactMethod {
// Scope the filter down to protocols node A can do outbound
let dial_info_filter = dial_info_filter.filtered(
@ -584,7 +581,7 @@ impl RoutingDomainDetail for LocalNetworkRoutingDomainDetail {
// based on an external preference table, for example the one kept by
// AddressFilter to deprioritize dialinfo that have recently failed to connect
let (ordered, dial_info_filter) = dial_info_filter.with_sequencing(sequencing);
let sort: Option<Box<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>> = if ordered {
let sort: Option<Box<DialInfoDetailSort>> = if ordered {
if let Some(dif_sort) = dif_sort {
Some(Box::new(move |a, b| {
let mut ord = dif_sort(a,b);
@ -596,12 +593,10 @@ impl RoutingDomainDetail for LocalNetworkRoutingDomainDetail {
} else {
Some(Box::new(move |a,b| { DialInfoDetail::ordered_sequencing_sort(a,b) }))
}
} else {
if let Some(dif_sort) = dif_sort {
} else if let Some(dif_sort) = dif_sort {
Some(Box::new(move |a,b| { dif_sort(a,b) }))
} else {
None
}
};
// If the filter is dead then we won't be able to connect

View File

@ -227,7 +227,7 @@ impl RoutingTableInner {
peer_b: &PeerInfo,
dial_info_filter: DialInfoFilter,
sequencing: Sequencing,
dif_sort: Option<Arc<dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering>>,
dif_sort: Option<Arc<DialInfoDetailSort>>,
) -> ContactMethod {
self.with_routing_domain(routing_domain, |rdd| {
rdd.get_contact_method(self, peer_a, peer_b, dial_info_filter, sequencing, dif_sort)
@ -543,18 +543,17 @@ impl RoutingTableInner {
// Collect all entries that are 'needs_ping' and have some node info making them reachable somehow
let mut node_refs = Vec::<NodeRef>::with_capacity(self.bucket_entry_count());
self.with_entries(cur_ts, BucketEntryState::Unreliable, |rti, entry| {
if entry.with_inner(|e| {
let entry_needs_ping = |e: &BucketEntryInner| {
// If this entry isn't in the routing domain we are checking, don't include it
if !e.exists_in_routing_domain(rti, routing_domain) {
return false;
}
// If we don't have node status for this node, then we should ping it to get some node status
if e.has_node_info(routing_domain.into()) {
if e.node_status(routing_domain).is_none() {
if e.has_node_info(routing_domain.into()) && e.node_status(routing_domain).is_none()
{
return true;
}
}
// If this entry needs a ping because this node hasn't seen our latest node info, then do it
if !e.has_seen_our_node_info_ts(routing_domain, own_node_info_ts) {
@ -567,7 +566,9 @@ impl RoutingTableInner {
}
false
}) {
};
if entry.with_inner(entry_needs_ping) {
node_refs.push(NodeRef::new(
outer_self.clone(),
entry,
@ -983,7 +984,7 @@ impl RoutingTableInner {
match entry {
None => has_valid_own_node_info,
Some(entry) => entry.with_inner(|e| {
e.signed_node_info(routing_domain.into())
e.signed_node_info(routing_domain)
.map(|sni| sni.has_any_signature())
.unwrap_or(false)
}),
@ -1080,11 +1081,7 @@ impl RoutingTableInner {
move |_rti: &RoutingTableInner, v: Option<Arc<BucketEntry>>| {
if let Some(entry) = &v {
// always filter out dead nodes
if entry.with_inner(|e| e.state(cur_ts) == BucketEntryState::Dead) {
false
} else {
true
}
!entry.with_inner(|e| e.state(cur_ts) == BucketEntryState::Dead)
} else {
// always filter out self peer, as it is irrelevant to the 'fastest nodes' search
false
@ -1100,7 +1097,7 @@ impl RoutingTableInner {
// same nodes are always the same
if let Some(a_entry) = a_entry {
if let Some(b_entry) = b_entry {
if Arc::ptr_eq(&a_entry, &b_entry) {
if Arc::ptr_eq(a_entry, b_entry) {
return core::cmp::Ordering::Equal;
}
}
@ -1151,9 +1148,7 @@ impl RoutingTableInner {
})
};
let out =
self.find_peers_with_sort_and_filter(node_count, cur_ts, filters, sort, transform);
out
self.find_peers_with_sort_and_filter(node_count, cur_ts, filters, sort, transform)
}
pub fn find_preferred_closest_nodes<T, O>(
@ -1194,7 +1189,7 @@ impl RoutingTableInner {
// same nodes are always the same
if let Some(a_entry) = a_entry {
if let Some(b_entry) = b_entry {
if Arc::ptr_eq(&a_entry, &b_entry) {
if Arc::ptr_eq(a_entry, b_entry) {
return core::cmp::Ordering::Equal;
}
}

View File

@ -46,7 +46,7 @@ impl RoutingTable {
// Envelope support
let mut envelope_support = Vec::new();
for ess in records[1].split(",") {
for ess in records[1].split(',') {
let ess = ess.trim();
let es = match ess.parse::<u8>() {
Ok(v) => v,
@ -64,9 +64,9 @@ impl RoutingTable {
// Node Id
let mut node_ids = TypedKeyGroup::new();
for node_id_str in records[2].split(",") {
for node_id_str in records[2].split(',') {
let node_id_str = node_id_str.trim();
let node_id = match TypedKey::from_str(&node_id_str) {
let node_id = match TypedKey::from_str(node_id_str) {
Ok(v) => v,
Err(e) => {
bail!(
@ -89,7 +89,7 @@ impl RoutingTable {
// Resolve each record and store in node dial infos list
let mut dial_info_details = Vec::new();
for rec in records[4].split(",") {
for rec in records[4].split(',') {
let rec = rec.trim();
let dial_infos = match DialInfo::try_vec_from_short(rec, hostname_str) {
Ok(dis) => dis,
@ -321,13 +321,13 @@ impl RoutingTable {
// See if we are specifying a direct dialinfo for bootstrap, if so use the direct mechanism
let mut bootstrap_dialinfos = Vec::<DialInfo>::new();
for b in &bootstrap {
if let Ok(bootstrap_di_vec) = DialInfo::try_vec_from_url(&b) {
if let Ok(bootstrap_di_vec) = DialInfo::try_vec_from_url(b) {
for bootstrap_di in bootstrap_di_vec {
bootstrap_dialinfos.push(bootstrap_di);
}
}
}
if bootstrap_dialinfos.len() > 0 {
if !bootstrap_dialinfos.is_empty() {
return self
.direct_bootstrap_task_routine(stop_token, bootstrap_dialinfos)
.await;

View File

@ -8,6 +8,9 @@ use futures_util::stream::{FuturesUnordered, StreamExt};
use futures_util::FutureExt;
use stop_token::future::FutureExt as StopFutureExt;
type PingValidatorFuture =
SendPinBoxFuture<Result<NetworkResult<Answer<Option<SenderInfo>>>, RPCError>>;
impl RoutingTable {
// Ping each node in the routing table if they need to be pinged
// to determine their reliability
@ -16,9 +19,7 @@ impl RoutingTable {
&self,
cur_ts: Timestamp,
relay_nr: NodeRef,
unord: &mut FuturesUnordered<
SendPinBoxFuture<Result<NetworkResult<Answer<Option<SenderInfo>>>, RPCError>>,
>,
unord: &mut FuturesUnordered<PingValidatorFuture>,
) -> EyreResult<()> {
let rpc = self.rpc_processor();
// Get our publicinternet dial info
@ -123,9 +124,7 @@ impl RoutingTable {
async fn ping_validator_public_internet(
&self,
cur_ts: Timestamp,
unord: &mut FuturesUnordered<
SendPinBoxFuture<Result<NetworkResult<Answer<Option<SenderInfo>>>, RPCError>>,
>,
unord: &mut FuturesUnordered<PingValidatorFuture>,
) -> EyreResult<()> {
let rpc = self.rpc_processor();
@ -161,9 +160,7 @@ impl RoutingTable {
async fn ping_validator_local_network(
&self,
cur_ts: Timestamp,
unord: &mut FuturesUnordered<
SendPinBoxFuture<Result<NetworkResult<Answer<Option<SenderInfo>>>, RPCError>>,
>,
unord: &mut FuturesUnordered<PingValidatorFuture>,
) -> EyreResult<()> {
let rpc = self.rpc_processor();

View File

@ -78,8 +78,11 @@ impl RoutingTable {
// Save up to N unpublished routes and test them
let background_safety_route_count = self.get_background_safety_route_count();
for x in 0..(usize::min(background_safety_route_count, unpublished_routes.len())) {
must_test_routes.push(unpublished_routes[x].0);
for unpublished_route in unpublished_routes.iter().take(usize::min(
background_safety_route_count,
unpublished_routes.len(),
)) {
must_test_routes.push(unpublished_route.0);
}
// Kill off all but N unpublished routes rather than testing them
@ -225,9 +228,9 @@ impl RoutingTable {
let remote_routes_needing_testing = rss.list_remote_routes(|k, v| {
let stats = v.get_stats();
if stats.needs_testing(cur_ts) {
return Some(*k);
Some(*k)
} else {
return None;
None
}
});
if !remote_routes_needing_testing.is_empty() {

View File

@ -30,8 +30,8 @@ pub async fn test_routingtable_buckets_round_trip() {
for crypto in routing_table_keys {
// The same keys are present in the original and copy RoutingTables.
let original_buckets = original_inner.buckets.get(&crypto).unwrap();
let copy_buckets = copy_inner.buckets.get(&crypto).unwrap();
let original_buckets = original_inner.buckets.get(crypto).unwrap();
let copy_buckets = copy_inner.buckets.get(crypto).unwrap();
// Recurse into RoutingTable.inner.buckets
for (left_buckets, right_buckets) in original_buckets.iter().zip(copy_buckets.iter()) {

View File

@ -13,6 +13,8 @@ impl MatchesDialInfoFilter for DialInfoDetail {
}
}
pub type DialInfoDetailSort = dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering;
impl DialInfoDetail {
pub fn ordered_sequencing_sort(a: &DialInfoDetail, b: &DialInfoDetail) -> core::cmp::Ordering {
let c = DialInfo::ordered_sequencing_sort(&a.dial_info, &b.dial_info);

View File

@ -2,7 +2,7 @@
use super::*;
#[allow(clippy::derive_hash_xor_eq)]
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Debug, PartialOrd, Ord, Hash, EnumSetType, Serialize, Deserialize)]
#[enumset(repr = "u8")]
pub enum Direction {

View File

@ -8,7 +8,7 @@ pub struct PeerInfo {
impl PeerInfo {
pub fn new(node_ids: TypedKeyGroup, signed_node_info: SignedNodeInfo) -> Self {
assert!(node_ids.len() > 0 && node_ids.len() <= MAX_CRYPTO_KINDS);
assert!(!node_ids.is_empty() && node_ids.len() <= MAX_CRYPTO_KINDS);
Self {
node_ids,
signed_node_info,

View File

@ -3,7 +3,7 @@
use super::*;
// Routing domain here is listed in order of preference, keep in order
#[allow(clippy::derive_hash_xor_eq)]
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Debug, Ord, PartialOrd, Hash, EnumSetType, Serialize, Deserialize)]
#[enumset(repr = "u8")]
pub enum RoutingDomain {

View File

@ -29,7 +29,7 @@ impl SignedDirectNodeInfo {
// Verify the signatures that we can
let validated_node_ids =
crypto.verify_signatures(node_ids, &node_info_bytes, &self.signatures)?;
if validated_node_ids.len() == 0 {
if validated_node_ids.is_empty() {
apibail_generic!("no valid node ids in direct node info");
}

View File

@ -33,8 +33,8 @@ impl SignedNodeInfo {
}
pub fn node_info(&self) -> &NodeInfo {
match self {
SignedNodeInfo::Direct(d) => &d.node_info(),
SignedNodeInfo::Relayed(r) => &r.node_info(),
SignedNodeInfo::Direct(d) => d.node_info(),
SignedNodeInfo::Relayed(r) => r.node_info(),
}
}
pub fn relay_ids(&self) -> TypedKeyGroup {

View File

@ -55,7 +55,7 @@ impl SignedRelayedNodeInfo {
)?;
let validated_node_ids =
crypto.verify_signatures(node_ids, &node_info_bytes, &self.signatures)?;
if validated_node_ids.len() == 0 {
if validated_node_ids.is_empty() {
apibail_generic!("no valid node ids in relayed node info");
}
Ok(validated_node_ids)

View File

@ -16,7 +16,7 @@ pub fn encode_node_info(
.reborrow()
.init_envelope_support(node_info.envelope_support().len() as u32);
if let Some(s) = es_builder.as_slice() {
s.clone_from_slice(&node_info.envelope_support());
s.clone_from_slice(node_info.envelope_support());
}
let mut cs_builder = builder
@ -100,7 +100,7 @@ pub fn decode_node_info(reader: &veilid_capnp::node_info::Reader) -> Result<Node
if envelope_support.len() > MAX_ENVELOPE_VERSIONS {
return Err(RPCError::protocol("too many envelope versions"));
}
if envelope_support.len() == 0 {
if envelope_support.is_empty() {
return Err(RPCError::protocol("no envelope versions"));
}
@ -129,7 +129,7 @@ pub fn decode_node_info(reader: &veilid_capnp::node_info::Reader) -> Result<Node
if crypto_support.len() > MAX_CRYPTO_KINDS {
return Err(RPCError::protocol("too many crypto kinds"));
}
if crypto_support.len() == 0 {
if crypto_support.is_empty() {
return Err(RPCError::protocol("no crypto kinds"));
}

View File

@ -31,22 +31,22 @@ impl RPCAnswer {
#[derive(Debug, Clone)]
pub enum RPCAnswerDetail {
StatusA(RPCOperationStatusA),
FindNodeA(RPCOperationFindNodeA),
AppCallA(RPCOperationAppCallA),
GetValueA(RPCOperationGetValueA),
SetValueA(RPCOperationSetValueA),
WatchValueA(RPCOperationWatchValueA),
StatusA(Box<RPCOperationStatusA>),
FindNodeA(Box<RPCOperationFindNodeA>),
AppCallA(Box<RPCOperationAppCallA>),
GetValueA(Box<RPCOperationGetValueA>),
SetValueA(Box<RPCOperationSetValueA>),
WatchValueA(Box<RPCOperationWatchValueA>),
#[cfg(feature = "unstable-blockstore")]
SupplyBlockA(RPCOperationSupplyBlockA),
SupplyBlockA(Box<RPCOperationSupplyBlockA>),
#[cfg(feature = "unstable-blockstore")]
FindBlockA(RPCOperationFindBlockA),
FindBlockA(Box<RPCOperationFindBlockA>),
#[cfg(feature = "unstable-tunnels")]
StartTunnelA(RPCOperationStartTunnelA),
StartTunnelA(Box<RPCOperationStartTunnelA>),
#[cfg(feature = "unstable-tunnels")]
CompleteTunnelA(RPCOperationCompleteTunnelA),
CompleteTunnelA(Box<RPCOperationCompleteTunnelA>),
#[cfg(feature = "unstable-tunnels")]
CancelTunnelA(RPCOperationCancelTunnelA),
CancelTunnelA(Box<RPCOperationCancelTunnelA>),
}
impl RPCAnswerDetail {
@ -98,62 +98,62 @@ impl RPCAnswerDetail {
veilid_capnp::answer::detail::StatusA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationStatusA::decode(&op_reader)?;
RPCAnswerDetail::StatusA(out)
RPCAnswerDetail::StatusA(Box::new(out))
}
veilid_capnp::answer::detail::FindNodeA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationFindNodeA::decode(&op_reader)?;
RPCAnswerDetail::FindNodeA(out)
RPCAnswerDetail::FindNodeA(Box::new(out))
}
veilid_capnp::answer::detail::AppCallA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationAppCallA::decode(&op_reader)?;
RPCAnswerDetail::AppCallA(out)
RPCAnswerDetail::AppCallA(Box::new(out))
}
veilid_capnp::answer::detail::GetValueA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationGetValueA::decode(&op_reader)?;
RPCAnswerDetail::GetValueA(out)
RPCAnswerDetail::GetValueA(Box::new(out))
}
veilid_capnp::answer::detail::SetValueA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationSetValueA::decode(&op_reader)?;
RPCAnswerDetail::SetValueA(out)
RPCAnswerDetail::SetValueA(Box::new(out))
}
veilid_capnp::answer::detail::WatchValueA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationWatchValueA::decode(&op_reader)?;
RPCAnswerDetail::WatchValueA(out)
RPCAnswerDetail::WatchValueA(Box::new(out))
}
#[cfg(feature = "unstable-blockstore")]
veilid_capnp::answer::detail::SupplyBlockA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationSupplyBlockA::decode(&op_reader)?;
RPCAnswerDetail::SupplyBlockA(out)
RPCAnswerDetail::SupplyBlockA(Box::new(out))
}
#[cfg(feature = "unstable-blockstore")]
veilid_capnp::answer::detail::FindBlockA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationFindBlockA::decode(&op_reader)?;
RPCAnswerDetail::FindBlockA(out)
RPCAnswerDetail::FindBlockA(Box::new(out))
}
#[cfg(feature = "unstable-tunnels")]
veilid_capnp::answer::detail::StartTunnelA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationStartTunnelA::decode(&op_reader)?;
RPCAnswerDetail::StartTunnelA(out)
RPCAnswerDetail::StartTunnelA(Box::new(out))
}
#[cfg(feature = "unstable-tunnels")]
veilid_capnp::answer::detail::CompleteTunnelA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationCompleteTunnelA::decode(&op_reader)?;
RPCAnswerDetail::CompleteTunnelA(out)
RPCAnswerDetail::CompleteTunnelA(Box::new(out))
}
#[cfg(feature = "unstable-tunnels")]
veilid_capnp::answer::detail::CancelTunnelA(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationCancelTunnelA::decode(&op_reader)?;
RPCAnswerDetail::CancelTunnelA(out)
RPCAnswerDetail::CancelTunnelA(Box::new(out))
}
};
Ok(out)

View File

@ -2,9 +2,9 @@ use super::*;
#[derive(Debug, Clone)]
pub enum RPCOperationKind {
Question(RPCQuestion),
Statement(RPCStatement),
Answer(RPCAnswer),
Question(Box<RPCQuestion>),
Statement(Box<RPCStatement>),
Answer(Box<RPCAnswer>),
}
impl RPCOperationKind {
@ -30,17 +30,17 @@ impl RPCOperationKind {
veilid_capnp::operation::kind::Which::Question(r) => {
let q_reader = r.map_err(RPCError::protocol)?;
let out = RPCQuestion::decode(&q_reader)?;
RPCOperationKind::Question(out)
RPCOperationKind::Question(Box::new(out))
}
veilid_capnp::operation::kind::Which::Statement(r) => {
let q_reader = r.map_err(RPCError::protocol)?;
let out = RPCStatement::decode(&q_reader)?;
RPCOperationKind::Statement(out)
RPCOperationKind::Statement(Box::new(out))
}
veilid_capnp::operation::kind::Which::Answer(r) => {
let q_reader = r.map_err(RPCError::protocol)?;
let out = RPCAnswer::decode(&q_reader)?;
RPCOperationKind::Answer(out)
RPCOperationKind::Answer(Box::new(out))
}
};
@ -73,7 +73,7 @@ impl RPCOperation {
op_id: OperationId::new(get_random_u64()),
opt_sender_peer_info: sender_peer_info.opt_sender_peer_info,
target_node_info_ts: sender_peer_info.target_node_info_ts,
kind: RPCOperationKind::Question(question),
kind: RPCOperationKind::Question(Box::new(question)),
}
}
pub fn new_statement(statement: RPCStatement, sender_peer_info: SenderPeerInfo) -> Self {
@ -81,7 +81,7 @@ impl RPCOperation {
op_id: OperationId::new(get_random_u64()),
opt_sender_peer_info: sender_peer_info.opt_sender_peer_info,
target_node_info_ts: sender_peer_info.target_node_info_ts,
kind: RPCOperationKind::Statement(statement),
kind: RPCOperationKind::Statement(Box::new(statement)),
}
}
@ -94,7 +94,7 @@ impl RPCOperation {
op_id: request.op_id,
opt_sender_peer_info: sender_peer_info.opt_sender_peer_info,
target_node_info_ts: sender_peer_info.target_node_info_ts,
kind: RPCOperationKind::Answer(answer),
kind: RPCOperationKind::Answer(Box::new(answer)),
}
}
@ -163,7 +163,7 @@ impl RPCOperation {
builder.set_op_id(self.op_id.as_u64());
if let Some(sender_peer_info) = &self.opt_sender_peer_info {
let mut pi_builder = builder.reborrow().init_sender_peer_info();
encode_peer_info(&sender_peer_info, &mut pi_builder)?;
encode_peer_info(sender_peer_info, &mut pi_builder)?;
}
builder.set_target_node_info_ts(self.target_node_info_ts.as_u64());
let mut k_builder = builder.reborrow().init_kind();

View File

@ -122,7 +122,7 @@ impl RPCOperationSetValueA {
value: Option<SignedValueData>,
peers: Vec<PeerInfo>,
) -> Result<Self, RPCError> {
if peers.len() as usize > MAX_SET_VALUE_A_PEERS_LEN {
if peers.len() > MAX_SET_VALUE_A_PEERS_LEN {
return Err(RPCError::protocol(
"encoded SetValueA peers length too long",
));

View File

@ -36,7 +36,7 @@ impl RPCOperationStatusQ {
) -> Result<(), RPCError> {
if let Some(ns) = &self.node_status {
let mut ns_builder = builder.reborrow().init_node_status();
encode_node_status(&ns, &mut ns_builder)?;
encode_node_status(ns, &mut ns_builder)?;
}
Ok(())
}
@ -98,11 +98,11 @@ impl RPCOperationStatusA {
) -> Result<(), RPCError> {
if let Some(ns) = &self.node_status {
let mut ns_builder = builder.reborrow().init_node_status();
encode_node_status(&ns, &mut ns_builder)?;
encode_node_status(ns, &mut ns_builder)?;
}
if let Some(si) = &self.sender_info {
let mut si_builder = builder.reborrow().init_sender_info();
encode_sender_info(&si, &mut si_builder)?;
encode_sender_info(si, &mut si_builder)?;
}
Ok(())
}

View File

@ -22,7 +22,12 @@ impl RPCOperationWatchValueQ {
watcher: PublicKey,
signature: Signature,
) -> Result<Self, RPCError> {
if subkeys.len() as usize > MAX_WATCH_VALUE_Q_SUBKEYS_LEN {
#[cfg(target_arch = "wasm32")]
let subkeys_len = subkeys.len() as usize;
#[cfg(not(target_arch = "wasm32"))]
let subkeys_len = subkeys.len();
if subkeys_len > MAX_WATCH_VALUE_Q_SUBKEYS_LEN {
return Err(RPCError::protocol("WatchValueQ subkeys length too long"));
}
Ok(Self {
@ -37,8 +42,12 @@ impl RPCOperationWatchValueQ {
// signature covers: key, subkeys, expiration, count, using watcher key
fn make_signature_data(&self) -> Vec<u8> {
let mut sig_data =
Vec::with_capacity(PUBLIC_KEY_LENGTH + 4 + (self.subkeys.len() as usize * 8) + 8 + 4);
#[cfg(target_arch = "wasm32")]
let subkeys_len = self.subkeys.len() as usize;
#[cfg(not(target_arch = "wasm32"))]
let subkeys_len = self.subkeys.len();
let mut sig_data = Vec::with_capacity(PUBLIC_KEY_LENGTH + 4 + (subkeys_len * 8) + 8 + 4);
sig_data.extend_from_slice(&self.key.kind.0);
sig_data.extend_from_slice(&self.key.value.bytes);
for sk in self.subkeys.ranges() {

View File

@ -43,22 +43,22 @@ impl RPCQuestion {
#[derive(Debug, Clone)]
pub enum RPCQuestionDetail {
StatusQ(RPCOperationStatusQ),
FindNodeQ(RPCOperationFindNodeQ),
AppCallQ(RPCOperationAppCallQ),
GetValueQ(RPCOperationGetValueQ),
SetValueQ(RPCOperationSetValueQ),
WatchValueQ(RPCOperationWatchValueQ),
StatusQ(Box<RPCOperationStatusQ>),
FindNodeQ(Box<RPCOperationFindNodeQ>),
AppCallQ(Box<RPCOperationAppCallQ>),
GetValueQ(Box<RPCOperationGetValueQ>),
SetValueQ(Box<RPCOperationSetValueQ>),
WatchValueQ(Box<RPCOperationWatchValueQ>),
#[cfg(feature = "unstable-blockstore")]
SupplyBlockQ(RPCOperationSupplyBlockQ),
SupplyBlockQ(Box<RPCOperationSupplyBlockQ>),
#[cfg(feature = "unstable-blockstore")]
FindBlockQ(RPCOperationFindBlockQ),
FindBlockQ(Box<RPCOperationFindBlockQ>),
#[cfg(feature = "unstable-tunnels")]
StartTunnelQ(RPCOperationStartTunnelQ),
StartTunnelQ(Box<RPCOperationStartTunnelQ>),
#[cfg(feature = "unstable-tunnels")]
CompleteTunnelQ(RPCOperationCompleteTunnelQ),
CompleteTunnelQ(Box<RPCOperationCompleteTunnelQ>),
#[cfg(feature = "unstable-tunnels")]
CancelTunnelQ(RPCOperationCancelTunnelQ),
CancelTunnelQ(Box<RPCOperationCancelTunnelQ>),
}
impl RPCQuestionDetail {
@ -111,62 +111,62 @@ impl RPCQuestionDetail {
veilid_capnp::question::detail::StatusQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationStatusQ::decode(&op_reader)?;
RPCQuestionDetail::StatusQ(out)
RPCQuestionDetail::StatusQ(Box::new(out))
}
veilid_capnp::question::detail::FindNodeQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationFindNodeQ::decode(&op_reader)?;
RPCQuestionDetail::FindNodeQ(out)
RPCQuestionDetail::FindNodeQ(Box::new(out))
}
veilid_capnp::question::detail::Which::AppCallQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationAppCallQ::decode(&op_reader)?;
RPCQuestionDetail::AppCallQ(out)
RPCQuestionDetail::AppCallQ(Box::new(out))
}
veilid_capnp::question::detail::GetValueQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationGetValueQ::decode(&op_reader)?;
RPCQuestionDetail::GetValueQ(out)
RPCQuestionDetail::GetValueQ(Box::new(out))
}
veilid_capnp::question::detail::SetValueQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationSetValueQ::decode(&op_reader)?;
RPCQuestionDetail::SetValueQ(out)
RPCQuestionDetail::SetValueQ(Box::new(out))
}
veilid_capnp::question::detail::WatchValueQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationWatchValueQ::decode(&op_reader)?;
RPCQuestionDetail::WatchValueQ(out)
RPCQuestionDetail::WatchValueQ(Box::new(out))
}
#[cfg(feature = "unstable-blockstore")]
veilid_capnp::question::detail::SupplyBlockQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationSupplyBlockQ::decode(&op_reader)?;
RPCQuestionDetail::SupplyBlockQ(out)
RPCQuestionDetail::SupplyBlockQ(Box::new(out))
}
#[cfg(feature = "unstable-blockstore")]
veilid_capnp::question::detail::FindBlockQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationFindBlockQ::decode(&op_reader)?;
RPCQuestionDetail::FindBlockQ(out)
RPCQuestionDetail::FindBlockQ(Box::new(out))
}
#[cfg(feature = "unstable-tunnels")]
veilid_capnp::question::detail::StartTunnelQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationStartTunnelQ::decode(&op_reader)?;
RPCQuestionDetail::StartTunnelQ(out)
RPCQuestionDetail::StartTunnelQ(Box::new(out))
}
#[cfg(feature = "unstable-tunnels")]
veilid_capnp::question::detail::CompleteTunnelQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationCompleteTunnelQ::decode(&op_reader)?;
RPCQuestionDetail::CompleteTunnelQ(out)
RPCQuestionDetail::CompleteTunnelQ(Box::new(out))
}
#[cfg(feature = "unstable-tunnels")]
veilid_capnp::question::detail::CancelTunnelQ(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationCancelTunnelQ::decode(&op_reader)?;
RPCQuestionDetail::CancelTunnelQ(out)
RPCQuestionDetail::CancelTunnelQ(Box::new(out))
}
};
Ok(out)

View File

@ -34,12 +34,12 @@ impl RPCStatement {
#[derive(Debug, Clone)]
pub enum RPCStatementDetail {
ValidateDialInfo(RPCOperationValidateDialInfo),
Route(RPCOperationRoute),
ValueChanged(RPCOperationValueChanged),
Signal(RPCOperationSignal),
ReturnReceipt(RPCOperationReturnReceipt),
AppMessage(RPCOperationAppMessage),
ValidateDialInfo(Box<RPCOperationValidateDialInfo>),
Route(Box<RPCOperationRoute>),
ValueChanged(Box<RPCOperationValueChanged>),
Signal(Box<RPCOperationSignal>),
ReturnReceipt(Box<RPCOperationReturnReceipt>),
AppMessage(Box<RPCOperationAppMessage>),
}
impl RPCStatementDetail {
@ -71,32 +71,32 @@ impl RPCStatementDetail {
veilid_capnp::statement::detail::ValidateDialInfo(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationValidateDialInfo::decode(&op_reader)?;
RPCStatementDetail::ValidateDialInfo(out)
RPCStatementDetail::ValidateDialInfo(Box::new(out))
}
veilid_capnp::statement::detail::Route(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationRoute::decode(&op_reader)?;
RPCStatementDetail::Route(out)
RPCStatementDetail::Route(Box::new(out))
}
veilid_capnp::statement::detail::ValueChanged(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationValueChanged::decode(&op_reader)?;
RPCStatementDetail::ValueChanged(out)
RPCStatementDetail::ValueChanged(Box::new(out))
}
veilid_capnp::statement::detail::Signal(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationSignal::decode(&op_reader)?;
RPCStatementDetail::Signal(out)
RPCStatementDetail::Signal(Box::new(out))
}
veilid_capnp::statement::detail::ReturnReceipt(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationReturnReceipt::decode(&op_reader)?;
RPCStatementDetail::ReturnReceipt(out)
RPCStatementDetail::ReturnReceipt(Box::new(out))
}
veilid_capnp::statement::detail::AppMessage(r) => {
let op_reader = r.map_err(RPCError::protocol)?;
let out = RPCOperationAppMessage::decode(&op_reader)?;
RPCStatementDetail::AppMessage(out)
RPCStatementDetail::AppMessage(Box::new(out))
}
};
Ok(out)

View File

@ -41,7 +41,7 @@ pub fn decode_peer_info(reader: &veilid_capnp::peer_info::Reader) -> Result<Peer
node_ids.add(decode_typed_key(&nid_reader)?);
}
let signed_node_info = decode_signed_node_info(&sni_reader)?;
if node_ids.len() == 0 {
if node_ids.is_empty() {
return Err(RPCError::protocol("no verified node ids"));
}
Ok(PeerInfo::new(node_ids, signed_node_info))

View File

@ -53,11 +53,11 @@ pub fn encode_route_hop(
match &route_hop.node {
RouteNode::NodeId(ni) => {
let mut ni_builder = node_builder.init_node_id();
encode_key256(&ni, &mut ni_builder);
encode_key256(ni, &mut ni_builder);
}
RouteNode::PeerInfo(pi) => {
let mut pi_builder = node_builder.init_peer_info();
encode_peer_info(&pi, &mut pi_builder)?;
encode_peer_info(pi, &mut pi_builder)?;
}
}
if let Some(rhd) = &route_hop.next_hop {
@ -76,10 +76,10 @@ pub fn decode_route_hop(reader: &veilid_capnp::route_hop::Reader) -> Result<Rout
}
veilid_capnp::route_hop::node::Which::PeerInfo(pi) => {
let pi_reader = pi.map_err(RPCError::protocol)?;
RouteNode::PeerInfo(
RouteNode::PeerInfo(Box::new(
decode_peer_info(&pi_reader)
.map_err(RPCError::map_protocol("invalid peer info in route hop"))?,
)
))
}
};
@ -134,7 +134,7 @@ pub fn decode_private_route(
let hops = match reader.get_hops().which().map_err(RPCError::protocol)? {
veilid_capnp::private_route::hops::Which::FirstHop(rh_reader) => {
let rh_reader = rh_reader.map_err(RPCError::protocol)?;
PrivateRouteHops::FirstHop(decode_route_hop(&rh_reader)?)
PrivateRouteHops::FirstHop(Box::new(decode_route_hop(&rh_reader)?))
}
veilid_capnp::private_route::hops::Which::Data(rhd_reader) => {
let rhd_reader = rhd_reader.map_err(RPCError::protocol)?;

View File

@ -181,9 +181,16 @@ impl RPCProcessor {
// Sent directly but with a safety route, respond to private route
let crypto_kind = target.best_node_id().kind;
let Some(pr_key) = rss
.get_private_route_for_safety_spec(crypto_kind, safety_spec, &target.node_ids())
.map_err(RPCError::internal)? else {
return Ok(NetworkResult::no_connection_other("no private route for response at this time"));
.get_private_route_for_safety_spec(
crypto_kind,
safety_spec,
&target.node_ids(),
)
.map_err(RPCError::internal)?
else {
return Ok(NetworkResult::no_connection_other(
"no private route for response at this time",
));
};
// Get the assembled route for response
@ -211,8 +218,11 @@ impl RPCProcessor {
avoid_nodes.add_all(&target.node_ids());
let Some(pr_key) = rss
.get_private_route_for_safety_spec(crypto_kind, safety_spec, &avoid_nodes)
.map_err(RPCError::internal)? else {
return Ok(NetworkResult::no_connection_other("no private route for response at this time"));
.map_err(RPCError::internal)?
else {
return Ok(NetworkResult::no_connection_other(
"no private route for response at this time",
));
};
// Get the assembled route for response
@ -228,7 +238,9 @@ impl RPCProcessor {
safety_selection,
} => {
let Some(avoid_node_id) = private_route.first_hop_node_id() else {
return Err(RPCError::internal("destination private route must have first hop"));
return Err(RPCError::internal(
"destination private route must have first hop",
));
};
let crypto_kind = private_route.public_key.kind;
@ -250,7 +262,7 @@ impl RPCProcessor {
} else {
let own_peer_info =
routing_table.get_own_peer_info(RoutingDomain::PublicInternet);
RouteNode::PeerInfo(own_peer_info)
RouteNode::PeerInfo(Box::new(own_peer_info))
};
Ok(NetworkResult::value(RespondTo::PrivateRoute(
@ -271,9 +283,16 @@ impl RPCProcessor {
} else {
// Get the private route to respond to that matches the safety route spec we sent the request with
let Some(pr_key) = rss
.get_private_route_for_safety_spec(crypto_kind, safety_spec, &[avoid_node_id])
.map_err(RPCError::internal)? else {
return Ok(NetworkResult::no_connection_other("no private route for response at this time"));
.get_private_route_for_safety_spec(
crypto_kind,
safety_spec,
&[avoid_node_id],
)
.map_err(RPCError::internal)?
else {
return Ok(NetworkResult::no_connection_other(
"no private route for response at this time",
));
};
pr_key
};
@ -342,9 +361,9 @@ impl RPCProcessor {
if let Some(sender_noderef) = res {
NetworkResult::value(Destination::relay(peer_noderef, sender_noderef))
} else {
return NetworkResult::invalid_message(
NetworkResult::invalid_message(
"not responding to sender that has no node info",
);
)
}
}
}
@ -352,9 +371,9 @@ impl RPCProcessor {
match &request.header.detail {
RPCMessageHeaderDetail::Direct(_) => {
// If this was sent directly, we should only ever respond directly
return NetworkResult::invalid_message(
NetworkResult::invalid_message(
"not responding to private route from direct question",
);
)
}
RPCMessageHeaderDetail::SafetyRouted(detail) => {
// If this was sent via a safety route, but not received over our private route, don't respond with a safety route,
@ -368,7 +387,7 @@ impl RPCProcessor {
// If this was received over our private route, it's okay to respond to a private route via our safety route
NetworkResult::value(Destination::private_route(
pr.clone(),
SafetySelection::Safe(detail.safety_spec.clone()),
SafetySelection::Safe(detail.safety_spec),
))
}
}

View File

@ -60,6 +60,7 @@ where
C: Fn(NodeRef) -> F,
D: Fn(&[NodeRef]) -> Option<R>,
{
#[allow(clippy::too_many_arguments)]
pub fn new(
routing_table: RoutingTable,
node_id: TypedKey,
@ -103,7 +104,7 @@ where
fn add_to_fanout_queue(self: Arc<Self>, new_nodes: &[NodeRef]) {
let ctx = &mut *self.context.lock();
let this = self.clone();
ctx.fanout_queue.add(&new_nodes, |current_nodes| {
ctx.fanout_queue.add(new_nodes, |current_nodes| {
let mut current_nodes_vec = this
.routing_table
.sort_and_clean_closest_noderefs(this.node_id, current_nodes);
@ -181,7 +182,9 @@ where
// Filter entries
entry.with(rti, |_rti, e| {
let Some(signed_node_info) = e.signed_node_info(RoutingDomain::PublicInternet) else {
let Some(signed_node_info) =
e.signed_node_info(RoutingDomain::PublicInternet)
else {
return false;
};
// Ensure only things that are valid/signed in the PublicInternet domain are returned

View File

@ -447,7 +447,7 @@ impl RPCProcessor {
capabilities: &[Capability],
) -> bool {
let routing_table = self.routing_table();
routing_table.signed_node_info_is_valid_in_routing_domain(routing_domain, &signed_node_info)
routing_table.signed_node_info_is_valid_in_routing_domain(routing_domain, signed_node_info)
&& signed_node_info.node_info().has_capabilities(capabilities)
}
@ -684,7 +684,7 @@ impl RPCProcessor {
let ssni_route =
self.get_sender_peer_info(&Destination::direct(compiled_route.first_hop.clone()));
let operation = RPCOperation::new_statement(
RPCStatement::new(RPCStatementDetail::Route(route_operation)),
RPCStatement::new(RPCStatementDetail::Route(Box::new(route_operation))),
ssni_route,
);
@ -812,7 +812,7 @@ impl RPCProcessor {
};
let private_route = PrivateRoute::new_stub(
destination_node_ref.best_node_id(),
RouteNode::PeerInfo(peer_info),
RouteNode::PeerInfo(Box::new(peer_info)),
);
// Wrap with safety route
@ -1021,6 +1021,7 @@ impl RPCProcessor {
}
/// Record answer received from node or route
#[allow(clippy::too_many_arguments)]
fn record_answer_received(
&self,
send_ts: Timestamp,
@ -1079,7 +1080,7 @@ impl RPCProcessor {
// If we sent to a private route without a safety route
// We need to mark our own node info as having been seen so we can optimize sending it
if let Err(e) = rss.mark_remote_private_route_seen_our_node_info(&rpr_pubkey, recv_ts) {
if let Err(e) = rss.mark_remote_private_route_seen_our_node_info(rpr_pubkey, recv_ts) {
log_rpc!(error "private route missing: {}", e);
}
@ -1116,7 +1117,6 @@ impl RPCProcessor {
RPCMessageHeaderDetail::Direct(_) => {
if let Some(sender_nr) = msg.opt_sender_nr.clone() {
sender_nr.stats_question_rcvd(recv_ts, bytes);
return;
}
}
// Process messages that arrived with no private route (private route stub)

View File

@ -17,7 +17,7 @@ impl RPCProcessor {
let app_call_q = RPCOperationAppCallQ::new(message)?;
let question = RPCQuestion::new(
network_result_try!(self.get_destination_respond_to(&dest)?),
RPCQuestionDetail::AppCallQ(app_call_q),
RPCQuestionDetail::AppCallQ(Box::new(app_call_q)),
);
// Send the app call question
@ -94,9 +94,9 @@ impl RPCProcessor {
// Pass the call up through the update callback
let message_q = app_call_q.destructure();
(self.unlocked_inner.update_callback)(VeilidUpdate::AppCall(VeilidAppCall::new(
(self.unlocked_inner.update_callback)(VeilidUpdate::AppCall(Box::new(VeilidAppCall::new(
sender, message_q, op_id,
)));
))));
// Wait for an app call answer to come back from the app
let res = self
@ -117,7 +117,10 @@ impl RPCProcessor {
let app_call_a = RPCOperationAppCallA::new(message_a)?;
// Send status answer
self.answer(msg, RPCAnswer::new(RPCAnswerDetail::AppCallA(app_call_a)))
self.answer(
msg,
RPCAnswer::new(RPCAnswerDetail::AppCallA(Box::new(app_call_a))),
)
.await
}

View File

@ -13,7 +13,7 @@ impl RPCProcessor {
message: Vec<u8>,
) -> Result<NetworkResult<()>, RPCError> {
let app_message = RPCOperationAppMessage::new(message)?;
let statement = RPCStatement::new(RPCStatementDetail::AppMessage(app_message));
let statement = RPCStatement::new(RPCStatementDetail::AppMessage(Box::new(app_message)));
// Send the app message request
self.statement(dest, statement).await
@ -58,8 +58,8 @@ impl RPCProcessor {
// Pass the message up through the update callback
let message = app_message.destructure();
(self.unlocked_inner.update_callback)(VeilidUpdate::AppMessage(VeilidAppMessage::new(
sender, message,
(self.unlocked_inner.update_callback)(VeilidUpdate::AppMessage(Box::new(
VeilidAppMessage::new(sender, message),
)));
Ok(NetworkResult::value(()))

View File

@ -38,7 +38,7 @@ impl RPCError {
move |x| Self::Internal(format!("{}: {}", message.to_string(), x.to_string()))
}
pub fn else_internal<M: ToString>(message: M) -> impl FnOnce() -> Self {
move || Self::Internal(format!("{}", message.to_string()))
move || Self::Internal(message.to_string())
}
pub fn network<X: ToString>(x: X) -> Self {
Self::Network(x.to_string())

View File

@ -30,8 +30,9 @@ impl RPCProcessor {
));
}
let find_node_q_detail =
RPCQuestionDetail::FindNodeQ(RPCOperationFindNodeQ::new(node_id, capabilities.clone()));
let find_node_q_detail = RPCQuestionDetail::FindNodeQ(Box::new(
RPCOperationFindNodeQ::new(node_id, capabilities.clone()),
));
let find_node_q = RPCQuestion::new(
network_result_try!(self.get_destination_respond_to(&dest)?),
find_node_q_detail,
@ -111,7 +112,10 @@ impl RPCProcessor {
let find_node_a = RPCOperationFindNodeA::new(closest_nodes)?;
// Send FindNode answer
self.answer(msg, RPCAnswer::new(RPCAnswerDetail::FindNodeA(find_node_a)))
self.answer(
msg,
RPCAnswer::new(RPCAnswerDetail::FindNodeA(Box::new(find_node_a))),
)
.await
}
}

View File

@ -65,7 +65,7 @@ impl RPCProcessor {
let get_value_q = RPCOperationGetValueQ::new(key, subkey, last_descriptor.is_none());
let question = RPCQuestion::new(
network_result_try!(self.get_destination_respond_to(&dest)?),
RPCQuestionDetail::GetValueQ(get_value_q),
RPCQuestionDetail::GetValueQ(Box::new(get_value_q)),
);
let question_context = QuestionContext::GetValue(ValidateGetValueContext {
@ -268,7 +268,7 @@ impl RPCProcessor {
)?;
// Send GetValue answer
self.answer(msg, RPCAnswer::new(RPCAnswerDetail::GetValueA(get_value_a)))
self.answer(msg, RPCAnswer::new(RPCAnswerDetail::GetValueA(Box::new(get_value_a))))
.await
}
}

View File

@ -15,7 +15,8 @@ impl RPCProcessor {
let receipt = receipt.as_ref().to_vec();
let return_receipt = RPCOperationReturnReceipt::new(receipt)?;
let statement = RPCStatement::new(RPCStatementDetail::ReturnReceipt(return_receipt));
let statement =
RPCStatement::new(RPCStatementDetail::ReturnReceipt(Box::new(return_receipt)));
// Send the return_receipt request
network_result_try!(self.statement(dest, statement).await?);

View File

@ -1,7 +1,10 @@
use super::*;
impl RPCProcessor {
#[cfg_attr(feature="verbose-tracing", instrument(level = "trace", skip_all, err))]
#[cfg_attr(
feature = "verbose-tracing",
instrument(level = "trace", skip_all, err)
)]
async fn process_route_safety_route_hop(
&self,
routed_operation: RoutedOperation,
@ -26,7 +29,10 @@ impl RPCProcessor {
}
// Get next hop node ref
let Some(mut next_hop_nr) = route_hop.node.node_ref(self.routing_table.clone(), safety_route.public_key.kind) else {
let Some(mut next_hop_nr) = route_hop
.node
.node_ref(self.routing_table.clone(), safety_route.public_key.kind)
else {
return Err(RPCError::network(format!(
"could not get route node hop ref: {}",
route_hop.node.describe(safety_route.public_key.kind)
@ -45,14 +51,18 @@ impl RPCProcessor {
},
routed_operation,
);
let next_hop_route_stmt = RPCStatement::new(RPCStatementDetail::Route(next_hop_route));
let next_hop_route_stmt =
RPCStatement::new(RPCStatementDetail::Route(Box::new(next_hop_route)));
// Send the next route statement
self.statement(Destination::direct(next_hop_nr), next_hop_route_stmt)
.await
}
#[cfg_attr(feature="verbose-tracing", instrument(level = "trace", skip_all, err))]
#[cfg_attr(
feature = "verbose-tracing",
instrument(level = "trace", skip_all, err)
)]
async fn process_route_private_route_hop(
&self,
routed_operation: RoutedOperation,
@ -68,7 +78,9 @@ impl RPCProcessor {
}
// Get next hop node ref
let Some(mut next_hop_nr) = next_route_node.node_ref(self.routing_table.clone(), safety_route_public_key.kind) else {
let Some(mut next_hop_nr) =
next_route_node.node_ref(self.routing_table.clone(), safety_route_public_key.kind)
else {
return Err(RPCError::network(format!(
"could not get route node hop ref: {}",
next_route_node.describe(safety_route_public_key.kind)
@ -87,7 +99,8 @@ impl RPCProcessor {
},
routed_operation,
);
let next_hop_route_stmt = RPCStatement::new(RPCStatementDetail::Route(next_hop_route));
let next_hop_route_stmt =
RPCStatement::new(RPCStatementDetail::Route(Box::new(next_hop_route)));
// Send the next route statement
self.statement(Destination::direct(next_hop_nr), next_hop_route_stmt)
@ -99,7 +112,10 @@ impl RPCProcessor {
/// Note: it is important that we never respond with a safety route to questions that come
/// in without a private route. Giving away a safety route when the node id is known is
/// a privacy violation!
#[cfg_attr(feature="verbose-tracing", instrument(level = "trace", skip_all, err))]
#[cfg_attr(
feature = "verbose-tracing",
instrument(level = "trace", skip_all, err)
)]
fn process_safety_routed_operation(
&self,
detail: RPCMessageHeaderDetailDirect,
@ -111,7 +127,9 @@ impl RPCProcessor {
// xxx: punish nodes that send messages that fail to decrypt eventually? How to do this for safety routes?
let node_id_secret = self.routing_table.node_id_secret_key(remote_sr_pubkey.kind);
let Ok(dh_secret) = vcrypto.cached_dh(&remote_sr_pubkey.value, &node_id_secret) else {
return Ok(NetworkResult::invalid_message("dh failed for remote safety route for safety routed operation"));
return Ok(NetworkResult::invalid_message(
"dh failed for remote safety route for safety routed operation",
));
};
let body = match vcrypto.decrypt_aead(
routed_operation.data(),
@ -141,7 +159,10 @@ impl RPCProcessor {
}
/// Process a routed operation that came in over both a safety route and a private route
#[cfg_attr(feature="verbose-tracing", instrument(level = "trace", skip_all, err))]
#[cfg_attr(
feature = "verbose-tracing",
instrument(level = "trace", skip_all, err)
)]
fn process_private_routed_operation(
&self,
detail: RPCMessageHeaderDetailDirect,
@ -152,15 +173,16 @@ impl RPCProcessor {
) -> Result<NetworkResult<()>, RPCError> {
// Get sender id of the peer with the crypto kind of the route
let Some(sender_id) = detail.peer_noderef.node_ids().get(pr_pubkey.kind) else {
return Ok(NetworkResult::invalid_message("route node doesnt have a required crypto kind for routed operation"));
return Ok(NetworkResult::invalid_message(
"route node doesnt have a required crypto kind for routed operation",
));
};
// Look up the private route and ensure it's one in our spec store
// Ensure the route is validated, and construct a return safetyspec that matches the inbound preferences
let rss = self.routing_table.route_spec_store();
let preferred_route = rss.get_route_id_for_key(&pr_pubkey.value);
let Some((secret_key, safety_spec)) = rss
.with_signature_validated_route(
let Some((secret_key, safety_spec)) = rss.with_signature_validated_route(
&pr_pubkey,
routed_operation.signatures(),
routed_operation.data(),
@ -175,25 +197,29 @@ impl RPCProcessor {
sequencing: routed_operation.sequencing(),
},
)
}
)
else {
return Ok(NetworkResult::invalid_message("signatures did not validate for private route"));
},
) else {
return Ok(NetworkResult::invalid_message(
"signatures did not validate for private route",
));
};
// Now that things are valid, decrypt the routed operation with DEC(nonce, DH(the SR's public key, the PR's (or node's) secret)
// xxx: punish nodes that send messages that fail to decrypt eventually. How to do this for private routes?
let Ok(dh_secret) = vcrypto.cached_dh(&remote_sr_pubkey.value, &secret_key) else {
return Ok(NetworkResult::invalid_message("dh failed for remote safety route for private routed operation"));
return Ok(NetworkResult::invalid_message(
"dh failed for remote safety route for private routed operation",
));
};
let Ok(body) = vcrypto
.decrypt_aead(
let Ok(body) = vcrypto.decrypt_aead(
routed_operation.data(),
routed_operation.nonce(),
&dh_secret,
None,
) else {
return Ok(NetworkResult::invalid_message("decryption of routed operation failed"));
return Ok(NetworkResult::invalid_message(
"decryption of routed operation failed",
));
};
// Pass message to RPC system
@ -209,7 +235,10 @@ impl RPCProcessor {
Ok(NetworkResult::value(()))
}
#[cfg_attr(feature="verbose-tracing", instrument(level = "trace", skip_all, err))]
#[cfg_attr(
feature = "verbose-tracing",
instrument(level = "trace", skip_all, err)
)]
fn process_routed_operation(
&self,
detail: RPCMessageHeaderDetailDirect,
@ -239,7 +268,10 @@ impl RPCProcessor {
)
}
}
#[cfg_attr(feature="verbose-tracing", instrument(level = "trace", skip_all, err))]
#[cfg_attr(
feature = "verbose-tracing",
instrument(level = "trace", skip_all, err)
)]
pub(crate) async fn process_private_route_first_hop(
&self,
mut routed_operation: RoutedOperation,
@ -247,14 +279,18 @@ impl RPCProcessor {
mut private_route: PrivateRoute,
) -> Result<NetworkResult<()>, RPCError> {
let Some(pr_first_hop) = private_route.pop_first_hop() else {
return Ok(NetworkResult::invalid_message("switching from safety route to private route requires first hop"));
return Ok(NetworkResult::invalid_message(
"switching from safety route to private route requires first hop",
));
};
// Check for loopback test where private route is the same as safety route
if sr_pubkey == private_route.public_key {
// If so, we're going to turn this thing right around without transiting the network
let PrivateRouteHops::Data(route_hop_data) = private_route.hops else {
return Ok(NetworkResult::invalid_message("Loopback test requires hops"));
return Ok(NetworkResult::invalid_message(
"Loopback test requires hops",
));
};
// Decrypt route hop data
@ -282,7 +318,7 @@ impl RPCProcessor {
hop_count: private_route.hop_count - 1,
hops: route_hop
.next_hop
.map(|rhd| PrivateRouteHops::Data(rhd))
.map(PrivateRouteHops::Data)
.unwrap_or(PrivateRouteHops::Empty),
},
)
@ -344,7 +380,9 @@ impl RPCProcessor {
};
// Validate the RouteHop
route_hop.validate(self.crypto.clone()).map_err(RPCError::protocol)?;
route_hop
.validate(self.crypto.clone())
.map_err(RPCError::protocol)?;
// Sign the operation if this is not our last hop
// as the last hop is already signed by the envelope
@ -360,7 +398,10 @@ impl RPCProcessor {
Ok(NetworkResult::value(route_hop))
}
#[cfg_attr(feature="verbose-tracing", instrument(level = "trace", skip(self), ret, err))]
#[cfg_attr(
feature = "verbose-tracing",
instrument(level = "trace", skip(self), ret, err)
)]
pub(crate) async fn process_route(
&self,
msg: RPCMessage,
@ -374,14 +415,8 @@ impl RPCProcessor {
}
let opi = routing_table.get_own_peer_info(msg.header.routing_domain());
if !opi
.signed_node_info()
.node_info()
.has_capability(CAP_ROUTE)
{
return Ok(NetworkResult::service_unavailable(
"route is not available",
));
if !opi.signed_node_info().node_info().has_capability(CAP_ROUTE) {
return Ok(NetworkResult::service_unavailable("route is not available"));
}
// Get header detail, must be direct and not inside a route itself
@ -395,7 +430,7 @@ impl RPCProcessor {
};
// Get the statement
let (_,_,_,kind) = msg.operation.destructure();
let (_, _, _, kind) = msg.operation.destructure();
let route = match kind {
RPCOperationKind::Statement(s) => match s.destructure() {
RPCStatementDetail::Route(s) => s,
@ -419,19 +454,22 @@ impl RPCProcessor {
SafetyRouteHops::Data(ref route_hop_data) => {
// Decrypt the blob with DEC(nonce, DH(the SR's public key, this hop's secret)
let node_id_secret = self.routing_table.node_id_secret_key(crypto_kind);
let Ok(dh_secret) = vcrypto
.cached_dh(&safety_route.public_key.value, &node_id_secret) else {
return Ok(NetworkResult::invalid_message("dh failed for safety route hop"));
let Ok(dh_secret) =
vcrypto.cached_dh(&safety_route.public_key.value, &node_id_secret)
else {
return Ok(NetworkResult::invalid_message(
"dh failed for safety route hop",
));
};
let Ok(mut dec_blob_data) = vcrypto
.decrypt_aead(
let Ok(mut dec_blob_data) = vcrypto.decrypt_aead(
&route_hop_data.blob,
&route_hop_data.nonce,
&dh_secret,
None,
)
else {
return Ok(NetworkResult::invalid_message("failed to decrypt route hop data for safety route hop"));
) else {
return Ok(NetworkResult::invalid_message(
"failed to decrypt route hop data for safety route hop",
));
};
// See if this is last hop in safety route, if so, we're decoding a PrivateRoute not a RouteHop
@ -440,26 +478,35 @@ impl RPCProcessor {
};
let Ok(dec_blob_reader) = RPCMessageData::new(dec_blob_data).get_reader() else {
return Ok(NetworkResult::invalid_message("Failed to decode RPCMessageData from blob"));
return Ok(NetworkResult::invalid_message(
"Failed to decode RPCMessageData from blob",
));
};
// Decode the blob appropriately
if dec_blob_tag == 1 {
// PrivateRoute
let private_route = {
let Ok(pr_reader) = dec_blob_reader
.get_root::<veilid_capnp::private_route::Reader>() else {
return Ok(NetworkResult::invalid_message("failed to get private route reader for blob"));
let Ok(pr_reader) =
dec_blob_reader.get_root::<veilid_capnp::private_route::Reader>()
else {
return Ok(NetworkResult::invalid_message(
"failed to get private route reader for blob",
));
};
let Ok(private_route) = decode_private_route(&pr_reader) else {
return Ok(NetworkResult::invalid_message("failed to decode private route"));
return Ok(NetworkResult::invalid_message(
"failed to decode private route",
));
};
private_route
};
// Validate the private route
if let Err(_) = private_route.validate(self.crypto.clone()) {
return Ok(NetworkResult::invalid_message("failed to validate private route"));
if private_route.validate(self.crypto.clone()).is_err() {
return Ok(NetworkResult::invalid_message(
"failed to validate private route",
));
}
// Switching from full safety route to private route first hop
@ -474,19 +521,26 @@ impl RPCProcessor {
} else if dec_blob_tag == 0 {
// RouteHop
let route_hop = {
let Ok(rh_reader) = dec_blob_reader
.get_root::<veilid_capnp::route_hop::Reader>() else {
return Ok(NetworkResult::invalid_message("failed to get route hop reader for blob"));
let Ok(rh_reader) =
dec_blob_reader.get_root::<veilid_capnp::route_hop::Reader>()
else {
return Ok(NetworkResult::invalid_message(
"failed to get route hop reader for blob",
));
};
let Ok(route_hop) = decode_route_hop(&rh_reader) else {
return Ok(NetworkResult::invalid_message("failed to decode route hop"));
return Ok(NetworkResult::invalid_message(
"failed to decode route hop",
));
};
route_hop
};
// Validate the route hop
if let Err(_) = route_hop.validate(self.crypto.clone()) {
return Ok(NetworkResult::invalid_message("failed to validate route hop"));
if route_hop.validate(self.crypto.clone()).is_err() {
return Ok(NetworkResult::invalid_message(
"failed to validate route hop",
));
}
// Continue the full safety route with another hop
@ -543,7 +597,7 @@ impl RPCProcessor {
hop_count: private_route.hop_count - 1,
hops: route_hop
.next_hop
.map(|rhd| PrivateRouteHops::Data(rhd))
.map(PrivateRouteHops::Data)
.unwrap_or(PrivateRouteHops::Empty),
},
)

View File

@ -80,7 +80,7 @@ impl RPCProcessor {
);
let question = RPCQuestion::new(
network_result_try!(self.get_destination_respond_to(&dest)?),
RPCQuestionDetail::SetValueQ(set_value_q),
RPCQuestionDetail::SetValueQ(Box::new(set_value_q)),
);
let question_context = QuestionContext::SetValue(ValidateSetValueContext {
descriptor,
@ -292,7 +292,7 @@ impl RPCProcessor {
let set_value_a = RPCOperationSetValueA::new(set, new_value, closer_to_key_peers)?;
// Send SetValue answer
self.answer(msg, RPCAnswer::new(RPCAnswerDetail::SetValueA(set_value_a)))
self.answer(msg, RPCAnswer::new(RPCAnswerDetail::SetValueA(Box::new(set_value_a))))
.await
}
}

View File

@ -26,7 +26,7 @@ impl RPCProcessor {
}
let signal = RPCOperationSignal::new(signal_info);
let statement = RPCStatement::new(RPCStatementDetail::Signal(signal));
let statement = RPCStatement::new(RPCStatementDetail::Signal(Box::new(signal)));
// Send the signal request
self.statement(dest, statement).await

View File

@ -101,7 +101,7 @@ impl RPCProcessor {
let status_q = RPCOperationStatusQ::new(node_status);
let question = RPCQuestion::new(
network_result_try!(self.get_destination_respond_to(&dest)?),
RPCQuestionDetail::StatusQ(status_q),
RPCQuestionDetail::StatusQ(Box::new(status_q)),
);
let debug_string = format!("Status => {}", dest);
@ -249,7 +249,10 @@ impl RPCProcessor {
let status_a = RPCOperationStatusA::new(node_status, sender_info);
// Send status answer
self.answer(msg, RPCAnswer::new(RPCAnswerDetail::StatusA(status_a)))
self.answer(
msg,
RPCAnswer::new(RPCAnswerDetail::StatusA(Box::new(status_a))),
)
.await
}
}

View File

@ -21,7 +21,9 @@ impl RPCProcessor {
.map_err(RPCError::internal)?;
let validate_dial_info = RPCOperationValidateDialInfo::new(dial_info, receipt, redirect)?;
let statement = RPCStatement::new(RPCStatementDetail::ValidateDialInfo(validate_dial_info));
let statement = RPCStatement::new(RPCStatementDetail::ValidateDialInfo(Box::new(
validate_dial_info,
)));
// Send the validate_dial_info request
// This can only be sent directly, as relays can not validate dial info
@ -153,8 +155,9 @@ impl RPCProcessor {
// Make a copy of the request, without the redirect flag
let validate_dial_info =
RPCOperationValidateDialInfo::new(dial_info.clone(), receipt.clone(), false)?;
let statement =
RPCStatement::new(RPCStatementDetail::ValidateDialInfo(validate_dial_info));
let statement = RPCStatement::new(RPCStatementDetail::ValidateDialInfo(Box::new(
validate_dial_info,
)));
// Send the validate_dial_info request
// This can only be sent directly, as relays can not validate dial info

Some files were not shown because too many files have changed in this diff Show More