Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
8 changes: 4 additions & 4 deletions src/bin/makerd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ struct Cli {
)]
pub rpc_network: String,
/// Sets the maker 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 = "maker")]
pub wallet_name: String,
#[clap(name = "WALLET", long, short = 'w')]
pub wallet_name: Option<String>,
}

fn main() -> Result<(), MakerError> {
Expand All @@ -63,12 +63,12 @@ fn main() -> Result<(), MakerError> {
url: args.rpc,
auth: Auth::UserPass(args.auth.0, args.auth.1),
network: rpc_network,
wallet_name: args.wallet_name.clone(),
wallet_name: "random".to_string(), // we can put anything here as it will get updated in the init.
};

let maker = Arc::new(Maker::init(
args.data_directory,
Some(args.wallet_name),
args.wallet_name,
Some(rpc_config),
None,
None,
Expand Down
8 changes: 4 additions & 4 deletions src/bin/taker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ struct Cli {
)]
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,
#[clap(name = "WALLET", long, short = 'w')]
pub wallet_name: Option<String>,
/// Sets the verbosity level of logs.
/// Default: Determined by the command passed.
#[clap(long, short = 'v', possible_values = &["off", "error", "warn", "info", "debug", "trace"])]
Expand Down Expand Up @@ -109,7 +109,7 @@ fn main() -> Result<(), TakerError> {
url: args.rpc,
auth: Auth::UserPass(args.auth.0, args.auth.1),
network: rpc_network,
wallet_name: args.wallet_name.clone(),
wallet_name: "random".to_string(), // we can put anything here as it will get updated in the init.
};

let swap_params = SwapParams {
Expand All @@ -122,7 +122,7 @@ fn main() -> Result<(), TakerError> {

let mut taker = Taker::init(
args.data_directory.clone(),
Some(args.wallet_name.clone()),
args.wallet_name.clone(),
Some(rpc_config.clone()),
TakerBehavior::Normal,
Some(connection_type),
Expand Down
28 changes: 15 additions & 13 deletions src/maker/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,24 +211,22 @@ fn setup_fidelity_bond(maker: &Arc<Maker>, maker_address: &str) -> Result<(), Ma
.get_block_count()
.map_err(WalletError::Rpc)? as u32;

// Set 100 blocks locktime for test
// Set 150 blocks locktime for test
let locktime = if cfg!(feature = "integration-test") {
LockTime::from_height(current_height + 100).map_err(WalletError::Locktime)?
LockTime::from_height(current_height + 150).map_err(WalletError::Locktime)?
} else {
LockTime::from_height(maker.config.fidelity_timelock + current_height)
.map_err(WalletError::Locktime)?
};

let sleep_delay = if cfg!(feature = "integration-test") {
3 // Wait for 3 sec in tests
} else {
300 // Wait for 5 mins in production
};
let sleep_increment = 10;
let mut sleep_multiplier = 0;

log::info!("Fidelity value chosen = {:?} BTC", amount.to_btc());
log::info!("Fidelity Tx fee = 1000 sats");

while !maker.shutdown.load(Relaxed) {
sleep_multiplier += 1;
// sync the wallet
maker.get_wallet().write()?.sync()?;

Expand All @@ -250,10 +248,11 @@ fn setup_fidelity_bond(maker: &Arc<Maker>, maker_address: &str) -> Result<(), Ma
let amount = required - available;
let addr = maker.get_wallet().write()?.get_next_external_address()?;

log::info!("Send > {:?} BTC to {:?}. Extra will be used for swaps after fidelity creation.", amount, addr);
log::info!("Next sync in {:?} secs", sleep_delay);
log::info!("Send at least {:.8} BTC to {:?} | If you send extra, that will be added to your swap balance", amount, addr);

thread::sleep(Duration::from_secs(sleep_delay));
let total_sleep = sleep_increment * sleep_multiplier.min(10 * 60);
log::info!("Next sync in {:?} secs", total_sleep);
thread::sleep(Duration::from_secs(total_sleep));
} else {
log::error!(
"[{}] Fidelity Bond Creation failed: {:?}. Shutting Down Maker server",
Expand Down Expand Up @@ -406,6 +405,8 @@ pub fn start_maker_server(maker: Arc<Maker>) -> Result<(), MakerError> {
maker_address
);

let heart_beat_interval = maker.config.heart_beat_interval_secs; // All maker internal threads loops at this frequency.

// Setup the wallet with fidelity bond.
let network = maker.get_wallet().read()?.store.network;
let balance = maker.get_wallet().read()?.balance()?;
Expand Down Expand Up @@ -475,6 +476,8 @@ pub fn start_maker_server(maker: Arc<Maker>) -> Result<(), MakerError> {
})?;

thread_pool.push(rpc_thread);

sleep(Duration::from_secs(heart_beat_interval)); // wait for 1 beat, to complete spawns of all the threads.
maker.setup_complete()?;
log::info!("[{}] Maker setup is ready", maker.config.port);
}
Expand All @@ -484,12 +487,11 @@ pub fn start_maker_server(maker: Arc<Maker>) -> Result<(), MakerError> {
// This loop beats at `maker.config.heart_beat_interval_secs`
while !maker.shutdown.load(Relaxed) {
let maker = maker.clone(); // This clone is needed to avoid moving the Arc<Maker> in each iterations.
let heart_beat_interval = maker.config.heart_beat_interval_secs;

// Block client connections if accepting_client=false
if !*accepting_clients.lock()? {
log::warn!(
"[{}] Bitcoin Core RPC Connection broken. Not accepting clients temporarily",
log::debug!(
"[{}] Temporary failure in backend node. Not accepting swap request. Check your node if this error persists",
maker.config.port
);
sleep(Duration::from_secs(heart_beat_interval));
Expand Down
79 changes: 40 additions & 39 deletions src/wallet/fidelity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub enum FidelityError {
WrongScriptType,
BondDoesNotExist,
BondAlreadySpent,
BondLocktimeExpired,
CertExpired,
General(String),
}
Expand Down Expand Up @@ -263,7 +264,14 @@ impl Wallet {
(info.height, info.time as u64)
};
// Estimated locktime from block height = [current-time + (maturity-height - block-count) * 10 * 60] sec
tip_time + ((blocks.to_consensus_u32() as u64 - tip_height as u64) * 10 * 60)
let height_diff =
if let Some(x) = blocks.to_consensus_u32().checked_sub(tip_height as u32) {
x as u64
} else {
return Err(FidelityError::BondLocktimeExpired.into());
};

tip_time + (height_diff * 10 * 60)
}
LockTime::Seconds(sec) => sec.to_consensus_u32() as u64,
};
Expand Down Expand Up @@ -371,29 +379,25 @@ impl Wallet {

let txid = self.rpc.send_raw_transaction(&tx)?;

let sleep_delay = if cfg!(feature = "integration-test") {
1 // wait for 1 sec in tests
} else {
60 // wait for 1 min in production
};
let sleep_increment = 10;
let mut sleep_multiplier = 0;

let conf_height = loop {
if let Ok(get_tx_result) = self.rpc.get_transaction(&txid, None) {
if let Some(ht) = get_tx_result.info.blockheight {
log::info!("Fidelity Bond confirmed at blockheight: {}", ht);
break ht;
} else {
log::info!(
"Fildelity Transaction {} seen in mempool, waiting for confirmation.",
txid
);

log::info!("Next sync in {:?} secs", sleep_delay);
sleep_multiplier += 1;

thread::sleep(Duration::from_secs(sleep_delay));
}
let get_tx_result = self.rpc.get_transaction(&txid, None)?;
if let Some(ht) = get_tx_result.info.blockheight {
log::info!("Fidelity Bond confirmed at blockheight: {}", ht);
break ht;
} else {
log::info!("Waiting for {} in mempool", txid);
log::info!(
"Fildelity Transaction {} seen in mempool, waiting for confirmation.",
txid
);

let total_sleep = sleep_increment * sleep_multiplier.min(10 * 60); // Caps at 1 Block interval i.e 10 mins
log::info!("Next sync in {:?} secs", total_sleep);
thread::sleep(Duration::from_secs(total_sleep));
}
};

Expand Down Expand Up @@ -467,28 +471,25 @@ impl Wallet {

let txid = self.rpc.send_raw_transaction(&tx)?;

let conf_height = loop {
if let Ok(get_tx_result) = self.rpc.get_transaction(&txid, None) {
if let Some(ht) = get_tx_result.info.blockheight {
log::info!("Fidelity Bond confirmed at blockheight: {}", ht);
break ht;
} else {
log::info!(
"Fildelity Transaction {} seen in mempool, waiting for confirmation.",
txid
);
let sleep_increment = 10;
let mut sleep_multiplier = 0;

if cfg!(feature = "integration-test") {
thread::sleep(Duration::from_secs(1)); // wait for 1 sec in tests
} else {
thread::sleep(Duration::from_secs(60)); // wait for 1 min in prod
}
let conf_height = loop {
sleep_multiplier += 1;

continue;
}
let get_tx_result = self.rpc.get_transaction(&txid, None)?;
if let Some(ht) = get_tx_result.info.blockheight {
log::info!("Fidelity Bond confirmed at blockheight: {}", ht);
break ht;
} else {
log::info!("Waiting for {} in mempool", txid);
continue;
log::info!(
"Redeem Fildelity Transaction {} seen in mempool, waiting for confirmation.",
txid
);

let total_sleep = sleep_increment * sleep_multiplier.min(10 * 60); // Caps at 1 Block interval i.e 10 mins
log::info!("Next sync in {:?} secs", total_sleep);
thread::sleep(Duration::from_secs(total_sleep));
}
};

Expand Down
8 changes: 4 additions & 4 deletions src/wallet/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ impl Wallet {
// Create or load the watch-only bitcoin core wallet
let wallet_name = &self.store.file_name;
if self.rpc.list_wallets()?.contains(wallet_name) {
log::info!("wallet already loaded: {}", wallet_name);
log::debug!("wallet already loaded: {}", wallet_name);
} else if list_wallet_dir(&self.rpc)?.contains(wallet_name) {
self.rpc.load_wallet(wallet_name)?;
log::info!("wallet loaded: {}", wallet_name);
log::debug!("wallet loaded: {}", wallet_name);
} else {
// pre-0.21 use legacy wallets
if self.rpc.version()? < 210_000 {
Expand All @@ -101,7 +101,7 @@ impl Wallet {
let _: Value = self.rpc.call("createwallet", &args)?;
}

log::info!("wallet created: {}", wallet_name);
log::debug!("wallet created: {}", wallet_name);
}

let descriptors_to_import = self.descriptors_to_import()?;
Expand All @@ -126,7 +126,7 @@ impl Wallet {
.unwrap_or(0)
.max(self.store.wallet_birthday.unwrap_or(0));
let node_synced = self.rpc.get_block_count()?;
log::info!(
log::debug!(
"rescan_blockchain from:{} to:{}",
last_synced_height,
node_synced
Expand Down
7 changes: 4 additions & 3 deletions tests/fidelity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ fn test_fidelity() {

let maker_thread = thread::spawn(move || start_maker_server(maker_clone));

thread::sleep(Duration::from_secs(12));
thread::sleep(Duration::from_secs(6));

// TODO: Assert that fund request for fidelity is printed in the log.

Expand All @@ -78,7 +78,7 @@ fn test_fidelity() {
let bond_value = wallet_read
.calculate_bond_value(highest_bond_index)
.unwrap();
assert_eq!(bond_value, Amount::from_sat(185));
assert_eq!(bond_value, Amount::from_sat(542));

let (bond, _, is_spent) = wallet_read
.get_fidelity_bonds()
Expand All @@ -93,6 +93,7 @@ fn test_fidelity() {

// Create another fidelity bond of 0.08 BTC and validate it.
let second_maturity_height = {
log::info!("Creating another fidelity bond using the `create_fidelity` API");
let index = maker
.get_wallet()
.write()
Expand All @@ -110,7 +111,7 @@ fn test_fidelity() {
assert_eq!(highest_bond_index, index);

let bond_value = wallet_read.calculate_bond_value(index).unwrap();
assert_eq!(bond_value, Amount::from_sat(1801));
assert_eq!(bond_value, Amount::from_sat(1317));

let (bond, _, is_spent) = wallet_read.get_fidelity_bonds().get(&index).unwrap();
assert_eq!(bond.amount, Amount::from_sat(8000000));
Expand Down