Skip to content

Commit

Permalink
stash
Browse files Browse the repository at this point in the history
  • Loading branch information
mojoX911 committed Jan 3, 2025
1 parent ee050ee commit 17de310
Show file tree
Hide file tree
Showing 31 changed files with 1,114 additions and 909 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "coinswap"
version = "0.1.0"
authors = ["developers at citadel-tech"]
authors = ["Developers at Citadel-Tech"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ CoinSwap is a rust implementation of a variant of atomic-swap protocol, using HT
* [Detailed design](https://gist.github.com/chris-belcher/9144bd57a91c194e332fb5ca371d0964)
* [Developer's resources](/docs/dev-book.md)

## Dependencies

Ensure you have the following dependency installed before compiling the project.

```shell
sudo apt install build-essential automake libtool
```

## Build and Test

The repo contains a fully automated integration testing framework on Bitcoin Regtest. The bitcoin binary used for testing is
Expand Down
2 changes: 2 additions & 0 deletions notes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Install c-compiler essentials.
sudo apt install build-essential automake libtool
37 changes: 14 additions & 23 deletions src/bin/directoryd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ use coinswap::{
wallet::RPCConfig,
};

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

#[derive(Parser)]
#[clap(version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
Expand All @@ -33,40 +31,33 @@ struct Cli {
value_parser = parse_proxy_auth,
default_value = "user:password",
)]
pub(crate) auth: (String, String),
/// Sets the full node network, this should match with the network of the running node.
#[clap(
name = "rpc_network",
long,
default_value = "regtest", possible_values = &["regtest", "signet", "mainnet"]
)]
pub(crate) rpc_network: String,
pub auth: (String, String),
}

fn main() -> Result<(), DirectoryServerError> {
setup_directory_logger(log::LevelFilter::Info);

let args = Cli::parse();

let rpc_network = bitcoin::Network::from_str(&args.rpc_network).unwrap();

let rpc_config = RPCConfig {
url: args.rpc,
auth: Auth::UserPass(args.auth.0, args.auth.1),
network: rpc_network,
wallet_name: "random".to_string(), // we can put anything here as it will get updated in the init.
};

let conn_type = ConnectionType::TOR;

#[cfg(feature = "tor")]
{
if conn_type == ConnectionType::TOR {
setup_mitosis();
}
}
let connection_type = if cfg!(feature = "integration-test") {
ConnectionType::CLEARNET

Check warning on line 49 in src/bin/directoryd.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/directoryd.rs#L49

Added line #L49 was not covered by tests
} else {
ConnectionType::TOR
};

#[cfg(not(feature = "tor"))]
let connection_type = ConnectionType::CLEARNET;

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

Check warning on line 59 in src/bin/directoryd.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/directoryd.rs#L57-L59

Added lines #L57 - L59 were not covered by tests
)?);

start_directory_server(directory, Some(rpc_config))?;

Expand Down
123 changes: 79 additions & 44 deletions src/bin/maker-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,16 @@ use coinswap::{
utill::{read_message, send_message, setup_maker_logger},
};

