Skip to content

Commit

Permalink
fix: use proper default port (#1355)
Browse files Browse the repository at this point in the history
  • Loading branch information
iduartgomez authored Jan 2, 2025
1 parent 7cd002b commit 5c3c3c9
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 54 deletions.
73 changes: 43 additions & 30 deletions crates/core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub struct ConfigArgs {
pub ws_api: WebsocketApiArgs,

#[clap(flatten)]
pub network_listener: NetworkArgs,
pub network_api: NetworkArgs,

#[clap(flatten)]
pub secrets: SecretArgs,
Expand All @@ -75,15 +75,16 @@ impl Default for ConfigArgs {
fn default() -> Self {
Self {
mode: Some(OperationMode::Network),
network_listener: NetworkArgs {
address: Some(default_address()),
network_port: Some(default_network_port()),
network_api: NetworkArgs {
address: Some(default_listening_address()),
network_port: Some(default_network_api_port()),
public_address: None,
public_port: None,
is_gateway: false,
load_from_network: false,
},
ws_api: WebsocketApiArgs {
address: Some(default_address()),
address: Some(default_listening_address()),
ws_api_port: Some(default_http_gateway_port()),
},
secrets: Default::default(),
Expand Down Expand Up @@ -216,22 +217,26 @@ impl ConfigArgs {
let secrets = self.secrets.build()?;

let peer_id = self
.network_listener
.network_api
.public_address
.zip(self.network_listener.public_port)
.zip(self.network_api.public_port)
.map(|(addr, port)| {
PeerId::new(
(addr, port).into(),
secrets.transport_keypair.public().clone(),
)
});
let gateways_file = config_paths.config_dir.join("gateways.toml");
let remotely_loaded_gateways = load_gateways_from_index(
"https://freenet.org/gateways.toml",
&config_paths.secrets_dir,
)
.await
.unwrap_or_default();
let remotely_loaded_gateways = if self.network_api.load_from_network {
load_gateways_from_index(
"https://freenet.org/gateways.toml",
&config_paths.secrets_dir,
)
.await
.unwrap_or_default()
} else {
Gateways::default()
};
let mut gateways = match File::open(&*gateways_file) {
Ok(mut file) => {
let mut content = String::new();
Expand Down Expand Up @@ -268,21 +273,21 @@ impl ConfigArgs {
mode,
peer_id,
network_api: NetworkApiConfig {
address: self.network_listener.address.unwrap_or_else(|| match mode {
address: self.network_api.address.unwrap_or_else(|| match mode {
OperationMode::Local => default_local_address(),
OperationMode::Network => default_address(),
OperationMode::Network => default_listening_address(),
}),
port: self
.network_listener
.network_api
.network_port
.unwrap_or(default_network_port()),
public_address: self.network_listener.public_address,
public_port: self.network_listener.public_port,
.unwrap_or(default_network_api_port()),
public_address: self.network_api.public_address,
public_port: self.network_api.public_port,
},
ws_api: WebsocketApiConfig {
address: self.ws_api.address.unwrap_or_else(|| match mode {
OperationMode::Local => default_local_address(),
OperationMode::Network => default_address(),
OperationMode::Network => default_listening_address(),
}),
port: self
.ws_api
Expand All @@ -293,7 +298,7 @@ impl ConfigArgs {
log_level: self.log_level.unwrap_or(tracing::log::LevelFilter::Info),
config_paths: Arc::new(config_paths),
gateways: gateways.gateways,
is_gateway: self.network_listener.is_gateway,
is_gateway: self.network_api.is_gateway,
};

fs::create_dir_all(this.config_dir())?;
Expand Down Expand Up @@ -422,30 +427,36 @@ pub struct NetworkArgs {
/// If the node is a gateway, it will be able to accept connections from other nodes.
#[arg(long)]
pub is_gateway: bool,

/// Load gateway configurations from the network and merge it with existing one.
#[arg(long, default_value = "true", env = "LOAD_FROM_NETWORK")]
pub load_from_network: bool,
}

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct NetworkApiConfig {
/// Address to bind to
#[serde(default = "default_address", rename = "network-address")]
/// Address to listen to locally
#[serde(default = "default_listening_address", rename = "network-address")]
pub address: IpAddr,

/// Port to expose api on
#[serde(default = "default_network_port", rename = "network-port")]
#[serde(default = "default_network_api_port", rename = "network-port")]
pub port: u16,

/// Public external address for the network, mandatory for gateways.
#[serde(
rename = "public_network_address",
skip_serializing_if = "Option::is_none"
)]
pub public_address: Option<IpAddr>,

/// Public external port for the network, mandatory for gateways.
#[serde(rename = "public_port", skip_serializing_if = "Option::is_none")]
pub public_port: Option<u16>,
}

#[inline]
const fn default_network_port() -> u16 {
pub const fn default_network_api_port() -> u16 {
31337
}

Expand All @@ -469,7 +480,7 @@ pub struct WebsocketApiArgs {
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct WebsocketApiConfig {
/// Address to bind to
#[serde(default = "default_address", rename = "ws-api-address")]
#[serde(default = "default_listening_address", rename = "ws-api-address")]
pub address: IpAddr,

/// Port to expose api on
Expand All @@ -490,14 +501,14 @@ impl Default for WebsocketApiConfig {
#[inline]
fn default() -> Self {
Self {
address: default_address(),
address: default_listening_address(),
port: default_http_gateway_port(),
}
}
}

#[inline]
const fn default_address() -> IpAddr {
const fn default_listening_address() -> IpAddr {
IpAddr::V4(Ipv4Addr::UNSPECIFIED)
}

Expand All @@ -507,7 +518,7 @@ const fn default_local_address() -> IpAddr {
}

#[inline]
pub(crate) const fn default_http_gateway_port() -> u16 {
const fn default_http_gateway_port() -> u16 {
50509
}

Expand Down Expand Up @@ -989,7 +1000,9 @@ mod tests {
let gateways = Gateways {
gateways: vec![
GatewayConfig {
address: Address::HostAddress(([127, 0, 0, 1], default_network_port()).into()),
address: Address::HostAddress(
([127, 0, 0, 1], default_network_api_port()).into(),
),
public_key_path: PathBuf::from("path/to/key"),
},
GatewayConfig {
Expand Down
15 changes: 6 additions & 9 deletions crates/core/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,11 +176,8 @@ impl NodeConfig {
match hostname.rsplit_once(':') {
None => {
// no port found, use default
let hostname_with_port = format!(
"{}:{}",
hostname,
crate::config::default_http_gateway_port()
);
let hostname_with_port =
format!("{}:{}", hostname, crate::config::default_network_api_port());

if let Ok(mut addrs) = hostname_with_port.to_socket_addrs() {
if let Some(addr) = addrs.next() {
Expand Down Expand Up @@ -227,7 +224,7 @@ impl NodeConfig {
match ips.into_iter().next() {
Some(ip) => Ok(SocketAddr::new(
ip,
port.unwrap_or_else(crate::config::default_http_gateway_port),
port.unwrap_or_else(crate::config::default_network_api_port),
)),
None => Err(anyhow::anyhow!("Fail to resolve IP address of {hostname}")),
}
Expand Down Expand Up @@ -1017,20 +1014,20 @@ mod tests {
socket_addr
== SocketAddr::new(
IpAddr::V4(Ipv4Addr::LOCALHOST),
crate::config::default_http_gateway_port()
crate::config::default_network_api_port()
)
|| socket_addr
== SocketAddr::new(
IpAddr::V6(Ipv6Addr::LOCALHOST),
crate::config::default_http_gateway_port()
crate::config::default_network_api_port()
)
);

let addr = Address::Hostname("google.com".to_string());
let socket_addr = NodeConfig::parse_socket_addr(&addr).await.unwrap();
assert_eq!(
socket_addr.port(),
crate::config::default_http_gateway_port()
crate::config::default_network_api_port()
);

let addr = Address::Hostname("google.com:8080".to_string());
Expand Down
12 changes: 6 additions & 6 deletions scripts/freenet-setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# freenet-setup.sh - Unified Gateway and Node setup script

# Check if required parameters are provided
# Ahora sólo esperamos 3 parámetros: <name> <type> <gw-host>
# Only expects 3 parameters: <name> <type> <gw-host>
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Usage: $0 <name> <type> <gw-host>"
echo "Example: $0 my-node node vega.locut.us"
Expand All @@ -13,13 +13,13 @@ NAME="$1"
TYPE="$2"
GW_HOST="$3"

# Validar el TYPE
# Validate TYPE
if [[ "$TYPE" != "gateway" && "$TYPE" != "node" ]]; then
echo "Error: Type must be either 'gateway' or 'node'."
exit 1
fi

# Si es node, necesitamos GW_HOST (aunque ya lo recibimos en $3).
# If is a regular node, require GW_HOST.
if [[ "$TYPE" == "node" && -z "$GW_HOST" ]]; then
echo "Error: <gw-host> parameter is required for node setup."
exit 1
Expand Down Expand Up @@ -58,13 +58,13 @@ fi
KEY_FILE="$KEYS_DIR/${NAME}_private_key.pem"
if [ ! -f "$KEY_FILE" ]; then
echo "Generating keys for $TYPE..."
openssl genpkey -algorithm RSA -out "$KEY_FILE"
openssl rsa -pubout -in "$KEY_FILE" -out "$KEYS_DIR/${NAME}_public_key.pem"
openssl genpkey -algorithm RSA -out "$KEY_FILE" -pkeyopt rsa_keygen_bits:4096
openssl pkey -in "$KEY_FILE" -pubout -out "$KEYS_DIR/${NAME}_public_key.pem"
else
echo "Keys already exist. Skipping key generation."
fi

# Si es nodo, creamos el archivo gateways.toml (sin descargar nada por SSH/SCP).
# If is a regular node, generate the gateways.toml file
if [[ "$TYPE" == "node" ]]; then
GATEWAY_CONFIG="$BASE_DIR/gateways.toml"
echo "Configuring gateways.toml for node..."
Expand Down
13 changes: 4 additions & 9 deletions scripts/local-network.mk
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,9 @@ create-dirs:
generate-keys:
@echo "→ Generating RSA keys..."
@for i in $$(seq 1 $(N_GATEWAYS)); do \
openssl genpkey -algorithm RSA -out $(KEYS_DIR)/gw$${i}_private_key.pem && \
openssl rsa -pubout -in $(KEYS_DIR)/gw$${i}_private_key.pem \
-out $(KEYS_DIR)/gw$${i}_public_key.pem; \
done
@for i in $$(seq 1 $(N_NODES)); do \
openssl genpkey -algorithm RSA -out $(BASE_DIR)/n$$i/n$${i}_private_key.pem && \
openssl rsa -pubout -in $(BASE_DIR)/n$$i/n$${i}_private_key.pem \
-out $(BASE_DIR)/n$$i/n$${i}_public_key.pem; \
openssl genpkey -algorithm RSA -out $(KEYS_DIR)/gw$${i}_private_key.pem -pkeyopt rsa_keygen_bits:4096 && \
openssl pkey -in $(KEYS_DIR)/gw$${i}_private_key.pem \
-pubout -out $(KEYS_DIR)/gw$${i}_public_key.pem; \
done

# Network Management
Expand Down Expand Up @@ -126,7 +121,7 @@ start-nodes:
--public-network-port $$public_port \
--db-dir $(BASE_DIR)/n$$i \
--network-port $$network_port \
--transport-keypair $(BASE_DIR)/n$$i/n$${i}_private_key.pem $(call LOG_CMD,$(LOGS_DIR)/n$$i.log)) & \
$(call LOG_CMD,$(LOGS_DIR)/n$$i.log)) & \
echo $$! > $(PID_DIR)/n$$i.pid; \
echo " Node $$i: network=$$network_port, ws=$$ws_port, public=$$public_port (PID: $$!)"; \
if [ $$i -lt $(N_NODES) ]; then \
Expand Down

0 comments on commit 5c3c3c9

Please sign in to comment.