Do a bunch of cleanups

This commit is contained in:
Tobin C. Harding 2020-10-22 13:30:07 +11:00
parent 0f17ec076c
commit ad006fae6a
7 changed files with 33 additions and 31 deletions

View File

@ -6,7 +6,7 @@ use libp2p::{
request_response::ResponseChannel, request_response::ResponseChannel,
NetworkBehaviour, PeerId, NetworkBehaviour, PeerId,
}; };
use rand::{CryptoRng, RngCore}; use rand::rngs::OsRng;
use std::{thread, time::Duration}; use std::{thread, time::Duration};
use tracing::debug; use tracing::debug;
@ -21,21 +21,20 @@ use crate::{
request_response::{AliceToBob, TIMEOUT}, request_response::{AliceToBob, TIMEOUT},
transport, TokioExecutor, transport, TokioExecutor,
}, },
SwapParams, PUNISH_TIMELOCK, REFUND_TIMELOCK, SwapAmounts, PUNISH_TIMELOCK, REFUND_TIMELOCK,
}; };
use xmr_btc::{alice::State0, bob, monero}; use xmr_btc::{alice::State0, bob, monero};
pub type Swarm = libp2p::Swarm<Alice>; pub type Swarm = libp2p::Swarm<Alice>;
#[allow(unused_assignments)] // Due to the mutable message0? #[allow(unused_assignments)] // Due to the mutable message0?
pub async fn swap<R: RngCore + CryptoRng>( pub async fn swap(
listen: Multiaddr, listen: Multiaddr,
rng: &mut R,
redeem_address: ::bitcoin::Address, redeem_address: ::bitcoin::Address,
punish_address: ::bitcoin::Address, punish_address: ::bitcoin::Address,
) -> Result<()> { ) -> Result<()> {
let mut message0: Option<bob::Message0> = None; let mut message0: Option<bob::Message0> = None;
let mut last_amounts: Option<SwapParams> = None; let mut last_amounts: Option<SwapAmounts> = None;
let mut swarm = new_swarm(listen)?; let mut swarm = new_swarm(listen)?;
@ -65,10 +64,12 @@ pub async fn swap<R: RngCore + CryptoRng>(
None => unreachable!("should have amounts by here"), None => unreachable!("should have amounts by here"),
}; };
// FIXME: Too many `bitcoin` crates/modules.
let xmr = monero::Amount::from_piconero(xmr.as_piconero()); let xmr = monero::Amount::from_piconero(xmr.as_piconero());
// TODO: This should be the Amount exported by xmr_btc.
let btc = ::bitcoin::Amount::from_sat(btc.as_sat()); let btc = ::bitcoin::Amount::from_sat(btc.as_sat());
// TODO: Pass this in using <R: RngCore + CryptoRng>
let rng = &mut OsRng;
let state0 = State0::new( let state0 = State0::new(
rng, rng,
btc, btc,
@ -195,8 +196,8 @@ impl Alice {
} }
/// Alice always sends her messages as a response to a request from Bob. /// Alice always sends her messages as a response to a request from Bob.
pub fn send_amounts(&mut self, channel: ResponseChannel<AliceToBob>, p: SwapParams) { pub fn send_amounts(&mut self, channel: ResponseChannel<AliceToBob>, amounts: SwapAmounts) {
let msg = AliceToBob::Amounts(p); let msg = AliceToBob::Amounts(amounts);
self.amounts.send(channel, msg); self.amounts.send(channel, msg);
} }
@ -228,15 +229,15 @@ impl Default for Alice {
} }
} }
// TODO: Check that this is correct. fn calculate_amounts(btc: ::bitcoin::Amount) -> SwapAmounts {
fn calculate_amounts(btc: ::bitcoin::Amount) -> SwapParams {
const XMR_PER_BTC: u64 = 100; // TODO: Get this from an exchange. const XMR_PER_BTC: u64 = 100; // TODO: Get this from an exchange.
// TODO: Check that this is correct.
// XMR uses 12 zerose BTC uses 8. // XMR uses 12 zerose BTC uses 8.
let picos = (btc.as_sat() * 10000) * XMR_PER_BTC; let picos = (btc.as_sat() * 10000) * XMR_PER_BTC;
let xmr = monero::Amount::from_piconero(picos); let xmr = monero::Amount::from_piconero(picos);
SwapParams { btc, xmr } SwapAmounts { btc, xmr }
} }
#[cfg(test)] #[cfg(test)]
@ -251,7 +252,7 @@ mod tests {
let btc = ::bitcoin::Amount::from_sat(ONE_BTC); let btc = ::bitcoin::Amount::from_sat(ONE_BTC);
let want = monero::Amount::from_piconero(HUNDRED_XMR); let want = monero::Amount::from_piconero(HUNDRED_XMR);
let SwapParams { xmr: got, .. } = calculate_amounts(btc); let SwapAmounts { xmr: got, .. } = calculate_amounts(btc);
assert_eq!(got, want); assert_eq!(got, want);
} }
} }

