Skip to content

Commit

Permalink
feat(manager): implement PeersArgs into ant node manager
Browse files Browse the repository at this point in the history
  • Loading branch information
RolandSherwin committed Dec 7, 2024
1 parent 9c2433b commit a1afb70
Show file tree
Hide file tree
Showing 19 changed files with 2,233 additions and 726 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions ant-bootstrap/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub enum Error {
FailedToObtainAddrsFromUrl(String, usize),
#[error("No Bootstrap Addresses found: {0}")]
NoBootstrapAddressesFound(String),
#[error("Failed to parse Url")]
FailedToParseUrl,
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("JSON error: {0}")]
Expand Down
63 changes: 40 additions & 23 deletions ant-bootstrap/src/initial_peers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ use crate::{
};
use clap::Args;
use libp2p::Multiaddr;
use serde::{Deserialize, Serialize};
use url::Url;

/// The name of the environment variable that can be used to pass peers to the node.
pub const ANT_PEERS_ENV: &str = "ANT_PEERS";

/// Command line arguments for peer configuration
#[derive(Args, Debug, Clone, Default)]
#[derive(Args, Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PeersArgs {
/// Set to indicate this is the first node in a new network
///
Expand All @@ -41,16 +42,15 @@ pub struct PeersArgs {
long = "peer",
value_name = "multiaddr",
value_delimiter = ',',
conflicts_with = "first",
value_parser = parse_multiaddr_str
conflicts_with = "first"
)]
pub addrs: Vec<Multiaddr>,
/// Specify the URL to fetch the network contacts from.
///
/// The URL can point to a text file containing Multiaddresses separated by newline character, or
/// a bootstrap cache JSON file.
#[clap(long, conflicts_with = "first")]
pub network_contacts_url: Option<Url>,
#[clap(long, conflicts_with = "first", value_delimiter = ',')]
pub network_contacts_url: Vec<String>,
/// Set to indicate this is a local network. You could also set the `local` feature flag to set this to true.
///
/// This would use mDNS for peer discovery.
Expand All @@ -59,7 +59,7 @@ pub struct PeersArgs {
/// Set to indicate this is a testnet.
///
/// This disables fetching peers from the mainnet network contacts.
#[clap(name = "testnet", long, conflicts_with = "network_contacts_url")]
#[clap(name = "testnet", long)]
pub disable_mainnet_contacts: bool,

/// Set to not load the bootstrap addresses from the local cache.
Expand Down Expand Up @@ -115,23 +115,21 @@ impl PeersArgs {
warn!("Invalid multiaddress format from arguments: {addr}");
}
}

// Read from ANT_PEERS environment variable if present
if let Ok(addrs) = std::env::var(ANT_PEERS_ENV) {
for addr_str in addrs.split(',') {
if let Some(addr) = craft_valid_multiaddr_from_str(addr_str, false) {
info!("Adding addr from environment variable: {addr}");
bootstrap_addresses.push(BootstrapAddr::new(addr));
} else {
warn!("Invalid multiaddress format from environment variable: {addr_str}");
}
}
}
bootstrap_addresses.extend(Self::read_bootstrap_addr_from_env());

// If we have a network contacts URL, fetch addrs from there.
if let Some(url) = self.network_contacts_url.clone() {
info!("Fetching bootstrap address from network contacts URL: {url}",);
let contacts_fetcher = ContactsFetcher::with_endpoints(vec![url])?;
if !self.network_contacts_url.is_empty() {
info!(
"Fetching bootstrap address from network contacts URLs: {:?}",
self.network_contacts_url
);
let addrs = self
.network_contacts_url
.iter()
.map(|url| url.parse::<Url>().map_err(|_| Error::FailedToParseUrl))
.collect::<Result<Vec<Url>>>()?;
let contacts_fetcher = ContactsFetcher::with_endpoints(addrs)?;
let addrs = contacts_fetcher.fetch_bootstrap_addresses().await?;
bootstrap_addresses.extend(addrs);
}
Expand Down Expand Up @@ -185,8 +183,27 @@ impl PeersArgs {
Err(Error::NoBootstrapPeersFound)
}
}
}

