Skip to content

Commit

Permalink
Merge pull request #337 from Wukong247/2024-12-22-add-cargo-hack-ci
Browse files Browse the repository at this point in the history
add cargo hack to ci
  • Loading branch information
mojoX911 authored Dec 22, 2024
2 parents 9c1f324 + dc374bf commit 52db3b0
Show file tree
Hide file tree
Showing 16 changed files with 190 additions and 104 deletions.
6 changes: 6 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,9 @@ jobs:

- name: Clippy
run: cargo clippy --all-targets --all-features -- -D warnings

- name: cargo install cargo-hack
uses: taiki-e/install-action@cargo-hack

- name: cargo hack
run: cargo hack --feature-powerset check
12 changes: 8 additions & 4 deletions src/bin/directoryd.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use clap::Parser;
use coinswap::{
market::directory::{start_directory_server, DirectoryServer, DirectoryServerError},
tor::setup_mitosis,
utill::{setup_directory_logger, ConnectionType},
};

#[cfg(feature = "tor")]
use coinswap::tor::setup_mitosis;
use std::{path::PathBuf, str::FromStr, sync::Arc};

#[derive(Parser)]
Expand All @@ -25,10 +27,12 @@ fn main() -> Result<(), DirectoryServerError> {

let conn_type = ConnectionType::from_str(&args.network)?;

if conn_type == ConnectionType::TOR {
setup_mitosis();
#[cfg(feature = "tor")]
{
if conn_type == ConnectionType::TOR {
setup_mitosis();
}
}

let directory = Arc::new(DirectoryServer::new(args.data_directory, Some(conn_type))?);

start_directory_server(directory)?;
Expand Down
11 changes: 8 additions & 3 deletions src/bin/makerd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ use bitcoind::bitcoincore_rpc::Auth;
use clap::Parser;
use coinswap::{
maker::{start_maker_server, Maker, MakerBehavior, MakerError},
tor::setup_mitosis,
utill::{parse_proxy_auth, setup_maker_logger, ConnectionType},
wallet::RPCConfig,
};
use std::{path::PathBuf, str::FromStr, sync::Arc};

#[cfg(feature = "tor")]
use coinswap::tor::setup_mitosis;

/// The Maker Server.
///
/// This app starts the Maker server.
Expand Down Expand Up @@ -67,8 +69,11 @@ fn main() -> Result<(), MakerError> {
wallet_name: "random".to_string(), // we can put anything here as it will get updated in the init.
};

if conn_type == ConnectionType::TOR {
setup_mitosis();
#[cfg(feature = "tor")]
{
if conn_type == ConnectionType::TOR {
setup_mitosis();
}
}

let maker = Arc::new(Maker::init(
Expand Down
11 changes: 10 additions & 1 deletion src/maker/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,16 @@ impl Default for MakerConfig {
directory_server_address: "127.0.0.1:8080".to_string(),
fidelity_value: 5_000_000, // 5 million sats
fidelity_timelock: 26_000, // Approx 6 months of blocks
connection_type: ConnectionType::TOR,
connection_type: {
#[cfg(feature = "tor")]
{
ConnectionType::TOR
}
#[cfg(not(feature = "tor"))]
{
ConnectionType::CLEARNET
}
},
}
}
}
Expand Down
122 changes: 67 additions & 55 deletions src/maker/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
//! The server listens at two port 6102 for P2P, and 6103 for RPC Client request.
use std::{
fs,
io::{ErrorKind, Read, Write},
io::{ErrorKind, Write},
net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, Ordering::Relaxed},
Arc,
Expand All @@ -17,9 +15,19 @@ use std::{
time::Duration,
};

#[cfg(feature = "tor")]
use std::io::Read;

#[cfg(feature = "tor")]
use std::{
fs,
path::{Path, PathBuf},
};

use bitcoin::{absolute::LockTime, Amount};
use bitcoind::bitcoincore_rpc::RpcApi;

#[cfg(feature = "tor")]
use socks::Socks5Stream;

pub use super::Maker;
Expand All @@ -32,10 +40,13 @@ use crate::{
rpc::start_rpc_server,
},
protocol::messages::TakerToMakerMessage,
utill::{monitor_log_for_completion, read_message, send_message, ConnectionType},
utill::{read_message, send_message, ConnectionType},
wallet::WalletError,
};

#[cfg(feature = "tor")]
use crate::utill::monitor_log_for_completion;

use crate::maker::error::MakerError;

// Default values for Maker configurations
Expand All @@ -50,15 +61,19 @@ pub const MIN_CONTRACT_REACTION_TIME: u16 = 48;
/// E.g., for 1 billion sats (0.01 BTC), a value of 10_000 would result in a 0.1% fee.
pub const AMOUNT_RELATIVE_FEE_PPB: Amount = Amount::from_sat(10_000_000);

#[cfg(feature = "tor")]
type OptionalJoinHandle = Option<mitosis::JoinHandle<()>>;

#[cfg(not(feature = "tor"))]
type OptionalJoinHandle = Option<()>;

/// Fetches the Maker and DNS address, and sends maker address to the DNS server.
/// Depending upon ConnectionType and test/prod environment, different maker address and DNS addresses are returned.
/// Return the Maker address and an optional tor thread handle.
///
/// Tor thread is spawned only if ConnectionType=TOR and --feature=tor is enabled.
/// Errors if ConncetionType=TOR but, the tor feature is not enabled.
fn network_bootstrap(
maker: Arc<Maker>,
) -> Result<(String, Option<mitosis::JoinHandle<()>>), MakerError> {
fn network_bootstrap(maker: Arc<Maker>) -> Result<(String, OptionalJoinHandle), MakerError> {
let maker_port = maker.config.port;
let mut tor_handle = None;
let (maker_address, dns_address) = match maker.config.connection_type {
Expand All @@ -72,63 +87,58 @@ fn network_bootstrap(

(maker_address, dns_address)
}
#[cfg(feature = "tor")]
ConnectionType::TOR => {
if !cfg!(feature = "tor") {
return Err(MakerError::General(
"Tor setup failure. Please compile with Tor feature enabled.",
));
} else {
let maker_socks_port = maker.config.socks_port;
let maker_socks_port = maker.config.socks_port;

let tor_log_dir = format!("/tmp/tor-rust-maker{}/log", maker_port);
let tor_log_dir = format!("/tmp/tor-rust-maker{}/log", maker_port);

if Path::new(&tor_log_dir).exists() {
match fs::remove_file(&tor_log_dir) {
Ok(_) => log::info!(
"[{}] Previous Maker log file deleted successfully",
maker_port
),
Err(_) => log::error!("[{}] Error deleting Maker log file", maker_port),
}
if Path::new(&tor_log_dir).exists() {
match fs::remove_file(&tor_log_dir) {
Ok(_) => log::info!(
"[{}] Previous Maker log file deleted successfully",
maker_port
),
Err(_) => log::error!("[{}] Error deleting Maker log file", maker_port),
}
}

tor_handle = Some(crate::tor::spawn_tor(
maker_socks_port,
maker_port,
format!("/tmp/tor-rust-maker{}", maker_port),
));
thread::sleep(Duration::from_secs(10));
tor_handle = Some(crate::tor::spawn_tor(
maker_socks_port,
maker_port,
format!("/tmp/tor-rust-maker{}", maker_port),
));
thread::sleep(Duration::from_secs(10));

if let Err(e) = monitor_log_for_completion(&PathBuf::from(tor_log_dir), "100%") {
log::error!("[{}] Error monitoring log file: {}", maker_port, e);
}
if let Err(e) = monitor_log_for_completion(&PathBuf::from(tor_log_dir), "100%") {
log::error!("[{}] Error monitoring log file: {}", maker_port, e);
}

log::info!("[{}] Maker tor is instantiated", maker_port);
log::info!("[{}] Maker tor is instantiated", maker_port);

let maker_hs_path_str =
format!("/tmp/tor-rust-maker{}/hs-dir/hostname", maker.config.port);
let mut maker_file = fs::File::open(maker_hs_path_str)?;
let mut maker_onion_addr: String = String::new();
maker_file.read_to_string(&mut maker_onion_addr)?;
let maker_hs_path_str =
format!("/tmp/tor-rust-maker{}/hs-dir/hostname", maker.config.port);
let mut maker_file = fs::File::open(maker_hs_path_str)?;
let mut maker_onion_addr: String = String::new();
maker_file.read_to_string(&mut maker_onion_addr)?;

maker_onion_addr.pop(); // Remove `\n` at the end.
maker_onion_addr.pop(); // Remove `\n` at the end.

let maker_address = format!("{}:{}", maker_onion_addr, maker.config.port);
let maker_address = format!("{}:{}", maker_onion_addr, maker.config.port);

let directory_onion_address = if cfg!(feature = "integration-test") {
let directory_hs_path_str = "/tmp/tor-rust-directory/hs-dir/hostname";
let mut directory_file = fs::File::open(directory_hs_path_str)?;
let mut directory_onion_addr: String = String::new();
let directory_onion_address = if cfg!(feature = "integration-test") {
let directory_hs_path_str = "/tmp/tor-rust-directory/hs-dir/hostname";
let mut directory_file = fs::File::open(directory_hs_path_str)?;
let mut directory_onion_addr: String = String::new();

directory_file.read_to_string(&mut directory_onion_addr)?;
directory_onion_addr.pop(); // Remove `\n` at the end.
format!("{}:{}", directory_onion_addr, 8080)
} else {
maker.config.directory_server_address.clone()
};
directory_file.read_to_string(&mut directory_onion_addr)?;
directory_onion_addr.pop(); // Remove `\n` at the end.
format!("{}:{}", directory_onion_addr, 8080)
} else {
maker.config.directory_server_address.clone()
};

(maker_address, directory_onion_address)
}
(maker_address, directory_onion_address)
}
};

Expand All @@ -155,6 +165,7 @@ fn network_bootstrap(
continue;
}
},
#[cfg(feature = "tor")]
ConnectionType::TOR => {
match Socks5Stream::connect(
format!("127.0.0.1:{}", maker.config.socks_port),
Expand Down Expand Up @@ -549,11 +560,12 @@ pub fn start_maker_server(maker: Arc<Maker>) -> Result<(), MakerError> {
}

log::info!("[{}] Maker is shutting down.", port);

if maker.config.connection_type == ConnectionType::TOR && cfg!(feature = "tor") {
crate::tor::kill_tor_handles(tor_thread.expect("Tor thread expected"));
#[cfg(feature = "tor")]
{
if maker.config.connection_type == ConnectionType::TOR && cfg!(feature = "tor") {
crate::tor::kill_tor_handles(tor_thread.expect("Tor thread expected"));
}
}

log::info!("Shutdown wallet sync initiated.");
maker.get_wallet().write()?.sync()?;
log::info!("Shutdown wallet syncing completed.");
Expand Down
33 changes: 24 additions & 9 deletions src/market/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
use crate::{
market::rpc::start_rpc_server_thread,
utill::{
get_dns_dir, get_tor_addrs, monitor_log_for_completion, parse_field, parse_toml,
ConnectionType,
},
utill::{get_dns_dir, parse_field, parse_toml, ConnectionType},
};

#[cfg(feature = "tor")]
use crate::utill::{get_tor_addrs, monitor_log_for_completion};

use std::{
collections::HashSet,
fs::{self, File},
Expand Down Expand Up @@ -77,7 +77,16 @@ impl Default for DirectoryServer {
rpc_port: 4321,
port: 8080,
socks_port: 19060,
connection_type: ConnectionType::TOR,
connection_type: {
#[cfg(feature = "tor")]
{
ConnectionType::TOR
}
#[cfg(not(feature = "tor"))]
{
ConnectionType::CLEARNET
}
},
data_dir: get_dns_dir(),
shutdown: AtomicBool::new(false),
addresses: Arc::new(RwLock::new(HashSet::new())),
Expand Down Expand Up @@ -219,12 +228,15 @@ pub fn write_addresses_to_file(
Ok(())
}
pub fn start_directory_server(directory: Arc<DirectoryServer>) -> Result<(), DirectoryServerError> {
#[cfg(feature = "tor")]
let mut tor_handle = None;

match directory.connection_type {
ConnectionType::CLEARNET => {}
#[cfg(feature = "tor")]
ConnectionType::TOR => {
if cfg!(feature = "tor") {
#[cfg(feature = "tor")]
{
let tor_log_dir = "/tmp/tor-rust-directory/log";
if Path::new(tor_log_dir).exists() {
match fs::remove_file(tor_log_dir) {
Expand Down Expand Up @@ -304,9 +316,12 @@ pub fn start_directory_server(directory: Arc<DirectoryServer>) -> Result<(), Dir
log::error!("Error closing Address Writer Thread : {:?}", e);
}

if let Some(handle) = tor_handle {
crate::tor::kill_tor_handles(handle);
log::info!("Directory server and Tor instance terminated successfully");
#[cfg(feature = "tor")]
{
if let Some(handle) = tor_handle {
crate::tor::kill_tor_handles(handle);
log::info!("Directory server and Tor instance terminated successfully");
}
}

write_addresses_to_file(&directory, &address_file)?;
Expand Down
Loading

0 comments on commit 52db3b0

Please sign in to comment.