diff --git a/Cargo.toml b/Cargo.toml index 4a070873..652a7bcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tokio = { version = "0.3", features = ["full"] } log = "^0.4" +env_logger = "0.7" futures = "0.3" rand = "0.7.3" itertools = "0.9.0" diff --git a/src/main.rs b/src/main.rs index 66944a24..95b8f658 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ use dirs::home_dir; use std::io; use std::iter::repeat; use std::path::PathBuf; +use std::sync::Once; use std::sync::{Arc, RwLock}; use bitcoin::hashes::hex::ToHex; @@ -340,7 +341,21 @@ enum Subcommand { CoinswapSend, } +static INIT: Once = Once::new(); + +/// Setup function that will only run once, even if called multiple times. +fn setup_logger() { + INIT.call_once(|| { + env_logger::builder() + .is_test(true) + .filter_module("teleport", log::LevelFilter::Trace) + .init(); + }); +} + fn main() -> Result<(), Box> { + setup_logger(); + let args = ArgsWithWalletFile::from_args(); match args.subcommand { @@ -429,6 +444,8 @@ mod test { // wallet name `teleport` loaded and have enough balance to execute transactions. #[tokio::test] async fn test_standard_coin_swap() { + setup_logger(); + let rpc = get_bitcoin_rpc().unwrap(); // unlock all utxos to avoid "insufficient fund" error diff --git a/src/maker_protocol.rs b/src/maker_protocol.rs index 3e304aa8..b888d048 100644 --- a/src/maker_protocol.rs +++ b/src/maker_protocol.rs @@ -49,8 +49,8 @@ enum ExpectedMessage { #[tokio::main] pub async fn start_maker(rpc: Arc, wallet: Arc>, port: u16) { match run(rpc, wallet, port).await { - Ok(_o) => println!("maker ended without error"), - Err(e) => println!("maker ended with err {:?}", e), + Ok(_o) => log::trace!("maker ended without error"), + Err(e) => log::trace!("maker ended with err {:?}", e), }; } @@ -64,7 +64,7 @@ struct ConnectionState { async fn run(rpc: Arc, wallet: Arc>, port: u16) -> Result<(), Error> { //TODO port number in config file let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await?; - log::trace!(target: "maker", "listening on port {}", port); + log::trace!("listening on port {}", port); let (server_loop_comms_tx, mut server_loop_comms_rx) = mpsc::channel::(100); let mut accepting_clients = true; @@ -75,12 +75,12 @@ async fn run(rpc: Arc, wallet: Arc>, port: u16) -> Result //unwrap the option here because we'll never close the mscp so it will always work match client_err.as_ref().unwrap() { Error::Rpc(_e) => { - println!("lost connection with bitcoin node, temporarily shutting \ + log::trace!("lost connection with bitcoin node, temporarily shutting \ down server until connection reestablished"); accepting_clients = false; continue; }, - _ => println!("ending server"), + _ => log::trace!("ending server"), } break Err(client_err.unwrap()); }, @@ -88,17 +88,17 @@ async fn run(rpc: Arc, wallet: Arc>, port: u16) -> Result _ = sleep(Duration::from_secs(60)) => { let r = rpc.get_best_block_hash(); accepting_clients = r.is_ok(); - println!("timeout branch, accepting clients={}", accepting_clients); + log::trace!("timeout branch, accepting clients={}", accepting_clients); continue; }, }; if !accepting_clients { - println!("rejecting connection from {:?}", addr); + log::trace!("rejecting connection from {:?}", addr); continue; } - println!("accepted connection from {:?}", addr); + log::trace!("accepted connection from {:?}", addr); let client_rpc = Arc::clone(&rpc); let client_wallet = Arc::clone(&wallet); let server_loop_comms_tx = server_loop_comms_tx.clone(); @@ -123,7 +123,7 @@ async fn run(rpc: Arc, wallet: Arc>, port: u16) -> Result ) .await { - println!("io error sending first message: {:?}", e); + log::trace!("io error sending first message: {:?}", e); return; } @@ -131,12 +131,12 @@ async fn run(rpc: Arc, wallet: Arc>, port: u16) -> Result let mut line = String::new(); match reader.read_line(&mut line).await { Ok(n) if n == 0 => { - log::trace!(target: "maker", "reached EOF"); + log::trace!("reached EOF"); break; } Ok(_n) => (), Err(e) => { - println!("error reading from socket: {:?}", e); + log::trace!("error reading from socket: {:?}", e); break; } }; @@ -146,7 +146,7 @@ async fn run(rpc: Arc, wallet: Arc>, port: u16) -> Result .send(Error::Protocol("kill signal")) .await .unwrap(); - println!("Kill signal received, stopping maker...."); + log::trace!("Kill signal received, stopping maker...."); break; } @@ -161,14 +161,14 @@ async fn run(rpc: Arc, wallet: Arc>, port: u16) -> Result Ok(reply) => { if let Some(message) = reply { if let Err(e) = send_message(&mut socket_writer, &message).await { - println!("closing due to io error sending message: {:?}", e); + log::trace!("closing due to io error sending message: {:?}", e); break; } } //if reply is None then dont send anything to client } Err(err) => { - println!("error handling client request: {:?}", err); + log::trace!("error handling client request: {:?}", err); match err { Error::Network(_e) => (), Error::Protocol(_e) => (), @@ -425,7 +425,7 @@ fn handle_proof_of_funding( &funding_info.contract_redeemscript, ); let (coin_privkey, coin_other_pubkey, hashlock_privkey) = incoming_swapcoin_keys; - println!( + log::trace!( "adding incoming_swapcoin contract_tx = {:?} fo = {:?}", my_receivers_contract_tx.clone(), funding_output @@ -672,6 +672,6 @@ fn handle_private_key_handover( } } wallet_ref.update_swap_coins_list()?; - println!("successfully completed coinswap"); + log::trace!("successfully completed coinswap"); Ok(None) } diff --git a/src/taker_protocol.rs b/src/taker_protocol.rs index 8f4036d9..c464bec2 100644 --- a/src/taker_protocol.rs +++ b/src/taker_protocol.rs @@ -48,13 +48,13 @@ use crate::wallet_sync::{ pub async fn start_taker(rpc: &Client, wallet: &mut Wallet) { match run(rpc, wallet).await { Ok(_o) => (), - Err(e) => log::trace!(target: "taker", "err {:?}", e), + Err(e) => log::trace!("err {:?}", e), }; } async fn run(rpc: &Client, wallet: &mut Wallet) -> Result<(), Error> { let mut offers_addresses = sync_offerbook().await; - log::trace!(target: "taker", "offers_addresses = {:?}", offers_addresses); + log::trace!("offers_addresses = {:?}", offers_addresses); send_coinswap(rpc, wallet, &mut offers_addresses).await?; Ok(()) @@ -79,7 +79,7 @@ async fn send_coinswap( let first_maker = maker_offers_addresses.last().unwrap(); let last_maker = maker_offers_addresses.first().unwrap().clone(); - log::trace!(target: "taker", "coinswapping to first maker1 = {}", first_maker.address); + log::trace!("coinswapping to first maker1 = {}", first_maker.address); let ( first_maker_multisig_pubkeys, @@ -139,7 +139,7 @@ async fn send_coinswap( for maker_index in 0..maker_count { let maker = maker_offers_addresses.pop().unwrap(); - log::trace!(target: "taker", "coinswapping to maker = {:?}", maker.address); + log::trace!("coinswapping to maker = {:?}", maker.address); let maker_refund_locktime = REFUND_LOCKTIME + REFUND_LOCKTIME_STEP * (maker_count - maker_index - 1); let is_taker_next_peer = maker_index == maker_count - 1; @@ -396,7 +396,7 @@ async fn send_coinswap( } wallet.update_swap_coins_list().unwrap(); - println!("successfully completed coinswap"); + log::trace!("successfully completed coinswap"); Ok(()) } @@ -404,7 +404,7 @@ async fn send_message( socket_writer: &mut WriteHalf<'_>, message: TakerToMakerMessage, ) -> Result<(), Error> { - println!("=> {:?}", message); + log::trace!("=> {:?}", message); let mut result_bytes = serde_json::to_vec(&message).map_err(|e| io::Error::from(e))?; result_bytes.push(b'\n'); socket_writer.write_all(&result_bytes).await?; @@ -426,14 +426,14 @@ async fn read_message(reader: &mut BufReader>) -> Result return Err(Error::Protocol("json parsing error")), }; - log::trace!(target: "taker", "<= {:?}", message); + log::trace!("<= {:?}", message); Ok(message) } async fn handshake_maker( socket: &mut TcpStream, ) -> Result<(BufReader>, WriteHalf<'_>), Error> { - println!("connected to maker"); + log::trace!("connected to maker"); let (reader, mut socket_writer) = socket.split(); let mut socket_reader = BufReader::new(reader); @@ -513,7 +513,7 @@ async fn request_senders_contract_tx_signatures( hashvalue: Hash160, locktime: u16, ) -> Result, Error> { - println!( + log::trace!( "requesting senders contract tx sig from maker = {}", maker_address ); @@ -578,7 +578,7 @@ async fn request_receivers_contract_tx_signatures( incoming_swapcoins: &[S], receivers_contract_txes: &[Transaction], ) -> Result, Error> { - println!( + log::trace!( "requesting receivers contract tx sig from maker = {}", maker_address ); @@ -625,7 +625,7 @@ async fn wait_for_funding_tx_confirmation( rpc: &Client, funding_txids: &[Txid], ) -> Result<(Vec, Vec), Error> { - println!( + log::trace!( "waiting for funding transaction to confirm, txids={:?}", funding_txids ); @@ -645,7 +645,7 @@ async fn wait_for_funding_tx_confirmation( if gettx.info.confirmations >= 1 { txid_tx_map.insert(*txid, deserialize::(&gettx.hex).unwrap()); txid_blockhash_map.insert(*txid, gettx.info.blockhash.unwrap()); - log::trace!(target: "taker", "funding tx {} reached 1 confirmation(s)", txid); + log::trace!("funding tx {} reached 1 confirmation(s)", txid); } } if txid_tx_map.len() == funding_txids.len() { @@ -655,7 +655,7 @@ async fn wait_for_funding_tx_confirmation( #[cfg(test)] crate::test::generate_1_block(&get_bitcoin_rpc().unwrap()); } - log::trace!(target: "taker", "funding transactions confirmed"); + log::trace!("funding transactions confirmed"); let txes = funding_txids .iter()