Skip to content

Commit

Permalink
doc fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
KnowWhoami committed Oct 5, 2024
1 parent e18d767 commit 3d39c73
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 40 deletions.
1 change: 0 additions & 1 deletion src/bin/directoryd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use std::{path::PathBuf, sync::Arc};
#[derive(Parser)]
#[clap(version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]

struct Cli {
/// Optional network type.
#[clap(long, short = 'n', default_value = "clearnet", possible_values = &["tor", "clearnet"])]
Expand Down
29 changes: 19 additions & 10 deletions src/bin/taker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ use std::{path::PathBuf, str::FromStr};
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]
struct Cli {
/// Optional Connection Network Type
#[clap(long, default_value = "clearnet",possible_values = &["tor","clearnet"])]
network: String,
#[clap(long, default_value = "clearnet",short= 'c', possible_values = &["tor","clearnet"])]
connection_type: String,
/// Optional DNS data directory. Default value : "~/.coinswap/taker"
#[clap(long, short = 'd')]
data_directory: Option<PathBuf>,
Expand All @@ -35,12 +35,11 @@ struct Cli {
pub auth: (String, String),
/// Sets the full node network, this should match with the network of the running node.
#[clap(
name = "NETWORK",
long,
short = 'n',
short = 'b',
default_value = "regtest", possible_values = &["regtest", "signet", "mainnet"]
)]
pub rpc_network: String,
pub bitcoin_network: String,
/// Sets the taker wallet's name. If the wallet file already exists at data-directory, it will load that wallet.
#[clap(name = "WALLET", long, short = 'w', default_value = "taker")]
pub wallet_name: String,
Expand Down Expand Up @@ -88,7 +87,6 @@ enum Commands {
GetNewAddress,
/// Send to an external wallet address.
SendToAddress {
/// Recipient address
#[clap(name = "address")]
address: String,
/// Amount to be sent (in sats)
Expand All @@ -107,8 +105,8 @@ enum Commands {
fn main() {
let args = Cli::parse();

let rpc_network = read_bitcoin_network_string(&args.rpc_network).unwrap();
let connection_type = read_connection_network_string(&args.network).unwrap();
let rpc_network = read_bitcoin_network_string(&args.bitcoin_network).unwrap();
let connection_type = read_connection_network_string(&args.connection_type).unwrap();
let rpc_config = RPCConfig {
url: args.rpc,
auth: Auth::UserPass(args.auth.0, args.auth.1),
Expand Down Expand Up @@ -136,7 +134,7 @@ fn main() {
// Determines the log level based on the verbosity argument or the command.
//
// If verbosity is provided, it converts the string to a `LevelFilter`.
// If verbosity is `None`, the log level is set according to the command.
// Otherwise, the log level is set based on the command.
let log_level = match args.verbosity {
Some(level) => LevelFilter::from_str(&level).unwrap(),
None => match args.command {
Expand Down Expand Up @@ -205,6 +203,17 @@ fn main() {
amount,
fee,
} => {
// NOTE:
//
// Currently, we take `fee` instead of `fee_rate` because we cannot calculate the fee for a
// transaction that hasn't been created yet when only a `fee_rate` is provided.
//
// As a result, the user must supply the fee as a parameter, and the function will return the
// transaction hex and the calculated `fee_rate`.
// This allows the user to infer what fee is needed for a successful transaction.
//
// This approach will be improved in the future BDK integration.

let fee = Amount::from_sat(fee);

let amount = Amount::from_sat(amount);
Expand All @@ -214,7 +223,6 @@ fn main() {
let destination =
Destination::Address(Address::from_str(&address).unwrap().assume_checked());

// create a signed tx
let tx = taker
.get_wallet_mut()
.spend_from_wallet(
Expand All @@ -225,6 +233,7 @@ fn main() {
)
.unwrap();

// Derive fee rate from given `fee` argument.
let calculated_fee_rate = fee / (tx.weight());

println!(
Expand Down
1 change: 0 additions & 1 deletion src/market/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ impl DirectoryServer {
///
/// Default data-dir for linux: `~/.coinswap/`
/// Default config locations: `~/.coinswap/dns/config.toml`.
pub fn new(
config_path: Option<PathBuf>,
connection_type: Option<ConnectionType>,
Expand Down
8 changes: 4 additions & 4 deletions src/utill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ pub fn seed_phrase_to_unique_id(seed: &str) -> String {
}

/// Setup function that will only run once, even if called multiple times.
/// Takes log level to set the desired logging verbosity for taker binary.
pub fn setup_logger(taker_log_level: LevelFilter) {
/// Takes log level to set the desired logging verbosity
pub fn setup_logger(filter: LevelFilter) {
Once::new().call_once(|| {
env::set_var("RUST_LOG", "coinswap=info");
let taker_log_dir = get_taker_dir().join("debug.log");
Expand All @@ -141,7 +141,7 @@ pub fn setup_logger(taker_log_level: LevelFilter) {
.logger(
Logger::builder()
.appender("taker")
.build("coinswap::taker", taker_log_level),
.build("coinswap::taker", filter),
)
.logger(
Logger::builder()
Expand All @@ -153,7 +153,7 @@ pub fn setup_logger(taker_log_level: LevelFilter) {
.appender("directory")
.build("coinswap::market", log::LevelFilter::Info),
)
.build(Root::builder().appender("stdout").build(taker_log_level))
.build(Root::builder().appender("stdout").build(filter))
.unwrap();
log4rs::init_config(config).unwrap();
});
Expand Down
32 changes: 8 additions & 24 deletions tests/taker_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ use std::{
};

/// The taker-cli command struct
/// Use it to perform all taker-cli operations
struct TakerCli {
data_dir: PathBuf,
/// Bitcoind instance
bitcoind: BitcoinD,
}

Expand Down Expand Up @@ -63,13 +61,12 @@ impl TakerCli {
.generate_to_address(101, &mining_address)
.unwrap();

// derive data directory
let data_dir = temp_dir.join("taker");

TakerCli { data_dir, bitcoind }
}

// Build a cli-command
// Execute a cli-command
fn execute(&self, cmd: &[&str]) -> String {
let mut args = vec![
"--data-directory",
Expand All @@ -81,14 +78,8 @@ impl TakerCli {
];

// RPC authentication (user:password) from the cookie file
//
// get rpc_auth
// Path to the cookie file
let cookie_file_path = Path::new(&self.bitcoind.params.cookie_file);

// Read the contents of the cookie file
let rpc_auth = fs::read_to_string(cookie_file_path).expect("failed to read from file");

args.push("--USER:PASSWORD");
args.push(&rpc_auth);

Expand All @@ -97,12 +88,9 @@ impl TakerCli {
args.push("--ADDRESS:PORT");
args.push(&rpc_address);

// Wallet name
args.push("--WALLET");
args.push("test_wallet");

// Custom arguments for the taker-cli command

// makers count
args.push("3");

Expand All @@ -112,27 +100,28 @@ impl TakerCli {
// fee_rate
args.push("1000");

// Final command to execute
for arg in cmd {
args.push(arg);
}

// Execute the command
let output = Command::new("./target/debug/taker")
.args(args)
.output()
.unwrap();

// Capture the standard output and error from the command execution
let mut value = output.stdout;
let error = output.stderr;

// Panic if there is any error output
if !error.is_empty() {
panic!("Error: {:?}", String::from_utf8(error).unwrap());
}

value.pop(); // Remove `\n` at the end
// Remove the `\n` at the end of the output
value.pop();

// Get the output string from bytes
// Convert the output bytes to a UTF-8 string
let output_string = std::str::from_utf8(&value).unwrap().to_string();

output_string
Expand All @@ -156,18 +145,15 @@ impl TakerCli {

#[test]
fn test_taker_cli() {
// create taker_cli instance
let taker_cli = TakerCli::new();

// Fund the taker with 3 utxos of 1 BTC each.
for _ in 0..3 {
// derive the address
let taker_address = taker_cli.execute(&["get-new-address"]);

let taker_address: Address<NetworkChecked> =
Address::from_str(&taker_address).unwrap().assume_checked();

// fund 1 BTC to derived address
taker_cli
.bitcoind
.client
Expand All @@ -184,7 +170,7 @@ fn test_taker_cli() {
.unwrap();
}

// confirm balance( Generate blocks)
// confirm balance
taker_cli.generate_blocks(10);

// Assert that total_balance & seed_balance must be 3 BTC
Expand All @@ -200,7 +186,7 @@ fn test_taker_cli() {
let no_of_seed_utxos = seed_utxos.matches("ListUnspentResultEntry {").count();
assert_eq!(3, no_of_seed_utxos);

// Send 100,000 satoshis to a new address within the wallet, with a fee of 1,000 satoshis.
// Send 100,000 sats to a new address within the wallet, with a fee of 1,000 sats.

// get new external address
let new_address = taker_cli.execute(&["get-new-address"]);
Expand All @@ -225,7 +211,6 @@ fn test_taker_cli() {
// broadcast signed transaction
taker_cli.bitcoind.client.send_raw_transaction(&tx).unwrap();

// confirm balances
taker_cli.generate_blocks(10);

// Assert the total_amount & seed_amount must be initial (balance -fee)
Expand All @@ -242,7 +227,6 @@ fn test_taker_cli() {
let no_of_seed_utxos = seed_utxos.matches("ListUnspentResultEntry {").count();
assert_eq!(4, no_of_seed_utxos);

// stopping Bitcoind
taker_cli.bitcoind.client.stop().unwrap();

// Wait for some time for successfull shutdown of bitcoind.
Expand Down

0 comments on commit 3d39c73

Please sign in to comment.