Clean up some logs and comments

This commit is contained in:
Lucas Soriano del Pino 2020-10-30 15:51:46 +11:00
parent 4d4acde476
commit 7fa7641feb
13 changed files with 88 additions and 82 deletions

View file

@ -12,8 +12,7 @@ use libp2p::{
use rand::rngs::OsRng;
use std::{sync::Arc, time::Duration};
use tokio::sync::Mutex;
use tracing::{info, warn};
use xmr_btc::alice;
use tracing::{debug, info, warn};
mod amounts;
mod message0;
@ -34,14 +33,12 @@ use crate::{
SwapAmounts, PUNISH_TIMELOCK, REFUND_TIMELOCK,
};
use xmr_btc::{
alice::{action_generator, Action, ReceiveBitcoinRedeemEncsig, State0},
alice::{self, action_generator, Action, ReceiveBitcoinRedeemEncsig, State0},
bitcoin::BroadcastSignedTransaction,
bob,
monero::{CreateWalletForOutput, Transfer},
};
pub type Swarm = libp2p::Swarm<Alice>;
pub async fn swap(
bitcoin_wallet: Arc<bitcoin::Wallet>,
monero_wallet: Arc<monero::Wallet>,
@ -55,15 +52,14 @@ pub async fn swap(
impl Network {
pub async fn send_message2(&mut self, proof: monero::TransferProof) {
tracing::debug!("Sending transfer proof");
match self.channel.take() {
None => warn!("Channel not found, did you call this twice?"),
Some(channel) => {
let mut guard = self.swarm.lock().await;
guard.send_message2(channel, alice::Message2 {
tx_lock_proof: proof,
})
});
info!("Sent transfer proof");
}
}
}
@ -78,17 +74,12 @@ pub async fn swap(
#[derive(Debug)]
struct UnexpectedMessage;
tracing::debug!("Receiving bitcoin redeem encsig");
(|| async {
let encsig = (|| async {
let mut guard = self.swarm.lock().await;
let encsig = match guard.next().await {
OutEvent::Message3(msg) => {
tracing::debug!("Got redeem encsig from Bob");
msg.tx_redeem_encsig
}
OutEvent::Message3(msg) => msg.tx_redeem_encsig,
other => {
warn!("Expected Bob's Message3, got: {:?}", other);
warn!("Expected Bob's Bitcoin redeem encsig, got: {:?}", other);
return Err(backoff::Error::Transient(UnexpectedMessage));
}
};
@ -97,33 +88,35 @@ pub async fn swap(
})
.retry(ConstantBackoff::new(Duration::from_secs(1)))
.await
.expect("transient errors to be retried")
.expect("transient errors to be retried");
info!("Received Bitcoin redeem encsig");
encsig
}
}
tracing::debug!("swapping ...");
let mut swarm = new_swarm(listen, local_port)?;
let message0: bob::Message0;
let mut state0: Option<alice::State0> = None;
let mut last_amounts: Option<SwapAmounts> = None;
// TODO: This loop is a neat idea for local development, as it allows us to keep
// Alice up and let Bob keep trying to connect, request amounts and/or send the
// first message of the handshake, but it comes at the cost of needing to handle
// mutable state, which has already been the source of a bug at one point. This
// is an obvious candidate for refactoring
loop {
match swarm.next().await {
OutEvent::ConnectionEstablished(id) => {
info!("Connection established with: {}", id);
OutEvent::ConnectionEstablished(bob) => {
info!("Connection established with: {}", bob);
}
OutEvent::Request(amounts::OutEvent::Btc { btc, channel }) => {
let amounts = calculate_amounts(btc);
// TODO: We cache the last amounts returned, this needs improving along with
// verification of message 0.
last_amounts = Some(amounts);
swarm.send_amounts(channel, amounts);
let (xmr, btc) = match last_amounts {
Some(p) => (p.xmr, p.btc),
None => unreachable!("should have amounts by here"),
};
let SwapAmounts { btc, xmr } = amounts;
let redeem_address = bitcoin_wallet.as_ref().new_address().await?;
let punish_address = redeem_address.clone();
@ -139,6 +132,8 @@ pub async fn swap(
redeem_address,
punish_address,
);
info!("Commencing handshake");
swarm.set_state0(state.clone());
state0 = Some(state)
@ -156,10 +151,7 @@ pub async fn swap(
};
}
let state1 = state0
.expect("to be set")
.receive(message0)
.expect("failed to receive msg 0");
let state1 = state0.expect("to be set").receive(message0)?;
let (state2, channel) = match swarm.next().await {
OutEvent::Message1 { msg, channel } => {
@ -197,7 +189,7 @@ pub async fn swap(
loop {
let state = action_generator.async_resume().await;
tracing::info!("resumed execution of alice generator, got: {:?}", state);
tracing::info!("Resumed execution of generator, got: {:?}", state);
match state {
GeneratorState::Yielded(Action::LockXmr {
@ -211,6 +203,7 @@ pub async fn swap(
let mut guard = network.as_ref().lock().await;
guard.send_message2(transfer_proof).await;
info!("Sent transfer proof");
}
GeneratorState::Yielded(Action::RedeemBtc(tx)) => {
@ -235,6 +228,8 @@ pub async fn swap(
}
}
pub type Swarm = libp2p::Swarm<Alice>;
fn new_swarm(listen: Multiaddr, port: Option<u16>) -> Result<Swarm> {
use anyhow::Context as _;
@ -366,11 +361,12 @@ impl Alice {
pub fn send_amounts(&mut self, channel: ResponseChannel<AliceToBob>, amounts: SwapAmounts) {
let msg = AliceToBob::Amounts(amounts);
self.amounts.send(channel, msg);
info!("Sent amounts response");
}
/// Message0 gets sent within the network layer using this state0.
pub fn set_state0(&mut self, state: State0) {
info!("Set state 0");
debug!("Set state 0");
let _ = self.message0.set_state(state);
}
@ -380,7 +376,8 @@ impl Alice {
channel: ResponseChannel<AliceToBob>,
msg: xmr_btc::alice::Message1,
) {
self.message1.send(channel, msg)
self.message1.send(channel, msg);
debug!("Sent Message1");
}
/// Send Message2 to Bob in response to receiving his Message2.
@ -389,7 +386,8 @@ impl Alice {
channel: ResponseChannel<AliceToBob>,
msg: xmr_btc::alice::Message2,
) {
self.message2.send(channel, msg)
self.message2.send(channel, msg);
debug!("Sent Message2");
}
}
@ -410,11 +408,11 @@ impl Default for Alice {
}
fn calculate_amounts(btc: ::bitcoin::Amount) -> SwapAmounts {
const XMR_PER_BTC: u64 = 100; // TODO: Get this from an exchange.
// TODO: Get this from an exchange.
// This value corresponds to 100 XMR per BTC
const PICONERO_PER_SAT: u64 = 1_000_000;
// TODO: Check that this is correct.
// XMR uses 12 zerose BTC uses 8.
let picos = (btc.as_sat() * 10000) * XMR_PER_BTC;
let picos = btc.as_sat() * PICONERO_PER_SAT;
let xmr = monero::Amount::from_piconero(picos);
SwapAmounts { btc, xmr }