pub fn parse_multiaddr_str(addr: &str) -> std::result::Result<Multiaddr, libp2p::multiaddr::Error> {
addr.parse::<Multiaddr>()
pub fn read_addr_from_env() -> Vec<Multiaddr> {
Self::read_bootstrap_addr_from_env()
.into_iter()
.map(|addr| addr.addr)
.collect()
}

pub fn read_bootstrap_addr_from_env() -> Vec<BootstrapAddr> {
let mut bootstrap_addresses = Vec::new();
// Read from ANT_PEERS environment variable if present
if let Ok(addrs) = std::env::var(ANT_PEERS_ENV) {
for addr_str in addrs.split(',') {
if let Some(addr) = craft_valid_multiaddr_from_str(addr_str, false) {
info!("Adding addr from environment variable: {addr}");
bootstrap_addresses.push(BootstrapAddr::new(addr));
} else {
warn!("Invalid multiaddress format from environment variable: {addr_str}");
}
}
}
bootstrap_addresses
}
}
4 changes: 2 additions & 2 deletions ant-bootstrap/tests/address_format_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async fn test_multiaddr_format_parsing() -> Result<(), Box<dyn std::error::Error
let args = PeersArgs {
first: false,
addrs: vec![addr.clone()],
network_contacts_url: None,
network_contacts_url: vec![],
local: false,
disable_mainnet_contacts: false,
ignore_cache: false,
Expand Down Expand Up @@ -82,7 +82,7 @@ async fn test_network_contacts_format() -> Result<(), Box<dyn std::error::Error>
let args = PeersArgs {
first: false,
addrs: vec![],
network_contacts_url: Some(format!("{}/peers", mock_server.uri()).parse()?),
network_contacts_url: vec![format!("{}/peers", mock_server.uri()).parse()?],
local: false,
disable_mainnet_contacts: false,
ignore_cache: false,
Expand Down
10 changes: 5 additions & 5 deletions ant-bootstrap/tests/cli_integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ async fn test_first_flag() -> Result<(), Box<dyn std::error::Error>> {
let args = PeersArgs {
first: true,
addrs: vec![],
network_contacts_url: None,
network_contacts_url: vec![],
local: false,
disable_mainnet_contacts: false,
ignore_cache: false,
Expand All @@ -56,7 +56,7 @@ async fn test_peer_argument() -> Result<(), Box<dyn std::error::Error>> {
let args = PeersArgs {
first: false,
addrs: vec![peer_addr.clone()],
network_contacts_url: None,
network_contacts_url: vec![],
local: false,
disable_mainnet_contacts: true,
ignore_cache: false,
Expand Down Expand Up @@ -90,7 +90,7 @@ async fn test_network_contacts_fallback() -> Result<(), Box<dyn std::error::Erro
let args = PeersArgs {
first: false,
addrs: vec![],
network_contacts_url: Some(format!("{}/peers", mock_server.uri()).parse()?),
network_contacts_url: vec![format!("{}/peers", mock_server.uri()).parse()?],
local: false,
disable_mainnet_contacts: false,
ignore_cache: false,
Expand Down Expand Up @@ -120,7 +120,7 @@ async fn test_local_mode() -> Result<(), Box<dyn std::error::Error>> {
let args = PeersArgs {
first: false,
addrs: vec![],
network_contacts_url: None,
network_contacts_url: vec![],
local: true,
disable_mainnet_contacts: false,
ignore_cache: false,
Expand Down Expand Up @@ -155,7 +155,7 @@ async fn test_test_network_peers() -> Result<(), Box<dyn std::error::Error>> {
let args = PeersArgs {
first: false,
addrs: vec![peer_addr.clone()],
network_contacts_url: None,
network_contacts_url: vec![],
local: false,
disable_mainnet_contacts: true,
ignore_cache: false,
Expand Down
Loading

0 comments on commit a1afb70

Please sign in to comment.