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

Fixes for production deployment #20

Merged
merged 8 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
38 changes: 38 additions & 0 deletions Cargo.lock

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

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ edition = "2021"
[dependencies]
const-hex = "1.11.3"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "fmt"] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "fmt", "json"] }
test-log = { version = "0.2.15", features = ["trace"] }
libp2p = { version = "0.53.2", features = [
"tokio",
Expand All @@ -18,6 +18,8 @@ libp2p = { version = "0.53.2", features = [
"yamux",
"kad",
"gossipsub",
"identify",
"dns",
] }
tokio = { version = "1.36.0", features = ["full"] }
eyre = "0.6.12"
Expand Down
12 changes: 8 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,14 @@ async fn list_all(
) -> Result<Json<Vec<PremintTypes>>, (StatusCode, String)> {
match storage::list_all(&state.db).await {
Ok(premints) => Ok(Json(premints)),
Err(_e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to list all premints".to_string(),
)),
Err(_e) => {
tracing::warn!("Failed to list all premints: {:?}", _e);

Err((
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to list all premints".to_string(),
))
}
}
}

Expand Down
18 changes: 15 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use crate::chain_list::CHAINS;
use crate::types::PremintName;
use envconfig::Envconfig;
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::str::FromStr;

use envconfig::Envconfig;

use crate::chain_list::CHAINS;
use crate::types::PremintName;

#[derive(Envconfig, Debug)]
pub struct Config {
#[envconfig(from = "SEED")]
Expand Down Expand Up @@ -49,6 +51,12 @@ pub struct Config {
// node_id will only be used for logging purposes, if set
#[envconfig(from = "NODE_ID")]
pub node_id: Option<u64>,

#[envconfig(from = "EXTERNAL_ADDRESS")]
pub external_address: Option<String>,

#[envconfig(from = "INTERACTIVE", default = "false")]
pub interactive: bool,
}

#[derive(Debug, Clone, Copy, PartialEq)]
Expand Down Expand Up @@ -152,6 +160,8 @@ mod test {
supported_chain_ids: "7777777".to_string(),
trusted_peers: None,
node_id: None,
external_address: None,
interactive: false,
};

let names = config.premint_names();
Expand All @@ -173,6 +183,8 @@ mod test {
supported_chain_ids: "7777777".to_string(),
trusted_peers: None,
node_id: None,
external_address: None,
interactive: false,
};

let names = config.premint_names();
Expand Down
34 changes: 27 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,46 @@
use clap::Parser;
use tokio::signal::unix::{signal, SignalKind};
use tracing_subscriber::EnvFilter;

use mintpool::api;
use mintpool::run::start_services;
use mintpool::stdin::watch_stdin;
use tracing_subscriber::EnvFilter;

#[tokio::main]
async fn main() -> eyre::Result<()> {
let _ = tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.pretty()
.try_init();

let config = mintpool::config::init();

if config.interactive {}
let subscriber = tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env());

match config.interactive {
true => subscriber.pretty().try_init(),
false => subscriber.json().try_init(),
}
.expect("Unable to initialize logger");

tracing::info!("Starting mintpool with config: {:?}", config);

let ctl = start_services(&config).await?;

let router = api::make_router(&config, ctl.clone()).await;
api::start_api(&config, router).await?;

watch_stdin(ctl).await;
if config.interactive {
watch_stdin(ctl).await;
} else {
let mut sigint = signal(SignalKind::interrupt())?;
let mut sigterm = signal(SignalKind::terminate())?;

tokio::select! {
_ = sigint.recv() => {
tracing::info!("Received SIGINT, shutting down");
}
_ = sigterm.recv() => {
tracing::info!("Received SIGTERM, shutting down");
}
}
}

Ok(())
}
Expand Down
30 changes: 28 additions & 2 deletions src/p2p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ use crate::types::{MintpoolNodeInfo, Premint, PremintName, PremintTypes};
use eyre::WrapErr;
use libp2p::core::ConnectedPoint;
use libp2p::futures::StreamExt;
use libp2p::gossipsub::Version;
use libp2p::identity::Keypair;
use libp2p::kad::store::MemoryStore;
use libp2p::kad::Addresses;
use libp2p::multiaddr::Protocol;
use libp2p::multiaddr::{Error, Protocol};
use libp2p::swarm::{ConnectionId, NetworkBehaviour, NetworkInfo, SwarmEvent};
use libp2p::{gossipsub, kad, noise, tcp, yamux, Multiaddr, PeerId};
use std::hash::{DefaultHasher, Hash, Hasher};
Expand All @@ -18,6 +19,7 @@ use tokio::select;
pub struct MintpoolBehaviour {
gossipsub: gossipsub::Behaviour,
kad: kad::Behaviour<MemoryStore>,
identify: libp2p::identify::Behaviour,
}

pub struct SwarmController {
Expand All @@ -36,7 +38,24 @@ impl SwarmController {
command_receiver: tokio::sync::mpsc::Receiver<SwarmCommand>,
event_sender: tokio::sync::mpsc::Sender<P2PEvent>,
) -> Self {
let swarm = Self::make_swarm_controller(id_keys).expect("Invalid config for swarm");
let mut swarm = Self::make_swarm_controller(id_keys).expect("Invalid config for swarm");

// add external address if configured
config
.external_address
.clone()
.map(|addr| addr.parse::<Multiaddr>())
.and_then(|addr| match addr {
Ok(addr) => {
swarm.add_external_address(addr.clone());
tracing::info!("Added external address: {:?}", addr);
Some(addr)
}
Err(err) => {
tracing::warn!("Error parsing external address: {:?}", err);
None
}
});

Self {
swarm,
Expand All @@ -56,13 +75,15 @@ impl SwarmController {

fn make_swarm_controller(id_keys: Keypair) -> eyre::Result<libp2p::Swarm<MintpoolBehaviour>> {
let peer_id = id_keys.public().to_peer_id();
let public_key = id_keys.public();
let swarm = libp2p::SwarmBuilder::with_existing_identity(id_keys)
.with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
yamux::Config::default,
)?
.with_dns()?
.with_behaviour(|key| {
let message_id_fn = |message: &gossipsub::Message| {
let mut s = DefaultHasher::new();
Expand All @@ -76,6 +97,7 @@ impl SwarmController {
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(10))
.validation_mode(gossipsub::ValidationMode::Strict)
.protocol_id("/mintpool/0.1.0", Version::V1_1)
.message_id_fn(message_id_fn)
.build()
.expect("valid config");
Expand All @@ -89,6 +111,10 @@ impl SwarmController {
MintpoolBehaviour {
gossipsub: gs,
kad: b,
identify: libp2p::identify::Behaviour::new(libp2p::identify::Config::new(
"mintpool/0.1.0".to_string(),
public_key,
)),
}
})?
.with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
Expand Down
14 changes: 13 additions & 1 deletion src/stdin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,19 @@ async fn process_stdin_line(ctl: ControllerInterface, line: String) {
if line.is_empty() {
return;
}
if line.starts_with("/ip4") {
if line.starts_with("/connect ") {
if let Err(err) = ctl
.send_command(ControllerCommands::ConnectToPeer {
address: (&line[9..]).parse().unwrap(),
})
.await
{
tracing::error!(
error = err.to_string(),
"Error sending connect to peer command"
);
};
} else if line.starts_with("/ip4") {
if let Err(err) = ctl
.send_command(ControllerCommands::ConnectToPeer { address: line })
.await
Expand Down
4 changes: 4 additions & 0 deletions src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ mod test {
trusted_peers: None,
api_port: 0,
node_id: None,
interactive: false,
external_address: None,
};

let store = PremintStorage::new(&config).await;
Expand All @@ -169,6 +171,8 @@ mod test {
supported_chain_ids: "7777777,".to_string(),
trusted_peers: None,
node_id: None,
interactive: false,
external_address: None,
};

let store = PremintStorage::new(&config).await;
Expand Down
2 changes: 2 additions & 0 deletions tests/p2p_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ mod build {
supported_chain_ids: "7777777".to_string(),
trusted_peers: None,
node_id: Some(i),
external_address: None,
interactive: false,
};

let ctl = mintpool::run::start_services(&config).await.unwrap();
Expand Down
Loading