/// maker-cli is a command line app to send RPC messages to maker server.
/// A simple command line app to operate the makerd server.
///
/// The app works as a RPC client for makerd, useful to access the server, retrieve information, and manage server operations.
///
/// For more detailed usage information, please refer: [maker demo doc link]
///
/// This is early beta, and there are known and unknown bugs. Please report issues at: https://github.com/citadel-tech/coinswap/issues
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
#[clap(version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]
struct App {
/// Sets the rpc-port of Makerd
#[clap(long, short = 'p', default_value = "127.0.0.1:6103")]
Expand All @@ -20,38 +27,53 @@ struct App {

#[derive(Parser, Debug)]
enum Commands {
/// Sends a Ping
Ping,
/// Returns a list of seed utxos
SeedUtxo,
/// Returns a list of swap coin utxos
SwapUtxo,
/// Returns a list of live contract utxos
ContractUtxo,
/// Returns a list of fidelity utxos
FidelityUtxo,
/// Returns the total seed balance
SeedBalance,
/// Returns the total swap coin balance
SwapBalance,
/// Returns the total live contract balance
ContractBalance,
/// Returns the total fidelity balance
FidelityBalance,
/// Gets a new address
NewAddress,
/// Send to an external address and returns the transaction hex.
/// Sends a ping to makerd. Will return a pong.
SendPing,
/// Lists all utxos in the wallet. Including fidelity bonds.
ListUtxo,
/// Lists utxos received from incoming swaps.
ListUtxoSwap,
/// Lists HTLC contract utxos.
ListUtxoContract,
/// Lists fidelity bond utxos.
ListUtxoFidelity,
/// Get total wallet balance, excluding Fidelity bonds.
GetBalance,
/// Get total balance received via incoming swaps.
GetBalanceSwap,
/// Get total balances of HTLC contract utxos.
GetBalanceContract,
/// Get total amount locked in fidelity bonds.
GetBalanceFidelity,
/// Gets a new bitcoin receiving address
GetNewAddress,
/// Send Bitcoin to an external address and returns the txid.
SendToAddress {
/// Recipient's address.
#[clap(long, short = 't')]
address: String,
/// Amount to send in sats
#[clap(long, short = 'a')]
amount: u64,
/// Total fee to be paid in sats
#[clap(long, short = 'f')]
fee: u64,
},
/// Returns the tor address
GetTorAddress,
/// Returns the data directory path
GetDataDir,
/// Stops the maker server
/// Show the server tor address
ShowTorAddress,
/// Show the data directory path
ShowDataDir,
/// Shutdown the makerd server
Stop,
/// Redeems the fidelity bond if timelock is matured. Returns the txid of the spending transaction.
RedeemFidelity {
#[clap(long, short = 'i', default_value = "0")]
index: u32,
},
/// Show all the fidelity bonds, current and previous, with an (index, {bond_proof, is_spent}) tupple.
ShowFidelity,
/// Sync the maker wallet with current blockchain state.
SyncWallet,
}

fn main() -> Result<(), MakerError> {
Expand All @@ -61,34 +83,34 @@ fn main() -> Result<(), MakerError> {
let stream = TcpStream::connect(cli.rpc_port)?;

match cli.command {
Commands::Ping => {
Commands::SendPing => {
send_rpc_req(stream, RpcMsgReq::Ping)?;
}
Commands::ContractUtxo => {
Commands::ListUtxoContract => {
send_rpc_req(stream, RpcMsgReq::ContractUtxo)?;
}
Commands::ContractBalance => {
Commands::GetBalanceContract => {
send_rpc_req(stream, RpcMsgReq::ContractBalance)?;
}
Commands::FidelityBalance => {
Commands::GetBalanceFidelity => {
send_rpc_req(stream, RpcMsgReq::FidelityBalance)?;
}
Commands::FidelityUtxo => {
Commands::ListUtxoFidelity => {
send_rpc_req(stream, RpcMsgReq::FidelityUtxo)?;
}
Commands::SeedBalance => {
send_rpc_req(stream, RpcMsgReq::SeedBalance)?;
Commands::GetBalance => {
send_rpc_req(stream, RpcMsgReq::Balance)?;

Check warning on line 102 in src/bin/maker-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/maker-cli.rs#L102

Added line #L102 was not covered by tests
}
Commands::SeedUtxo => {
send_rpc_req(stream, RpcMsgReq::SeedUtxo)?;
Commands::ListUtxo => {
send_rpc_req(stream, RpcMsgReq::Utxo)?;

Check warning on line 105 in src/bin/maker-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/maker-cli.rs#L105

Added line #L105 was not covered by tests
}
Commands::SwapBalance => {
Commands::GetBalanceSwap => {
send_rpc_req(stream, RpcMsgReq::SwapBalance)?;
}
Commands::SwapUtxo => {
Commands::ListUtxoSwap => {
send_rpc_req(stream, RpcMsgReq::SwapUtxo)?;
}
Commands::NewAddress => {
Commands::GetNewAddress => {
send_rpc_req(stream, RpcMsgReq::NewAddress)?;
}
Commands::SendToAddress {
Expand All @@ -105,30 +127,43 @@ fn main() -> Result<(), MakerError> {
},
)?;
}
Commands::GetTorAddress => {
Commands::ShowTorAddress => {
send_rpc_req(stream, RpcMsgReq::GetTorAddress)?;
}
Commands::GetDataDir => {
Commands::ShowDataDir => {
send_rpc_req(stream, RpcMsgReq::GetDataDir)?;
}
Commands::Stop => {
send_rpc_req(stream, RpcMsgReq::Stop)?;
}
Commands::RedeemFidelity { index } => {
send_rpc_req(stream, RpcMsgReq::RedeemFidelity(index))?;

Check warning on line 140 in src/bin/maker-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/maker-cli.rs#L139-L140

Added lines #L139 - L140 were not covered by tests
}
Commands::ShowFidelity => {
send_rpc_req(stream, RpcMsgReq::ListFidelity)?;

Check warning on line 143 in src/bin/maker-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/maker-cli.rs#L143

Added line #L143 was not covered by tests
}
Commands::SyncWallet => {
send_rpc_req(stream, RpcMsgReq::SyncWallet)?;

Check warning on line 146 in src/bin/maker-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/maker-cli.rs#L146

Added line #L146 was not covered by tests
}
}

Ok(())
}

fn send_rpc_req(mut stream: TcpStream, req: RpcMsgReq) -> Result<(), MakerError> {
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
// stream.set_read_timeout(Some(Duration::from_secs(20)))?;
stream.set_write_timeout(Some(Duration::from_secs(20)))?;

send_message(&mut stream, &req)?;

let response_bytes = read_message(&mut stream)?;
let response: RpcMsgResp = serde_cbor::from_slice(&response_bytes)?;

println!("{}", response);
if matches!(response, RpcMsgResp::Pong) {
println!("success");

Check warning on line 163 in src/bin/maker-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/maker-cli.rs#L162-L163

Added lines #L162 - L163 were not covered by tests
} else {
println!("{}", response);

Check warning on line 165 in src/bin/maker-cli.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/maker-cli.rs#L165

Added line #L165 was not covered by tests
}

Ok(())
}
57 changes: 25 additions & 32 deletions src/bin/makerd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,42 @@ use coinswap::{
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.
use std::{path::PathBuf, sync::Arc};
/// Coinswap Maker Server
///
/// The server requires a Bitcoin Core RPC connection running in Signet. It requires some starting balance, arounbd 0.05 BTC Fidelity + Swap Liquidity (suggested 0.05 BTC).
/// After succesful creation of Fidelity Bond, the server will start listinening for incoimng swap requests and earn swap fees.
///
/// This app starts the Maker server.
#[derive(Parser)]
/// The server is operated with the maker-cli app, for all basic wallet related operations.
///
/// For more detailed usage information, please refer: [maker demo doc link]
///
/// This is early beta, and there are known and unknown bugs. Please report issues at: https://github.com/citadel-tech/coinswap/issues
#[derive(Parser, Debug)]
#[clap(version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]
struct Cli {
/// Optional DNS data directory. Default value : "~/.coinswap/maker"
#[clap(long, short = 'd')]
data_directory: Option<PathBuf>,
/// Sets the full node address for rpc connection.
/// Bitcoin Core RPC network address.
#[clap(
name = "ADDRESS:PORT",
long,
short = 'r',
default_value = "127.0.0.1:18443"
)]
pub(crate) rpc: String,
/// Sets the rpc basic authentication.
pub rpc: String,
/// Bitcoin Core RPC authentication string (username, password).
#[clap(
name = "USER:PASSWD",
short = 'a',
long,
value_parser = parse_proxy_auth,
default_value = "user:password",
)]
pub(crate) auth: (String, String),
/// Sets the full node network, this should match with the network of the running node.
#[clap(
name = "NETWORK",
long,
short = 'n',
default_value = "regtest", possible_values = &["regtest", "signet", "mainnet"]
)]
pub(crate) rpc_network: String,
/// Sets the maker wallet's name. If the wallet file already exists at data-directory, it will load that wallet.
pub auth: (String, String),
/// Optional wallet name. If the wallet exists, load the wallet, else create a new wallet with given name. Default: maker-wallet
#[clap(name = "WALLET", long, short = 'w')]
pub(crate) wallet_name: Option<String>,
}
Expand All @@ -55,23 +50,21 @@ fn main() -> Result<(), MakerError> {

let args = Cli::parse();

let rpc_network = bitcoin::Network::from_str(&args.rpc_network).unwrap();

let rpc_config = RPCConfig {
url: args.rpc,
auth: Auth::UserPass(args.auth.0, args.auth.1),
network: rpc_network,
wallet_name: "random".to_string(), // we can put anything here as it will get updated in the init.
};

let conn_type = ConnectionType::TOR;

#[cfg(feature = "tor")]
{
if conn_type == ConnectionType::TOR {
setup_mitosis();
}
}
let connection_type = if cfg!(feature = "integration-test") {
ConnectionType::CLEARNET

Check warning on line 61 in src/bin/makerd.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/makerd.rs#L61

Added line #L61 was not covered by tests
} else {
ConnectionType::TOR
};

#[cfg(not(feature = "tor"))]
let connection_type = ConnectionType::CLEARNET;

let maker = Arc::new(Maker::init(
args.data_directory,
Expand All @@ -80,7 +73,7 @@ fn main() -> Result<(), MakerError> {
None,
None,
None,
Some(conn_type),
Some(connection_type),

Check warning on line 76 in src/bin/makerd.rs

View check run for this annotation

Codecov / codecov/patch

src/bin/makerd.rs#L76

Added line #L76 was not covered by tests
MakerBehavior::Normal,
)?);

Expand Down
Loading

0 comments on commit 17de310

Please sign in to comment.