Skip to content

Commit

Permalink
Move integration test to tests/ directory
Browse files Browse the repository at this point in the history
This is the standard way in rust to have integration tests.

It required moving much of the code previous in main.rs into a new file lib.rs

For integration tests the `#[cfg(test)]` annotation has no effect, so the
code has been recoded to allow for passing special parameters that only
integration tests will use.

I noticed that the test wallet files (`tests/taker-wallet` etc) get rewritten
every run, so there's no reason to have these files in the depository. They've
been deleted.
  • Loading branch information
chris-belcher committed Jan 9, 2022
1 parent c938596 commit f48a2f4
Show file tree
Hide file tree
Showing 10 changed files with 740 additions and 681 deletions.
451 changes: 451 additions & 0 deletions src/lib.rs

Large diffs are not rendered by default.

664 changes: 26 additions & 638 deletions src/main.rs

Large diffs are not rendered by default.

21 changes: 10 additions & 11 deletions src/maker_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,13 @@ pub enum MakerBehavior {
CloseOnSignSendersContractTx,
}

#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub struct MakerConfig {
pub port: u16,
pub rpc_ping_interval: u64,
pub watchtower_ping_interval: u64,
pub maker_behavior: MakerBehavior,
pub kill_flag: Arc<RwLock<bool>>,
}