View File

@ -72,6 +72,7 @@ where
let xmr = xmr_btc::monero::Amount::from_piconero(xmr.as_piconero()); let xmr = xmr_btc::monero::Amount::from_piconero(xmr.as_piconero());
let btc = ::bitcoin::Amount::from_sat(btc.as_sat()); let btc = ::bitcoin::Amount::from_sat(btc.as_sat());
// TODO: Pass this in using <R: RngCore + CryptoRng>
let rng = &mut OsRng; let rng = &mut OsRng;
let state0 = State0::new( let state0 = State0::new(
rng, rng,

View File

@ -16,12 +16,12 @@ use tracing::error;
use crate::{ use crate::{
network::request_response::{AliceToBob, BobToAlice, Codec, Protocol}, network::request_response::{AliceToBob, BobToAlice, Codec, Protocol},
SwapParams, SwapAmounts,
}; };
#[derive(Debug)] #[derive(Debug)]
pub enum OutEvent { pub enum OutEvent {
Amounts(SwapParams), Amounts(SwapAmounts),
} }
/// A `NetworkBehaviour` that represents getting the amounts of an XMR/BTC swap. /// A `NetworkBehaviour` that represents getting the amounts of an XMR/BTC swap.

View File

@ -9,7 +9,7 @@ pub mod network;
pub const ONE_BTC: u64 = 100_000_000; pub const ONE_BTC: u64 = 100_000_000;
const REFUND_TIMELOCK: u32 = 10; // FIXME: What should this be? const REFUND_TIMELOCK: u32 = 10; // Relative timelock, this is number of blocks. TODO: What should it be?
const PUNISH_TIMELOCK: u32 = 20; // FIXME: What should this be? const PUNISH_TIMELOCK: u32 = 20; // FIXME: What should this be?
pub type Never = std::convert::Infallible; pub type Never = std::convert::Infallible;
@ -17,7 +17,7 @@ pub type Never = std::convert::Infallible;
/// Commands sent from Bob to the main task. /// Commands sent from Bob to the main task.
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub enum Cmd { pub enum Cmd {
VerifyAmounts(SwapParams), VerifyAmounts(SwapAmounts),
} }
/// Responses send from the main task back to Bob. /// Responses send from the main task back to Bob.
@ -27,9 +27,9 @@ pub enum Rsp {
Abort, Abort,
} }
/// XMR/BTC swap parameters. /// XMR/BTC swap amounts.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)] #[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct SwapParams { pub struct SwapAmounts {
/// Amount of BTC to swap. /// Amount of BTC to swap.
#[serde(with = "::bitcoin::util::amount::serde::as_sat")] #[serde(with = "::bitcoin::util::amount::serde::as_sat")]
pub btc: ::bitcoin::Amount, pub btc: ::bitcoin::Amount,
@ -38,7 +38,7 @@ pub struct SwapParams {
pub xmr: xmr_btc::monero::Amount, pub xmr: xmr_btc::monero::Amount,
} }
impl Display for SwapParams { impl Display for SwapAmounts {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( write!(
f, f,

View File

@ -16,7 +16,6 @@ use anyhow::{bail, Result};
use futures::{channel::mpsc, StreamExt}; use futures::{channel::mpsc, StreamExt};
use libp2p::Multiaddr; use libp2p::Multiaddr;
use log::LevelFilter; use log::LevelFilter;
use rand::rngs::OsRng;
use std::{io, io::Write, process}; use std::{io, io::Write, process};
use structopt::StructOpt; use structopt::StructOpt;
use tracing::info; use tracing::info;
@ -26,10 +25,13 @@ mod cli;
mod trace; mod trace;
use cli::Options; use cli::Options;
use swap::{alice, bitcoin::Wallet, bob, Cmd, Rsp, SwapParams}; use swap::{alice, bitcoin::Wallet, bob, Cmd, Rsp, SwapAmounts};
use xmr_btc::bitcoin::BuildTxLockPsbt; use xmr_btc::bitcoin::BuildTxLockPsbt;
// TODO: Add root seed file instead of generating new seed each run.
// TODO: Add root seed file instead of generating new seed each run.
// TODO: Remove all instances of the todo! macro
// TODO: Add a config file with these in it.
// Alice's address and port until we have a config file. // Alice's address and port until we have a config file.
pub const PORT: u16 = 9876; // Arbitrarily chosen. pub const PORT: u16 = 9876; // Arbitrarily chosen.
pub const ADDR: &str = "127.0.0.1"; pub const ADDR: &str = "127.0.0.1";
@ -97,7 +99,7 @@ async fn swap_as_alice(
redeem: bitcoin::Address, redeem: bitcoin::Address,
punish: bitcoin::Address, punish: bitcoin::Address,
) -> Result<()> { ) -> Result<()> {
alice::swap(addr, &mut OsRng, redeem, punish).await alice::swap(addr, redeem, punish).await
} }
async fn swap_as_bob<W>( async fn swap_as_bob<W>(
@ -132,10 +134,10 @@ where
} }
} }
fn verify(p: SwapParams) -> Rsp { fn verify(amounts: SwapAmounts) -> Rsp {
let mut s = String::new(); let mut s = String::new();
println!("Got rate from Alice for XMR/BTC swap\n"); println!("Got rate from Alice for XMR/BTC swap\n");
println!("{}", p); println!("{}", amounts);
print!("Would you like to continue with this swap [y/N]: "); print!("Would you like to continue with this swap [y/N]: ");
let _ = io::stdout().flush(); let _ = io::stdout().flush();
io::stdin() io::stdin()

View File

@ -25,8 +25,7 @@ pub struct PeerTracker {
} }
impl PeerTracker { impl PeerTracker {
/// Returns an arbitrary connected counterparty. /// Returns the peer id of counterparty if we are connected.
/// This is useful if we are connected to a single other node.
pub fn counterparty_peer_id(&self) -> Option<PeerId> { pub fn counterparty_peer_id(&self) -> Option<PeerId> {
if let Some((id, _)) = &self.connected { if let Some((id, _)) = &self.connected {
return Some(id.clone()); return Some(id.clone());
@ -34,8 +33,7 @@ impl PeerTracker {
None None
} }
/// Returns an arbitrary connected counterparty. /// Returns the multiaddr of counterparty if we are connected.
/// This is useful if we are connected to a single other node.
pub fn counterparty_addr(&self) -> Option<Multiaddr> { pub fn counterparty_addr(&self) -> Option<Multiaddr> {
if let Some((_, addr)) = &self.connected { if let Some((_, addr)) = &self.connected {
return Some(addr.clone()); return Some(addr.clone());

View File

@ -7,7 +7,7 @@ use libp2p::{
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{fmt::Debug, io}; use std::{fmt::Debug, io};
use crate::SwapParams; use crate::SwapAmounts;
use xmr_btc::{alice, bob, monero}; use xmr_btc::{alice, bob, monero};
/// Time to wait for a response back once we send a request. /// Time to wait for a response back once we send a request.
@ -28,7 +28,7 @@ pub enum BobToAlice {
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
pub enum AliceToBob { pub enum AliceToBob {
Amounts(SwapParams), Amounts(SwapAmounts),
Message0(alice::Message0), Message0(alice::Message0),
Message1(alice::Message1), Message1(alice::Message1),
} }