Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: use a simple network id to differentiate between network #2508

Merged
merged 2 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -125,6 +125,6 @@ fn default_cache_path() -> Result<PathBuf> {

/// Returns the name of the cache file
pub fn cache_file_name() -> String {
let network_id = format!("{}_{}", get_key_version_str(), get_truncate_version_str());
let network_id = format!("{}_{}", get_network_id(), get_truncate_version_str());
format!("bootstrap_cache_{network_id}.json")
}
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
17 changes: 14 additions & 3 deletions ant-node-manager/src/add_services/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub struct InstallNodeServiceCtxBuilder {
pub log_dir_path: PathBuf,
pub log_format: Option<LogFormat>,
pub name: String,
pub network_id: Option<u8>,
pub max_archived_log_files: Option<usize>,
pub max_log_files: Option<usize>,
pub metrics_port: Option<u16>,
Expand All @@ -105,6 +106,10 @@ impl InstallNodeServiceCtxBuilder {
];

push_arguments_from_peers_args(&self.peers_args, &mut args);
if let Some(id) = self.network_id {
args.push(OsString::from("--network-id"));
args.push(OsString::from(id.to_string()));
}
if self.home_network {
args.push(OsString::from("--home-network"));
}
Expand Down Expand Up @@ -185,6 +190,7 @@ pub struct AddNodeServiceOptions {
pub max_archived_log_files: Option<usize>,
pub max_log_files: Option<usize>,
pub metrics_port: Option<PortRange>,
pub network_id: Option<u8>,
pub node_ip: Option<Ipv4Addr>,
pub node_port: Option<PortRange>,
pub owner: Option<String>,
Expand Down Expand Up @@ -314,10 +320,11 @@ mod tests {
home_network: false,
log_dir_path: PathBuf::from("/logs"),
log_format: None,
name: "test-node".to_string(),
max_archived_log_files: None,
max_log_files: None,
metrics_port: None,
name: "test-node".to_string(),
network_id: None,
node_ip: None,
node_port: None,
owner: None,
Expand Down Expand Up @@ -349,10 +356,11 @@ mod tests {
home_network: false,
log_dir_path: PathBuf::from("/logs"),
log_format: None,
name: "test-node".to_string(),
max_archived_log_files: None,
max_log_files: None,
metrics_port: None,
name: "test-node".to_string(),
network_id: None,
node_ip: None,
node_port: None,
owner: None,
Expand Down Expand Up @@ -385,10 +393,11 @@ mod tests {
home_network: false,
log_dir_path: PathBuf::from("/logs"),
log_format: None,
name: "test-node".to_string(),
max_archived_log_files: Some(10),
max_log_files: Some(10),
metrics_port: None,
name: "test-node".to_string(),
network_id: Some(5),
node_ip: None,
node_port: None,
owner: None,
Expand Down Expand Up @@ -510,6 +519,8 @@ mod tests {
"http://localhost:8080",

Check notice

Code scanning / devskim

Accessing localhost could indicate debug code, or could hinder scaling. Note

Do not leave debug code in production
"--testnet",
"--ignore-cache",
"--network-id",
"5",
"--home-network",
"--log-format",
"json",
Expand Down
2 changes: 2 additions & 0 deletions ant-node-manager/src/add_services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ pub async fn add_node(
max_log_files: options.max_log_files,
metrics_port: metrics_free_port,
name: service_name.clone(),
network_id: options.network_id,
node_ip: options.node_ip,
node_port,
owner: owner.clone(),
Expand Down Expand Up @@ -246,6 +247,7 @@ pub async fn add_node(
max_archived_log_files: options.max_archived_log_files,
max_log_files: options.max_log_files,
metrics_port: metrics_free_port,
network_id: options.network_id,
node_ip: options.node_ip,
node_port,
number: node_number,
Expand Down
Loading
Loading