Skip to content

Commit

Permalink
address review comments & make general api's for testing.
Browse files Browse the repository at this point in the history
  • Loading branch information
KnowWhoami committed Dec 20, 2024
1 parent e0d32ca commit f5e8a19
Show file tree
Hide file tree
Showing 26 changed files with 550 additions and 664 deletions.
10 changes: 7 additions & 3 deletions src/bin/directory-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ use coinswap::{
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct App {
/// Sets the rpc-port of DNS
#[clap(long, short = 'p', default_value = "127.0.0.1:4321")]
rpc_port: String,
/// The command to execute
#[clap(subcommand)]
command: Commands,
Expand All @@ -26,8 +29,7 @@ enum Commands {
ListAddresses,
}

fn send_rpc_req(req: &RpcMsgReq) -> Result<(), DirectoryServerError> {
let mut stream = TcpStream::connect("127.0.0.1:4321")?;
fn send_rpc_req(mut stream: TcpStream, req: RpcMsgReq) -> Result<(), DirectoryServerError> {
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
stream.set_write_timeout(Some(Duration::from_secs(20)))?;

Expand All @@ -44,9 +46,11 @@ fn main() -> Result<(), DirectoryServerError> {
setup_directory_logger(log::LevelFilter::Info);
let cli = App::parse();

let stream = TcpStream::connect(cli.rpc_port)?;

match cli.command {
Commands::ListAddresses => {
send_rpc_req(&RpcMsgReq::ListAddresses)?;
send_rpc_req(stream, RpcMsgReq::ListAddresses)?;

Check warning on line 53 in src/bin/directory-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/directory-cli.rs#L53

Added line #L53 was not covered by tests
}
}
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion src/bin/directoryd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ struct Cli {
/// Optional network type.
#[clap(long, short = 'n', default_value = "tor", possible_values = &["tor", "clearnet"])]
network: String,
/// Optional DNS data directory. Default value : "~/.coinswap/directory"
/// Optional DNS data directory. Default value : "~/.coinswap/dns"
#[clap(long, short = 'd')]
data_directory: Option<PathBuf>,
}
Expand Down
51 changes: 28 additions & 23 deletions src/bin/maker-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ use coinswap::{
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct App {
/// Sets the rpc-port of Makerd
#[clap(long, short = 'p', default_value = "127.0.0.1:6103")]
rpc_port: String,
/// The command to execute
#[clap(subcommand)]
command: Commands,
Expand Down Expand Up @@ -37,7 +40,7 @@ enum Commands {
FidelityBalance,
/// Gets a new address
NewAddress,
// Send to an external address and returns the transaction hex.
/// Send to an external address and returns the transaction hex.
SendToAddress {
address: String,
amount: u64,
Expand All @@ -55,66 +58,68 @@ fn main() -> Result<(), MakerError> {
setup_maker_logger(log::LevelFilter::Info);
let cli = App::parse();

let stream = TcpStream::connect(cli.rpc_port)?;

match cli.command {
Commands::Ping => {
send_rpc_req(&RpcMsgReq::Ping)?;
send_rpc_req(stream, RpcMsgReq::Ping)?;
}
Commands::ContractUtxo => {
send_rpc_req(&RpcMsgReq::ContractUtxo)?;
send_rpc_req(stream, RpcMsgReq::ContractUtxo)?;
}
Commands::ContractBalance => {
send_rpc_req(&RpcMsgReq::ContractBalance)?;
send_rpc_req(stream, RpcMsgReq::ContractBalance)?;
}
Commands::FidelityBalance => {
send_rpc_req(&RpcMsgReq::FidelityBalance)?;
send_rpc_req(stream, RpcMsgReq::FidelityBalance)?;
}
Commands::FidelityUtxo => {
send_rpc_req(&RpcMsgReq::FidelityUtxo)?;
send_rpc_req(stream, RpcMsgReq::FidelityUtxo)?;
}
Commands::SeedBalance => {
send_rpc_req(&RpcMsgReq::SeedBalance)?;
send_rpc_req(stream, RpcMsgReq::SeedBalance)?;
}
Commands::SeedUtxo => {
send_rpc_req(&RpcMsgReq::SeedUtxo)?;
send_rpc_req(stream, RpcMsgReq::SeedUtxo)?;
}
Commands::SwapBalance => {
send_rpc_req(&RpcMsgReq::SwapBalance)?;
send_rpc_req(stream, RpcMsgReq::SwapBalance)?;
}
Commands::SwapUtxo => {
send_rpc_req(&RpcMsgReq::SwapUtxo)?;
send_rpc_req(stream, RpcMsgReq::SwapUtxo)?;
}
Commands::NewAddress => {
send_rpc_req(&RpcMsgReq::NewAddress)?;
send_rpc_req(stream, RpcMsgReq::NewAddress)?;
}
Commands::SendToAddress {
address,
amount,
fee,
} => {
send_rpc_req(&RpcMsgReq::SendToAddress {
address,
amount,
fee,
})?;
send_rpc_req(
stream,
RpcMsgReq::SendToAddress {
address,
amount,
fee,
},
)?;
}
// TODO: Test Coverage
Commands::GetTorAddress => {
send_rpc_req(&RpcMsgReq::GetTorAddress)?;
send_rpc_req(stream, RpcMsgReq::GetTorAddress)?;
}
// TODO: Test Coverage
Commands::GetDataDir => {
send_rpc_req(&RpcMsgReq::GetDataDir)?;
send_rpc_req(stream, RpcMsgReq::GetDataDir)?;
}
Commands::Stop => {
send_rpc_req(&RpcMsgReq::Stop)?;
send_rpc_req(stream, RpcMsgReq::Stop)?;
}
}

Ok(())
}

fn send_rpc_req(req: &RpcMsgReq) -> Result<(), MakerError> {
let mut stream = TcpStream::connect("127.0.0.1:6103")?;
fn send_rpc_req(mut stream: TcpStream, req: RpcMsgReq) -> Result<(), MakerError> {
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
stream.set_write_timeout(Some(Duration::from_secs(20)))?;

Expand Down
2 changes: 1 addition & 1 deletion src/maker/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ pub struct Maker {
/// Path for the data directory.
pub data_dir: PathBuf,
/// Thread pool for managing all spawned threads
pub thread_pool: Arc<ThreadPool>
pub thread_pool: Arc<ThreadPool>,
}

#[allow(clippy::too_many_arguments)]
Expand Down
10 changes: 5 additions & 5 deletions src/maker/rpc/messages.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::{fmt::Display, path::PathBuf};
use std::fmt::Display;

use bitcoind::bitcoincore_rpc::json::ListUnspentResultEntry;
use serde::{Deserialize, Serialize};

use std::path::PathBuf;
#[derive(Serialize, Deserialize, Debug)]
pub enum RpcMsgReq {
Ping,
Expand Down Expand Up @@ -56,9 +56,9 @@ impl Display for RpcMsgResp {
Self::SwapUtxoResp { utxos } => write!(f, "{:?}", utxos),
Self::FidelityUtxoResp { utxos } => write!(f, "{:?}", utxos),
Self::ContractUtxoResp { utxos } => write!(f, "{:?}", utxos),
Self::SendToAddressResp(tx_hex) => write!(f, "{:?}", tx_hex),
Self::GetTorAddressResp(addr) => write!(f, "{:?}", addr),
Self::GetDataDirResp(path) => write!(f, "{:?}", path),
Self::SendToAddressResp(tx_hex) => write!(f, "{}", tx_hex),
Self::GetTorAddressResp(addr) => write!(f, "{}", addr),
Self::GetDataDirResp(path) => write!(f, "{}", path.display()),
Self::Shutdown => write!(f, "Shutdown Initiated"),
}
}
Expand Down
8 changes: 3 additions & 5 deletions src/maker/rpc/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::{
fs::File,
io::{ErrorKind, Read},
net::{TcpListener, TcpStream},
path::PathBuf,
sync::{atomic::Ordering::Relaxed, Arc},
thread::sleep,
time::Duration,
Expand Down Expand Up @@ -154,18 +153,17 @@ fn handle_request(maker: &Arc<Maker>, socket: &mut TcpStream) -> Result<(), Make
}
RpcMsgReq::GetTorAddress => {
if maker.config.connection_type == ConnectionType::CLEARNET {
let resp = RpcMsgResp::GetTorAddressResp("Maker Tor is not running".to_string());
let resp = RpcMsgResp::GetTorAddressResp("Maker is not running on TOR".to_string());
if let Err(e) = send_message(socket, &resp) {
log::info!("Error sending RPC response {:?}", e);

Check warning on line 158 in src/maker/rpc/server.rs

View check run for this annotation

Codecov / codecov/patch

src/maker/rpc/server.rs#L158

Added line #L158 was not covered by tests
};
} else {
let maker_hs_path_str =
format!("/tmp/tor-rust-maker{}/hs-dir/hostname", maker.config.port);
let maker_hs_path = PathBuf::from(maker_hs_path_str);
let mut maker_file = File::open(maker_hs_path)?;
let mut maker_file = 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();
maker_onion_addr.pop(); // Remove `\n` at the end.
let maker_address = format!("{}:{}", maker_onion_addr, maker.config.port);

Check warning on line 167 in src/maker/rpc/server.rs

View check run for this annotation

Codecov / codecov/patch

src/maker/rpc/server.rs#L161-L167

Added lines #L161 - L167 were not covered by tests

let resp = RpcMsgResp::GetTorAddressResp(maker_address);
Expand Down
43 changes: 18 additions & 25 deletions src/maker/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,6 @@ fn network_bootstrap(
} else {
maker.config.directory_server_address.clone()
};
log::info!("[{}] Maker server address : {}", maker_port, maker_address);

log::info!(
"[{}] Directory server address : {}",
maker_port,
dns_address
);

(maker_address, dns_address)
}
Expand All @@ -89,8 +82,8 @@ fn network_bootstrap(

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

if Path::new(tor_log_dir.as_str()).exists() {
match fs::remove_file(Path::new(tor_log_dir.as_str())) {
if Path::new(&tor_log_dir).exists() {
match fs::remove_file(&tor_log_dir) {

Check warning on line 86 in src/maker/server.rs

View check run for this annotation

Codecov / codecov/patch

src/maker/server.rs#L86

Added line #L86 was not covered by tests
Ok(_) => log::info!(
"[{}] Previous Maker log file deleted successfully",
maker_port
Expand All @@ -114,39 +107,39 @@ fn network_bootstrap(

let maker_hs_path_str =
format!("/tmp/tor-rust-maker{}/hs-dir/hostname", maker.config.port);
let maker_hs_path = PathBuf::from(maker_hs_path_str);
let mut maker_file = fs::File::open(maker_hs_path)?;
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();

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

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".to_string();
let directory_hs_path = PathBuf::from(directory_hs_path_str);
let mut directory_file = fs::File::open(directory_hs_path)?;
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();
directory_onion_addr.pop(); // Remove `\n` at the end.
format!("{}:{}", directory_onion_addr, 8080)
} else {
maker.config.directory_server_address.clone()
};

log::info!("[{}] Maker server address : {}", maker_port, maker_address);

log::info!(
"[{}] Directory server address : {}",
maker_port,
directory_onion_address
);

(maker_address, directory_onion_address)
}
}
};

log::info!("[{}] Maker server address : {}", maker_port, maker_address);

log::info!(
"[{}] Directory server address : {}",
maker_port,
dns_address
);

// Keep trying until send is successful.
loop {
let mut stream = match maker.config.connection_type {
Expand Down
6 changes: 3 additions & 3 deletions src/market/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,9 @@ pub fn start_directory_server(directory: Arc<DirectoryServer>) -> Result<(), Dir
ConnectionType::CLEARNET => {}
ConnectionType::TOR => {
if cfg!(feature = "tor") {
let tor_log_dir = "/tmp/tor-rust-directory/log".to_string();
if Path::new(tor_log_dir.as_str()).exists() {
match std::fs::remove_file(Path::new(tor_log_dir.clone().as_str())) {
let tor_log_dir = "/tmp/tor-rust-directory/log";
if Path::new(tor_log_dir).exists() {
match fs::remove_file(tor_log_dir) {

Check warning on line 230 in src/market/directory.rs

View check run for this annotation

Codecov / codecov/patch

src/market/directory.rs#L230

Added line #L230 was not covered by tests
Ok(_) => log::info!("Previous directory log file deleted successfully"),
Err(_) => log::error!("Error deleting directory log file"),
}
Expand Down
26 changes: 17 additions & 9 deletions src/utill.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
//! Various utility and helper functions for both Taker and Maker.
use std::{
env,
io::{ErrorKind, Read},
net::TcpStream,
path::{Path, PathBuf},
str::FromStr,
sync::Once,
};

use bitcoin::{
hashes::{sha256, Hash},
key::{rand::thread_rng, Keypair},
Expand All @@ -21,6 +12,14 @@ use log4rs::{
config::{Appender, Logger, Root},
Config,
};
use std::{
env, fmt,
io::{ErrorKind, Read},
net::TcpStream,
path::{Path, PathBuf},
str::FromStr,
sync::Once,
};

use std::{
collections::HashMap,
Expand Down Expand Up @@ -73,6 +72,15 @@ impl FromStr for ConnectionType {
}
}

impl fmt::Display for ConnectionType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConnectionType::TOR => write!(f, "tor"),

Check warning on line 78 in src/utill.rs

View check run for this annotation

Codecov / codecov/patch

src/utill.rs#L78

Added line #L78 was not covered by tests
ConnectionType::CLEARNET => write!(f, "clearnet"),
}
}
}

/// Read the tor address given an hidden_service directory path
pub fn get_tor_addrs(hs_dir: &Path) -> io::Result<String> {
let hostname_file_path = hs_dir.join("hs-dir").join("hostname");
Expand Down
2 changes: 1 addition & 1 deletion src/wallet/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,7 @@ impl Wallet {
)?[0]
.clone();
self.update_external_index(self.store.external_index + 1)?;
Ok(receive_address.assume_checked())
Ok(receive_address.assume_checked()) // TODO: should we check the network or just assume_checked?
}

/// Gets the next internal addresses from the HD keychain.
Expand Down
Loading

0 comments on commit f5e8a19

Please sign in to comment.