Skip to content

Commit

Permalink
refactor: remove all changes to sn_networking
Browse files Browse the repository at this point in the history
  • Loading branch information
dirvine committed Nov 22, 2024
1 parent b8dce02 commit 4dd9829
Show file tree
Hide file tree
Showing 4 changed files with 2 additions and 91 deletions.
4 changes: 0 additions & 4 deletions sn_networking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ loud = []

[dependencies]
lazy_static = "~1.4.0"
chrono = { version = "0.4", features = ["serde"] }
serde_json = "1.0"
libp2p = { version = "0.54.1", features = [
"tokio",
"dns",
Expand Down Expand Up @@ -80,8 +78,6 @@ sha2 = "0.10"
walkdir = "~2.5.0"
strum = { version = "0.26.2", features = ["derive"] }
void = "1.0.2"
bootstrap_cache = { path = "../bootstrap_cache" }
tempfile = "3.8"

[dev-dependencies]
assert_fs = "1.0.0"
Expand Down
8 changes: 0 additions & 8 deletions sn_networking/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,6 @@ impl Debug for GetRecordError {
/// Network Errors
#[derive(Debug, Error)]
pub enum NetworkError {
#[error("Invalid address: {0}")]
InvalidAddress(String),
#[error("Cache error: {0}")]
CacheError(String),
#[error("Record store error: {0}")]
RecordStoreError(String),
#[error("Serialization error: {0}")]
SerializationError(String),
#[error("Dial Error")]
DialError(#[from] DialError),

Expand Down
2 changes: 0 additions & 2 deletions sn_networking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ pub mod target_arch;
mod transfers;
mod transport;

// Removed the bootstrap_cache module and its imports

use cmd::LocalSwarmCmd;
use xor_name::XorName;

Expand Down
79 changes: 2 additions & 77 deletions sn_networking/src/network_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@
// permissions and limitations relating to use of the SAFE Network Software.

use crate::target_arch::Instant;
use bootstrap_cache::CacheStore;
use libp2p::{kad::KBucketKey, PeerId, Multiaddr};
use libp2p::{kad::KBucketKey, PeerId};
use rand::{thread_rng, Rng};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use sn_protocol::NetworkAddress;
use std::collections::{btree_map::Entry, BTreeMap};
use std::sync::Arc;

// The number of PeerId to generate when starting an instance of NetworkDiscovery
const INITIAL_GENERATION_ATTEMPTS: usize = 10_000;
Expand All @@ -24,27 +22,14 @@ const MAX_PEERS_PER_BUCKET: usize = 5;

/// Keep track of NetworkAddresses belonging to every bucket (if we can generate them with reasonable effort)
/// which we can then query using Kad::GetClosestPeers to effectively fill our RT.
#[derive(Clone)]
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub(crate) struct NetworkDiscovery {
self_key: KBucketKey<PeerId>,
candidates: BTreeMap<u32, Vec<NetworkAddress>>,
peer_cache: Option<Arc<CacheStore>>,
}

impl std::fmt::Debug for NetworkDiscovery {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NetworkDiscovery")
.field("self_key", &self.self_key)
.field("candidates", &self.candidates)
.field("peer_cache", &"<CacheStore>")
.finish()
}
}

impl NetworkDiscovery {
/// Create a new instance of NetworkDiscovery and tries to populate each bucket with random peers.
#[allow(dead_code)]
pub(crate) fn new(self_peer_id: &PeerId) -> Self {
let start = Instant::now();
let self_key = KBucketKey::from(*self_peer_id);
Expand All @@ -63,53 +48,10 @@ impl NetworkDiscovery {
Self {
self_key,
candidates,
peer_cache: None,
}
}

/// Set the peer cache for this NetworkDiscovery instance
#[allow(dead_code)]
pub(crate) fn with_peer_cache(mut self, cache: Arc<CacheStore>) -> Self {
self.peer_cache = Some(cache);
self
}

/// Save the current peers to the peer cache
#[allow(dead_code)]
pub(crate) async fn save_peers_to_cache(&self) {
if let Some(cache) = &self.peer_cache {
for candidates in self.candidates.values() {
for candidate in candidates {
if let Ok(addr) = candidate.to_string().parse() {
let _ = cache.add_peer(addr).await;
}
}
}
}
}

/// Load peers from the peer cache and add them to our candidates
#[allow(dead_code)]
pub(crate) async fn load_peers_from_cache(&mut self) {
if let Some(cache) = &self.peer_cache {
let peers = cache.get_reliable_peers().await;
for peer in peers {
if let Ok(peer_id) = peer_id_from_multiaddr(&peer.addr) {
let network_addr = NetworkAddress::from_peer(peer_id);
if let Some(ilog2) = network_addr
.as_kbucket_key()
.distance(&self.self_key)
.ilog2()
{
self.insert_candidates(ilog2, vec![network_addr]);
}
}
}
}
}

/// The result from the kad::GetClosestPeers are again used to update our kbucket.
#[allow(dead_code)]
pub(crate) fn handle_get_closest_query(&mut self, closest_peers: Vec<PeerId>) {
let now = Instant::now();

Expand Down Expand Up @@ -141,7 +83,6 @@ impl NetworkDiscovery {

/// Returns one random candidate per bucket. Also tries to refresh the candidate list.
/// Todo: Limit the candidates to return. Favor the closest buckets.
#[allow(dead_code)]
pub(crate) fn candidates(&mut self) -> Vec<&NetworkAddress> {
self.try_refresh_candidates();

Expand All @@ -158,7 +99,6 @@ impl NetworkDiscovery {
}

/// Tries to refresh our current candidate list. We replace the old ones with new if we find any.
#[allow(dead_code)]
fn try_refresh_candidates(&mut self) {
let candidates_vec = Self::generate_candidates(&self.self_key, GENERATION_ATTEMPTS);
for (ilog2, candidates) in candidates_vec {
Expand All @@ -167,7 +107,6 @@ impl NetworkDiscovery {
}

// Insert the new candidates and remove the old ones to maintain MAX_PEERS_PER_BUCKET.
#[allow(dead_code)]
fn insert_candidates(&mut self, ilog2: u32, new_candidates: Vec<NetworkAddress>) {
match self.candidates.entry(ilog2) {
Entry::Occupied(mut entry) => {
Expand All @@ -193,7 +132,6 @@ impl NetworkDiscovery {
}

/// Uses rayon to parallelize the generation
#[allow(dead_code)]
fn generate_candidates(
self_key: &KBucketKey<PeerId>,
num_to_generate: usize,
Expand Down Expand Up @@ -233,16 +171,3 @@ impl NetworkDiscovery {
)
}
}

// Helper function to extract PeerId from Multiaddr
#[allow(dead_code)]
fn peer_id_from_multiaddr(addr: &Multiaddr) -> Result<PeerId, Box<dyn std::error::Error>> {
let components: Vec<_> = addr.iter().collect();
for component in components.iter().rev() {
if let libp2p::multiaddr::Protocol::P2p(hash) = component {
let err_conv = |e| Box::new(std::io::Error::new(std::io::ErrorKind::Other, format!("{e:?}")));
return Ok(PeerId::from_bytes(hash.to_bytes().as_slice()).map_err(err_conv)?);
}
}
Err("No PeerId found in Multiaddr".into())
}

0 comments on commit 4dd9829

Please sign in to comment.