Skip to content

Commit

Permalink
Adds env_logger
Browse files Browse the repository at this point in the history
This adds an env_logger and sets it up in main. Its run within a
std::sync::Once to ensure its only setup once even though main executes
multiple times. Logger will throw error otherwise.

Adds logging in the test.
  • Loading branch information
mojoX911 committed Sep 10, 2021
1 parent 171a386 commit d1ffc26
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 29 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
17 changes: 17 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<dyn std::error::Error>> {
setup_logger();

let args = ArgsWithWalletFile::from_args();

match args.subcommand {
Expand Down Expand Up @@ -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
Expand Down
32 changes: 16 additions & 16 deletions src/maker_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ enum ExpectedMessage {
#[tokio::main]
pub async fn start_maker(rpc: Arc<Client>, wallet: Arc<RwLock<Wallet>>, 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),
};
}

Expand All @@ -64,7 +64,7 @@ struct ConnectionState {
async fn run(rpc: Arc<Client>, wallet: Arc<RwLock<Wallet>>, 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::<Error>(100);
let mut accepting_clients = true;
Expand All @@ -75,30 +75,30 @@ async fn run(rpc: Arc<Client>, wallet: Arc<RwLock<Wallet>>, 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());
},
//TODO make a const for this magic number of how often to poll the rpc
_ = 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();
Expand All @@ -123,20 +123,20 @@ async fn run(rpc: Arc<Client>, wallet: Arc<RwLock<Wallet>>, port: u16) -> Result
)
.await
{
println!("io error sending first message: {:?}", e);
log::trace!("io error sending first message: {:?}", e);
return;
}

loop {
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;
}
};
Expand All @@ -146,7 +146,7 @@ async fn run(rpc: Arc<Client>, wallet: Arc<RwLock<Wallet>>, port: u16) -> Result
.send(Error::Protocol("kill signal"))
.await
.unwrap();
println!("Kill signal received, stopping maker....");
log::trace!("Kill signal received, stopping maker....");
break;
}

Expand All @@ -161,14 +161,14 @@ async fn run(rpc: Arc<Client>, wallet: Arc<RwLock<Wallet>>, 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) => (),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
26 changes: 13 additions & 13 deletions src/taker_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand All @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -396,15 +396,15 @@ async fn send_coinswap(
}
wallet.update_swap_coins_list().unwrap();

println!("successfully completed coinswap");
log::trace!("successfully completed coinswap");
Ok(())
}

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?;
Expand All @@ -426,14 +426,14 @@ async fn read_message(reader: &mut BufReader<ReadHalf<'_>>) -> Result<MakerToTak
Err(_e) => 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<ReadHalf<'_>>, 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);
Expand Down Expand Up @@ -513,7 +513,7 @@ async fn request_senders_contract_tx_signatures<S: SwapCoin>(
hashvalue: Hash160,
locktime: u16,
) -> Result<Vec<Signature>, Error> {
println!(
log::trace!(
"requesting senders contract tx sig from maker = {}",
maker_address
);
Expand Down Expand Up @@ -578,7 +578,7 @@ async fn request_receivers_contract_tx_signatures<S: SwapCoin>(
incoming_swapcoins: &[S],
receivers_contract_txes: &[Transaction],
) -> Result<Vec<Signature>, Error> {
println!(
log::trace!(
"requesting receivers contract tx sig from maker = {}",
maker_address
);
Expand Down Expand Up @@ -625,7 +625,7 @@ async fn wait_for_funding_tx_confirmation(
rpc: &Client,
funding_txids: &[Txid],
) -> Result<(Vec<Transaction>, Vec<String>), Error> {
println!(
log::trace!(
"waiting for funding transaction to confirm, txids={:?}",
funding_txids
);
Expand All @@ -645,7 +645,7 @@ async fn wait_for_funding_tx_confirmation(
if gettx.info.confirmations >= 1 {
txid_tx_map.insert(*txid, deserialize::<Transaction>(&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() {
Expand All @@ -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()
Expand Down

0 comments on commit d1ffc26

Please sign in to comment.