Skip to content

Commit

Permalink
feat!: use a simple network id to differentiate between network
Browse files Browse the repository at this point in the history
  • Loading branch information
RolandSherwin committed Dec 9, 2024
1 parent f53c275 commit 31fbdb5
Show file tree
Hide file tree
Showing 10 changed files with 160 additions and 73 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.

4 changes: 2 additions & 2 deletions ant-bootstrap/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// permissions and limitations relating to use of the SAFE Network Software.

use crate::error::{Error, Result};
use ant_protocol::version::{get_key_version_str, get_truncate_version_str};
use ant_protocol::version::{get_network_id, get_truncate_version_str};
use std::{
path::{Path, PathBuf},
time::Duration,
Expand Down Expand Up @@ -118,7 +118,7 @@ fn default_cache_path() -> Result<PathBuf> {

std::fs::create_dir_all(&dir)?;

let network_id = format!("{}_{}", get_key_version_str(), get_truncate_version_str());
let network_id = format!("{}_{}", get_network_id(), get_truncate_version_str());
let path = dir.join(format!("bootstrap_cache_{}.json", network_id));

Ok(path)
Expand Down
1 change: 1 addition & 0 deletions ant-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ harness = false
ant-bootstrap = { path = "../ant-bootstrap", version = "0.1.0" }
ant-build-info = { path = "../ant-build-info", version = "0.1.19" }
ant-logging = { path = "../ant-logging", version = "0.2.40" }
ant-protocol = { path = "../ant-protocol", version = "0.17.15" }
autonomi = { path = "../autonomi", version = "0.2.4", features = [
"fs",
"vault",
Expand Down
3 changes: 3 additions & 0 deletions ant-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ use tracing::Level;
async fn main() -> Result<()> {
color_eyre::install().expect("Failed to initialise error handler");
let opt = Opt::parse();
if let Some(network_id) = opt.network_id {
ant_protocol::version::set_network_id(network_id);
}
let _log_guards = init_logging_and_metrics(&opt)?;
#[cfg(feature = "metrics")]
tokio::spawn(init_metrics(std::process::id()));
Expand Down
6 changes: 6 additions & 0 deletions ant-cli/src/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ pub(crate) struct Opt {
#[clap(long = "timeout", global = true, value_parser = |t: &str| -> Result<Duration> { Ok(t.parse().map(Duration::from_secs)?) })]
pub connection_timeout: Option<Duration>,

/// Specify the network ID to use. This will allow you to run the CLI on a different network.
///
/// By default, the network ID is set to 1, which represents the mainnet.
#[clap(long, verbatim_doc_comment)]
pub network_id: Option<u8>,

/// Prevent verification of data storage on the network.
///
/// This may increase operation speed, but offers no guarantees that operations were successful.
Expand Down
54 changes: 34 additions & 20 deletions ant-networking/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use ant_protocol::{
messages::{ChunkProof, Nonce, Request, Response},
storage::{try_deserialize_record, RetryStrategy},
version::{
get_key_version_str, IDENTIFY_CLIENT_VERSION_STR, IDENTIFY_NODE_VERSION_STR,
get_network_id, IDENTIFY_CLIENT_VERSION_STR, IDENTIFY_NODE_VERSION_STR,
IDENTIFY_PROTOCOL_STR, REQ_RESPONSE_VERSION_STR,
},
NetworkAddress, PrettyPrintKBucketKey, PrettyPrintRecordKey,
Expand Down Expand Up @@ -267,16 +267,16 @@ pub(super) struct NodeBehaviour {
#[derive(Debug)]
pub struct NetworkBuilder {
bootstrap_cache: Option<BootstrapCacheStore>,
concurrency_limit: Option<usize>,
is_behind_home_network: bool,
keypair: Keypair,
local: bool,
listen_addr: Option<SocketAddr>,
request_timeout: Option<Duration>,
concurrency_limit: Option<usize>,
local: bool,
#[cfg(feature = "open-metrics")]
metrics_registries: Option<MetricsRegistries>,
#[cfg(feature = "open-metrics")]
metrics_server_port: Option<u16>,
request_timeout: Option<Duration>,
#[cfg(feature = "upnp")]
upnp: bool,
}
Expand All @@ -285,16 +285,16 @@ impl NetworkBuilder {
pub fn new(keypair: Keypair, local: bool) -> Self {
Self {
bootstrap_cache: None,
concurrency_limit: None,
is_behind_home_network: false,
keypair,
local,
listen_addr: None,
request_timeout: None,
concurrency_limit: None,
local,
#[cfg(feature = "open-metrics")]
metrics_registries: None,
#[cfg(feature = "open-metrics")]
metrics_server_port: None,
request_timeout: None,
#[cfg(feature = "upnp")]
upnp: false,
}
Expand Down Expand Up @@ -394,7 +394,7 @@ impl NetworkBuilder {
check_and_wipe_storage_dir_if_necessary(
root_dir.clone(),
storage_dir_path.clone(),
get_key_version_str(),
get_network_id(),
)?;

// Configures the disk_store to store records under the provided path and increase the max record size
Expand Down Expand Up @@ -431,7 +431,6 @@ impl NetworkBuilder {
Some(store_cfg),
false,
ProtocolSupport::Full,
IDENTIFY_NODE_VERSION_STR.to_string(),
#[cfg(feature = "upnp")]
upnp,
)?;
Expand Down Expand Up @@ -482,7 +481,6 @@ impl NetworkBuilder {
None,
true,
ProtocolSupport::Outbound,
IDENTIFY_CLIENT_VERSION_STR.to_string(),
#[cfg(feature = "upnp")]
false,
)?;
Expand All @@ -497,9 +495,13 @@ impl NetworkBuilder {
record_store_cfg: Option<NodeRecordStoreConfig>,
is_client: bool,
req_res_protocol: ProtocolSupport,
identify_version: String,
#[cfg(feature = "upnp")] upnp: bool,
) -> Result<(Network, mpsc::Receiver<NetworkEvent>, SwarmDriver)> {
let identify_protocol_str = IDENTIFY_PROTOCOL_STR
.read()
.expect("Failed to obtain read lock for IDENTIFY_PROTOCOL_STR")
.clone();

let peer_id = PeerId::from(self.keypair.public());
// vdash metric (if modified please notify at https://github.com/happybeing/vdash/issues):
#[cfg(not(target_arch = "wasm32"))]
Expand Down Expand Up @@ -563,7 +565,7 @@ impl NetworkBuilder {
"The protocol version string that is used to connect to the correct network",
Info::new(vec![(
"identify_protocol_str".to_string(),
IDENTIFY_PROTOCOL_STR.to_string(),
identify_protocol_str.clone(),
)]),
);

Expand All @@ -577,14 +579,16 @@ impl NetworkBuilder {
let request_response = {
let cfg = RequestResponseConfig::default()
.with_request_timeout(self.request_timeout.unwrap_or(REQUEST_TIMEOUT_DEFAULT_S));
let req_res_version_str = REQ_RESPONSE_VERSION_STR
.read()
.expect("Failed to obtain read lock for REQ_RESPONSE_VERSION_STR")
.clone();

info!(
"Building request response with {:?}",
REQ_RESPONSE_VERSION_STR.as_str()
);
info!("Building request response with {req_res_version_str:?}",);
request_response::cbor::Behaviour::new(
[(
StreamProtocol::new(&REQ_RESPONSE_VERSION_STR),
StreamProtocol::try_from_owned(req_res_version_str)
.expect("StreamProtocol should start with a /"),
req_res_protocol,
)],
cfg,
Expand Down Expand Up @@ -640,12 +644,22 @@ impl NetworkBuilder {
#[cfg(feature = "local")]
let mdns = mdns::tokio::Behaviour::new(mdns_config, peer_id)?;

let agent_version = if is_client {
IDENTIFY_CLIENT_VERSION_STR
.read()
.expect("Failed to obtain read lock for IDENTIFY_CLIENT_VERSION_STR")
.clone()
} else {
IDENTIFY_NODE_VERSION_STR
.read()
.expect("Failed to obtain read lock for IDENTIFY_NODE_VERSION_STR")
.clone()
};
// Identify Behaviour
let identify_protocol_str = IDENTIFY_PROTOCOL_STR.to_string();
info!("Building Identify with identify_protocol_str: {identify_protocol_str:?} and identify_version: {identify_version:?}");
info!("Building Identify with identify_protocol_str: {identify_protocol_str:?} and identify_protocol_str: {identify_protocol_str:?}");
let identify = {
let cfg = libp2p::identify::Config::new(identify_protocol_str, self.keypair.public())
.with_agent_version(identify_version)
.with_agent_version(agent_version)
// Enlength the identify interval from default 5 mins to 1 hour.
.with_interval(RESEND_IDENTIFY_INVERVAL);
libp2p::identify::Behaviour::new(cfg)
Expand Down
11 changes: 7 additions & 4 deletions ant-networking/src/event/swarm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,13 @@ impl SwarmDriver {
} => {
debug!(conn_id=%connection_id, %peer_id, ?info, "identify: received info");

if info.protocol_version != IDENTIFY_PROTOCOL_STR.to_string() {
warn!(?info.protocol_version, "identify: {peer_id:?} does not have the same protocol. Our IDENTIFY_PROTOCOL_STR: {:?}", IDENTIFY_PROTOCOL_STR.as_str());
let our_identify_protocol = IDENTIFY_PROTOCOL_STR.read().expect("IDENTIFY_PROTOCOL_STR has been locked to write. A call to set_network_id performed. This should not happen.").to_string();

if info.protocol_version != our_identify_protocol {
warn!(?info.protocol_version, "identify: {peer_id:?} does not have the same protocol. Our IDENTIFY_PROTOCOL_STR: {our_identify_protocol:?}");

self.send_event(NetworkEvent::PeerWithUnsupportedProtocol {
our_protocol: IDENTIFY_PROTOCOL_STR.to_string(),
our_protocol: our_identify_protocol,
their_protocol: info.protocol_version,
});
// Block the peer from any further communication.
Expand All @@ -143,8 +145,9 @@ impl SwarmDriver {
return Ok(());
}

let our_agent_version = IDENTIFY_NODE_VERSION_STR.read().expect("IDENTIFY_NODE_VERSION_STR has been locked to write. A call to set_network_id performed. This should not happen.").to_string();
// if client, return.
if info.agent_version != IDENTIFY_NODE_VERSION_STR.to_string() {
if info.agent_version != our_agent_version {
return Ok(());
}

Expand Down
21 changes: 17 additions & 4 deletions ant-node/src/bin/antnode/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use ant_node::{Marker, NodeBuilder, NodeEvent, NodeEventsReceiver};
use ant_protocol::{
node::get_antnode_root_dir,
node_rpc::{NodeCtrl, StopResult},
version::IDENTIFY_PROTOCOL_STR,
version,
};
use clap::{command, Parser};
use color_eyre::{eyre::eyre, Result};
Expand Down Expand Up @@ -128,6 +128,12 @@ struct Opt {
#[clap(long, verbatim_doc_comment)]
max_archived_log_files: Option<usize>,

/// Specify the network ID to use. This will allow you to run the node on a different network.
///
/// By default, the network ID is set to 1, which represents the mainnet.
#[clap(long, verbatim_doc_comment)]
network_id: Option<u8>,

/// Specify the rewards address.
/// The rewards address is the address that will receive the rewards for the node.
/// It should be a valid EVM address.
Expand Down Expand Up @@ -217,13 +223,20 @@ fn main() -> Result<()> {
color_eyre::install()?;
let opt = Opt::parse();

if let Some(network_id) = opt.network_id {
version::set_network_id(network_id);
}

let identify_protocol_str = version::IDENTIFY_PROTOCOL_STR
.read()
.expect("Failed to obtain read lock for IDENTIFY_PROTOCOL_STR");
if opt.version {
println!(
"{}",
ant_build_info::version_string(
"Autonomi Node",
env!("CARGO_PKG_VERSION"),
Some(&IDENTIFY_PROTOCOL_STR)
Some(&identify_protocol_str)
)
);
return Ok(());
Expand All @@ -240,7 +253,7 @@ fn main() -> Result<()> {
}

if opt.protocol_version {
println!("Network version: {}", *IDENTIFY_PROTOCOL_STR);
println!("Network version: {identify_protocol_str}");
return Ok(());
}

Expand Down Expand Up @@ -279,7 +292,7 @@ fn main() -> Result<()> {
);
info!("\n{}\n{}", msg, "=".repeat(msg.len()));

ant_build_info::log_version_info(env!("CARGO_PKG_VERSION"), &IDENTIFY_PROTOCOL_STR);
ant_build_info::log_version_info(env!("CARGO_PKG_VERSION"), &identify_protocol_str);
debug!(
"antnode built with git version: {}",
ant_build_info::git_info()
Expand Down
Loading

0 comments on commit 31fbdb5

Please sign in to comment.