Skip to content

Commit

Permalink
feat(autonomi): get bootstrap peers in Client::init
Browse files Browse the repository at this point in the history
  • Loading branch information
b-zee committed Dec 9, 2024
1 parent dbcd2ab commit c01a91b
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 8 deletions.
24 changes: 24 additions & 0 deletions ant-networking/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,15 @@ pub enum NetworkSwarmCmd {
addr: Multiaddr,
sender: oneshot::Sender<Result<()>>,
},

/// Adds a peer address to the routing table.
///
/// See [`libp2p::kad::Behaviour::add_address`] for more details.
AddPeerAddresses {
addresses: Vec<(PeerId, Multiaddr)>,
sender: oneshot::Sender<()>,
},

// Get closest peers from the network
GetClosestPeersToAddressFromNetwork {
key: NetworkAddress,
Expand Down Expand Up @@ -320,6 +329,12 @@ impl Debug for NetworkSwarmCmd {
NetworkSwarmCmd::Dial { addr, .. } => {
write!(f, "NetworkSwarmCmd::Dial {{ addr: {addr:?} }}")
}
NetworkSwarmCmd::AddPeerAddresses { addresses, .. } => {
write!(
f,
"NetworkSwarmCmd::AddPeerAddresses {{ addresses: {addresses:?} }}"
)
}
NetworkSwarmCmd::GetNetworkRecord { key, cfg, .. } => {
write!(
f,
Expand Down Expand Up @@ -486,6 +501,15 @@ impl SwarmDriver {
Err(e) => sender.send(Err(e.into())),
};
}

NetworkSwarmCmd::AddPeerAddresses { addresses, sender } => {
cmd_string = "AddPeerAddresses";
for (peer, addr) in addresses {
let _update = self.swarm.behaviour_mut().kademlia.add_address(&peer, addr);
}
let _ = sender.send(());
}

NetworkSwarmCmd::GetClosestPeersToAddressFromNetwork { key, sender } => {
cmd_string = "GetClosestPeersToAddressFromNetwork";
let query_id = self
Expand Down
9 changes: 9 additions & 0 deletions ant-networking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@ impl Network {
receiver.await?
}

/// Adds a peer address to the routing table.
///
/// See [`libp2p::kad::Behaviour::add_address`] for more details.
pub async fn add_peer_addresses(&self, addresses: Vec<(PeerId, Multiaddr)>) -> Result<()> {
let (sender, receiver) = oneshot::channel();
self.send_network_swarm_cmd(NetworkSwarmCmd::AddPeerAddresses { addresses, sender });
Ok(receiver.await?)
}

/// Returns the closest peers to the given `XorName`, sorted by their distance to the xor_name.
/// Excludes the client's `PeerId` while calculating the closest peers.
pub async fn client_get_all_close_peers_in_range_or_close_group(
Expand Down
35 changes: 33 additions & 2 deletions autonomi/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ pub mod wasm;
// private module with utility functions
mod utils;

use ant_bootstrap::{BootstrapCacheConfig, BootstrapCacheStore};
use ant_bootstrap::{BootstrapCacheConfig, BootstrapCacheStore, PeersArgs};
pub use ant_evm::Amount;

use ant_networking::{interval, multiaddr_is_global, Network, NetworkBuilder, NetworkEvent};
use ant_protocol::{version::IDENTIFY_PROTOCOL_STR, CLOSE_GROUP_SIZE};
use libp2p::{identity::Keypair, Multiaddr};
use libp2p::{identity::Keypair, multiaddr::Protocol, Multiaddr};
use std::{collections::HashSet, sync::Arc, time::Duration};
use tokio::sync::mpsc;

Expand Down Expand Up @@ -77,6 +77,37 @@ pub enum ConnectError {
}

impl Client {
pub async fn init() -> Result<Self, ant_bootstrap::Error> {
// Get list of peers for bootstrapping to the network.
let peers = match PeersArgs::default().get_addrs(None).await {
Ok(peers) => peers,
Err(e) => return Err(e),
};

let (network, _event_receiver) = build_client_and_run_swarm(true);

let peers_len = peers.len();
// Add peers to the routing table.
let peers_with_p2p: Vec<_> = peers
.into_iter()
.filter_map(|addr| {
addr.iter().find_map(|p| match p {
Protocol::P2p(id) => Some((id, addr.clone())),
_ => None,
})
})
.collect();
if peers_with_p2p.len() < peers_len {
tracing::warn!("Some bootstrap addresses have no peer ID, skipping them");
}
let _ = network.add_peer_addresses(peers_with_p2p).await;

Ok(Self {
network,
client_event_sender: Arc::new(None),
})
}

/// Connect to the network.
///
/// This will timeout after [`CONNECT_TIMEOUT_SECS`] secs.
Expand Down
8 changes: 2 additions & 6 deletions autonomi/tests/put.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,18 @@
use ant_logging::LogBuilder;
use autonomi::Client;
use eyre::Result;
use std::time::Duration;
use test_utils::{evm::get_funded_wallet, gen_random_data, peers_from_env};
use tokio::time::sleep;
use test_utils::{evm::get_funded_wallet, gen_random_data};

#[tokio::test]
async fn put() -> Result<()> {
let _log_appender_guard = LogBuilder::init_single_threaded_tokio_test("put", false);

let client = Client::connect(&peers_from_env()?).await?;
let client = Client::init().await?;
let wallet = get_funded_wallet();
let data = gen_random_data(1024 * 1024 * 10);

let addr = client.data_put_public(data.clone(), wallet.into()).await?;

sleep(Duration::from_secs(10)).await;

let data_fetched = client.data_get_public(addr).await?;
assert_eq!(data, data_fetched, "data fetched should match data put");

Expand Down

0 comments on commit c01a91b

Please sign in to comment.