#[tokio::main]
Expand Down Expand Up @@ -99,6 +100,9 @@ async fn run(
let (server_loop_comms_tx, mut server_loop_comms_rx) = mpsc::channel::<Error>(100);
let mut accepting_clients = true;
let mut last_watchtowers_ping = Instant::now();

let my_kill_flag = config.kill_flag.clone();

loop {
let (mut socket, addr) = select! {
new_client = listener.accept() => new_client?,
Expand Down Expand Up @@ -129,6 +133,9 @@ async fn run(
};
log::debug!("Ping: RPC = {}{}", rpc_ping_success, debug_msg);
accepting_clients = rpc_ping_success && watchtowers_ping_success;
if *my_kill_flag.read().unwrap() {
break Err(Error::Protocol("kill flag is true"));
}
continue;
},
};
Expand All @@ -146,6 +153,7 @@ async fn run(
let client_rpc = Arc::clone(&rpc);
let client_wallet = Arc::clone(&wallet);
let server_loop_comms_tx = server_loop_comms_tx.clone();
let maker_behavior = config.maker_behavior;

tokio::spawn(async move {
let (socket_reader, mut socket_writer) = socket.split();
Expand Down Expand Up @@ -184,15 +192,6 @@ async fn run(
break;
}
};
#[cfg(test)]
if line == "kill".to_string() {
server_loop_comms_tx
.send(Error::Protocol("kill signal"))
.await
.unwrap();
log::info!("Kill signal received, stopping maker....");
break;
}

line = line.trim_end().to_string();
let message_result = handle_message(
Expand All @@ -201,7 +200,7 @@ async fn run(
Arc::clone(&client_rpc),
Arc::clone(&client_wallet),
addr,
config.maker_behavior,
maker_behavior,
)
.await;
match message_result {
Expand Down
5 changes: 0 additions & 5 deletions src/taker_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ use crate::messages::{
SignSendersContractTx, SwapCoinPrivateKey, TakerHello, TakerToMakerMessage, PREIMAGE_LEN,
};

#[cfg(test)]
use crate::get_bitcoin_rpc;

use crate::offerbook_sync::{sync_offerbook, OfferAddress};
use crate::wallet_sync::{
generate_keypair, CoreAddressLabelType, IncomingSwapCoin, OutgoingSwapCoin, Wallet,
Expand Down Expand Up @@ -816,8 +813,6 @@ async fn wait_for_funding_tx_confirmation(
}
}
sleep(Duration::from_millis(1000)).await;
#[cfg(test)]
crate::test::generate_1_block(&get_bitcoin_rpc().unwrap());
}
}

Expand Down
32 changes: 20 additions & 12 deletions src/wallet_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,6 @@ pub const NETWORK: Network = Network::Regtest; //not configurable for now
const DERIVATION_PATH: &str = "m/84'/1'/0'";
const WALLET_FILE_VERSION: u32 = 0;

#[cfg(not(test))]
const INITIAL_ADDRESS_IMPORT_COUNT: usize = 5000;
#[cfg(test)]
const INITIAL_ADDRESS_IMPORT_COUNT: usize = 6;

//TODO the wallet file format is probably best handled with sqlite

#[derive(serde::Serialize, serde::Deserialize)]
Expand All @@ -84,10 +79,16 @@ pub struct Wallet {
master_key: ExtendedPrivKey,
wallet_file_name: String,
external_index: u32,
initial_address_import_count: usize,
incoming_swap_coins: HashMap<Script, IncomingSwapCoin>,
outgoing_swap_coins: HashMap<Script, OutgoingSwapCoin>,
}

pub enum WalletSyncAddressAmount {
Normal,
Testing,
}

pub enum CoreAddressLabelType {
Wallet,
WatchOnlySwapCoin,
Expand Down Expand Up @@ -348,7 +349,10 @@ impl Wallet {
.map_err(|e| io::Error::from(e))?)
}

pub fn load_wallet_from_file<P: AsRef<Path>>(wallet_file_name: P) -> Result<Wallet, Error> {
pub fn load_wallet_from_file<P: AsRef<Path>>(
wallet_file_name: P,
sync_amount: WalletSyncAddressAmount,
) -> Result<Wallet, Error> {
let wallet_file_name = wallet_file_name
.as_ref()
.as_os_str()
Expand All @@ -372,6 +376,10 @@ impl Wallet {
master_key: xprv,
wallet_file_name,
external_index: wallet_file_data.external_index,
initial_address_import_count: match sync_amount {
WalletSyncAddressAmount::Normal => 5000,
WalletSyncAddressAmount::Testing => 6,
},
incoming_swap_coins: wallet_file_data
.incoming_swap_coins
.iter()
Expand All @@ -395,7 +403,6 @@ impl Wallet {
Ok(())
}

#[cfg(test)]
pub fn get_external_index(&self) -> u32 {
self.external_index
}
Expand Down Expand Up @@ -448,7 +455,6 @@ impl Wallet {
.insert(coin.get_multisig_redeemscript(), coin);
}

#[cfg(test)]
pub fn get_swap_coins_count(&self) -> usize {
self.incoming_swap_coins.len() + self.outgoing_swap_coins.len()
}
Expand Down Expand Up @@ -503,7 +509,7 @@ impl Wallet {

fn is_xpub_descriptor_imported(&self, rpc: &Client, descriptor: &str) -> Result<bool, Error> {
let first_addr = rpc.derive_addresses(&descriptor, Some([0, 0]))?[0].clone();
let last_index = (INITIAL_ADDRESS_IMPORT_COUNT - 1) as u32;
let last_index = (self.initial_address_import_count - 1) as u32;
let last_addr =
rpc.derive_addresses(&descriptor, Some([last_index, last_index]))?[0].clone();

Expand Down Expand Up @@ -566,14 +572,17 @@ impl Wallet {
hd_descriptors_to_import: &[&String],
swapcoin_descriptors_to_import: &[String],
) -> Result<(), Error> {
log::debug!(target: "wallet",
"import_initial_addresses with initial_address_import_count = {}",
self.initial_address_import_count);
let address_label = self.get_core_wallet_label();

let import_requests = hd_descriptors_to_import
.iter()
.map(|desc| ImportMultiRequest {
timestamp: ImportMultiRescanSince::Now,
descriptor: Some(desc),
range: Some((0, INITIAL_ADDRESS_IMPORT_COUNT - 1)),
range: Some((0, self.initial_address_import_count - 1)),
watchonly: Some(true),
label: Some(&address_label),
..Default::default()
Expand Down Expand Up @@ -607,7 +616,6 @@ impl Wallet {

pub fn startup_sync(&mut self, rpc: &Client) -> Result<(), Error> {
//TODO many of these unwraps to be replaced with proper error handling

let hd_descriptors = self.get_hd_wallet_descriptors(rpc)?;
let hd_descriptors_to_import = hd_descriptors
.iter()
Expand Down Expand Up @@ -659,7 +667,7 @@ impl Wallet {
.map(|d| {
json!(
{"desc": d,
"range": INITIAL_ADDRESS_IMPORT_COUNT-1})
"range": self.initial_address_import_count-1})
})
.chain(swapcoin_descriptors_to_import.iter().map(|d| json!(d)))
.collect::<Vec<Value>>();
Expand Down
19 changes: 7 additions & 12 deletions src/watchtower_protocol.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashSet;
use std::iter::FromIterator;
use std::net::Ipv4Addr;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use tokio::io::BufReader;
Expand Down Expand Up @@ -65,15 +66,15 @@ pub enum WatchtowerToMakerMessage {
//pub async fn

#[tokio::main]
pub async fn start_watchtower(rpc: &Client) {
match run(rpc).await {
pub async fn start_watchtower(rpc: &Client, kill_flag: Arc<RwLock<bool>>) {
match run(rpc, kill_flag).await {
Ok(_o) => log::info!("watchtower ended without error"),
Err(e) => log::info!("watchtower ended with err {:?}", e),
};
}

//TODO i think rpc doesnt need to be wrapped in Arc, because its not used in the spawned task
async fn run(rpc: &Client) -> Result<(), Error> {
async fn run(rpc: &Client, kill_flag: Arc<RwLock<bool>>) -> Result<(), Error> {
//TODO port number in config file
let port = 6103;
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await?;
Expand Down Expand Up @@ -121,6 +122,9 @@ async fn run(rpc: &Client) -> Result<(), Error> {
&mut last_checked_block_height);
accepting_clients = r.is_ok();
log::info!("Timeout Branch, Accepting Clients @ {}", port);
if *kill_flag.read().unwrap() {
break Err(Error::Protocol("kill flag is true"));
}
continue;
},
};
Expand Down Expand Up @@ -164,15 +168,6 @@ async fn run(rpc: &Client) -> Result<(), Error> {
break;
}
};
#[cfg(test)]
if line == "kill".to_string() {
server_loop_err_comms_tx
.send(Error::Protocol("kill signal"))
.await
.unwrap();
log::info!("Kill signal received, stopping watchtower....");
break;
}

line = line.trim_end().to_string();
let message_result = handle_message(line, &watched_txes_comms_tx).await;
Expand Down
1 change: 0 additions & 1 deletion tests/maker-wallet-1

This file was deleted.

Loading

0 comments on commit f48a2f4

Please sign in to comment.