2020-10-15 18:14:39 -04:00
|
|
|
//! Run an XMR/BTC swap in the role of Bob.
|
|
|
|
//! Bob holds BTC and wishes receive XMR.
|
|
|
|
use anyhow::Result;
|
2020-10-26 22:26:40 -04:00
|
|
|
use async_trait::async_trait;
|
2020-10-27 02:18:19 -04:00
|
|
|
use backoff::{future::FutureOperation as _, ExponentialBackoff};
|
2020-10-15 18:14:39 -04:00
|
|
|
use futures::{
|
|
|
|
channel::mpsc::{Receiver, Sender},
|
2020-10-27 02:18:19 -04:00
|
|
|
FutureExt, StreamExt,
|
2020-10-15 18:14:39 -04:00
|
|
|
};
|
2020-10-26 22:26:40 -04:00
|
|
|
use genawaiter::GeneratorState;
|
2020-10-15 18:14:39 -04:00
|
|
|
use libp2p::{core::identity::Keypair, Multiaddr, NetworkBehaviour, PeerId};
|
2020-10-21 18:58:22 -04:00
|
|
|
use rand::rngs::OsRng;
|
2020-10-26 22:26:40 -04:00
|
|
|
use std::{process, sync::Arc};
|
|
|
|
use tokio::sync::Mutex;
|
2020-10-27 02:18:19 -04:00
|
|
|
use tracing::{debug, info, warn};
|
2020-10-15 18:14:39 -04:00
|
|
|
|
2020-10-19 19:10:28 -04:00
|
|
|
mod amounts;
|
2020-10-20 23:41:50 -04:00
|
|
|
mod message0;
|
2020-10-21 22:23:12 -04:00
|
|
|
mod message1;
|
2020-10-25 23:27:41 -04:00
|
|
|
mod message2;
|
2020-10-26 22:26:40 -04:00
|
|
|
mod message3;
|
2020-10-15 18:14:39 -04:00
|
|
|
|
2020-10-26 22:26:40 -04:00
|
|
|
use self::{amounts::*, message0::*, message1::*, message2::*, message3::*};
|
2020-10-15 18:14:39 -04:00
|
|
|
use crate::{
|
2020-10-26 22:26:40 -04:00
|
|
|
bitcoin,
|
|
|
|
bitcoin::TX_LOCK_MINE_TIMEOUT,
|
|
|
|
monero,
|
2020-10-15 18:14:39 -04:00
|
|
|
network::{
|
|
|
|
peer_tracker::{self, PeerTracker},
|
|
|
|
transport, TokioExecutor,
|
|
|
|
},
|
2020-10-26 22:26:40 -04:00
|
|
|
Cmd, Never, Rsp, SwapAmounts, PUNISH_TIMELOCK, REFUND_TIMELOCK,
|
2020-10-20 23:41:50 -04:00
|
|
|
};
|
|
|
|
use xmr_btc::{
|
2020-10-21 20:04:49 -04:00
|
|
|
alice,
|
2020-10-26 22:26:40 -04:00
|
|
|
bitcoin::{BroadcastSignedTransaction, EncryptedSignature, SignTxLock},
|
|
|
|
bob::{self, action_generator, ReceiveTransferProof, State0},
|
|
|
|
monero::CreateWalletForOutput,
|
2020-10-15 18:14:39 -04:00
|
|
|
};
|
|
|
|
|
2020-10-21 23:12:49 -04:00
|
|
|
// FIXME: This whole function is horrible, needs total re-write.
|
2020-10-26 22:26:40 -04:00
|
|
|
pub async fn swap(
|
|
|
|
bitcoin_wallet: Arc<bitcoin::Wallet>,
|
|
|
|
monero_wallet: Arc<monero::Wallet>,
|
2020-10-15 18:14:39 -04:00
|
|
|
btc: u64,
|
|
|
|
addr: Multiaddr,
|
|
|
|
mut cmd_tx: Sender<Cmd>,
|
|
|
|
mut rsp_rx: Receiver<Rsp>,
|
2020-10-20 23:41:50 -04:00
|
|
|
refund_address: ::bitcoin::Address,
|
2020-10-26 22:26:40 -04:00
|
|
|
) -> Result<()> {
|
|
|
|
struct Network(Swarm);
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
impl ReceiveTransferProof for Network {
|
|
|
|
async fn receive_transfer_proof(&mut self) -> monero::TransferProof {
|
2020-10-27 02:18:19 -04:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct UnexpectedMessage;
|
|
|
|
|
|
|
|
let future = self.0.next().shared();
|
|
|
|
|
|
|
|
(|| async {
|
|
|
|
let proof = match future.clone().await {
|
|
|
|
OutEvent::Message2(msg) => msg.tx_lock_proof,
|
|
|
|
other => {
|
|
|
|
warn!("Expected Alice's Message2, got: {:?}", other);
|
|
|
|
return Err(backoff::Error::Transient(UnexpectedMessage));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Result::<_, backoff::Error<UnexpectedMessage>>::Ok(proof)
|
|
|
|
})
|
|
|
|
.retry(ExponentialBackoff {
|
|
|
|
max_elapsed_time: None,
|
|
|
|
..Default::default()
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
.expect("transient errors to be retried")
|
2020-10-26 22:26:40 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-15 18:14:39 -04:00
|
|
|
let mut swarm = new_swarm()?;
|
|
|
|
|
|
|
|
libp2p::Swarm::dial_addr(&mut swarm, addr)?;
|
2020-10-20 23:41:50 -04:00
|
|
|
let alice = match swarm.next().await {
|
|
|
|
OutEvent::ConnectionEstablished(alice) => alice,
|
2020-10-15 18:14:39 -04:00
|
|
|
other => panic!("unexpected event: {:?}", other),
|
|
|
|
};
|
|
|
|
info!("Connection established.");
|
|
|
|
|
2020-10-20 23:41:50 -04:00
|
|
|
swarm.request_amounts(alice.clone(), btc);
|
2020-10-15 18:14:39 -04:00
|
|
|
|
2020-10-20 23:41:50 -04:00
|
|
|
let (btc, xmr) = match swarm.next().await {
|
2020-10-21 23:12:49 -04:00
|
|
|
OutEvent::Amounts(amounts) => {
|
|
|
|
debug!("Got amounts from Alice: {:?}", amounts);
|
|
|
|
let cmd = Cmd::VerifyAmounts(amounts);
|
2020-10-15 18:14:39 -04:00
|
|
|
cmd_tx.try_send(cmd)?;
|
|
|
|
let response = rsp_rx.next().await;
|
|
|
|
if response == Some(Rsp::Abort) {
|
|
|
|
info!("Amounts no good, aborting ...");
|
|
|
|
process::exit(0);
|
|
|
|
}
|
2020-10-20 23:41:50 -04:00
|
|
|
|
2020-10-15 18:14:39 -04:00
|
|
|
info!("User verified amounts, continuing with swap ...");
|
2020-10-21 23:12:49 -04:00
|
|
|
(amounts.btc, amounts.xmr)
|
2020-10-15 18:14:39 -04:00
|
|
|
}
|
|
|
|
other => panic!("unexpected event: {:?}", other),
|
2020-10-20 23:41:50 -04:00
|
|
|
};
|
|
|
|
|
2020-10-21 22:30:07 -04:00
|
|
|
// TODO: Pass this in using <R: RngCore + CryptoRng>
|
2020-10-21 18:58:22 -04:00
|
|
|
let rng = &mut OsRng;
|
2020-10-20 23:41:50 -04:00
|
|
|
let state0 = State0::new(
|
|
|
|
rng,
|
|
|
|
btc,
|
|
|
|
xmr,
|
|
|
|
REFUND_TIMELOCK,
|
|
|
|
PUNISH_TIMELOCK,
|
|
|
|
refund_address,
|
|
|
|
);
|
2020-10-21 22:23:12 -04:00
|
|
|
|
2020-10-20 23:41:50 -04:00
|
|
|
swarm.send_message0(alice.clone(), state0.next_message(rng));
|
2020-10-21 22:23:12 -04:00
|
|
|
let state1 = match swarm.next().await {
|
2020-10-26 22:26:40 -04:00
|
|
|
OutEvent::Message0(msg) => state0.receive(bitcoin_wallet.as_ref(), msg).await?,
|
2020-10-20 23:41:50 -04:00
|
|
|
other => panic!("unexpected event: {:?}", other),
|
|
|
|
};
|
2020-10-15 18:14:39 -04:00
|
|
|
|
2020-10-21 22:23:12 -04:00
|
|
|
swarm.send_message1(alice.clone(), state1.next_message());
|
2020-10-25 23:27:41 -04:00
|
|
|
let state2 = match swarm.next().await {
|
2020-10-21 22:23:12 -04:00
|
|
|
OutEvent::Message1(msg) => {
|
2020-10-26 19:09:53 -04:00
|
|
|
state1.receive(msg)? // TODO: Same as above.
|
2020-10-21 22:23:12 -04:00
|
|
|
}
|
|
|
|
other => panic!("unexpected event: {:?}", other),
|
|
|
|
};
|
|
|
|
|
2020-10-25 23:27:41 -04:00
|
|
|
swarm.send_message2(alice.clone(), state2.next_message());
|
|
|
|
|
|
|
|
info!("Handshake complete, we now have State2 for Bob.");
|
2020-10-21 22:23:12 -04:00
|
|
|
|
2020-10-26 22:26:40 -04:00
|
|
|
let network = Arc::new(Mutex::new(Network(swarm)));
|
|
|
|
|
|
|
|
let mut action_generator = action_generator(
|
|
|
|
network.clone(),
|
|
|
|
monero_wallet.clone(),
|
|
|
|
bitcoin_wallet.clone(),
|
|
|
|
state2,
|
|
|
|
TX_LOCK_MINE_TIMEOUT,
|
|
|
|
);
|
|
|
|
|
|
|
|
loop {
|
|
|
|
let state = action_generator.async_resume().await;
|
|
|
|
|
|
|
|
info!("resumed execution of bob generator, got: {:?}", state);
|
|
|
|
|
|
|
|
match state {
|
|
|
|
GeneratorState::Yielded(bob::Action::LockBtc(tx_lock)) => {
|
|
|
|
let signed_tx_lock = bitcoin_wallet.sign_tx_lock(tx_lock).await?;
|
|
|
|
let _ = bitcoin_wallet
|
|
|
|
.broadcast_signed_transaction(signed_tx_lock)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
GeneratorState::Yielded(bob::Action::SendBtcRedeemEncsig(tx_redeem_encsig)) => {
|
|
|
|
let mut guard = network.as_ref().lock().await;
|
|
|
|
guard.0.send_message3(alice.clone(), tx_redeem_encsig);
|
|
|
|
}
|
|
|
|
GeneratorState::Yielded(bob::Action::CreateXmrWalletForOutput {
|
|
|
|
spend_key,
|
|
|
|
view_key,
|
|
|
|
}) => {
|
|
|
|
monero_wallet
|
|
|
|
.create_and_load_wallet_for_output(spend_key, view_key)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
GeneratorState::Yielded(bob::Action::CancelBtc(tx_cancel)) => {
|
|
|
|
let _ = bitcoin_wallet
|
|
|
|
.broadcast_signed_transaction(tx_cancel)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
GeneratorState::Yielded(bob::Action::RefundBtc(tx_refund)) => {
|
|
|
|
let _ = bitcoin_wallet
|
|
|
|
.broadcast_signed_transaction(tx_refund)
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
GeneratorState::Complete(()) => return Ok(()),
|
|
|
|
}
|
|
|
|
}
|
2020-10-15 18:14:39 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub type Swarm = libp2p::Swarm<Bob>;
|
|
|
|
|
|
|
|
fn new_swarm() -> Result<Swarm> {
|
|
|
|
let behaviour = Bob::default();
|
|
|
|
|
|
|
|
let local_key_pair = behaviour.identity();
|
|
|
|
let local_peer_id = behaviour.peer_id();
|
|
|
|
|
2020-10-26 01:55:53 -04:00
|
|
|
let transport = {
|
|
|
|
#[cfg(feature = "tor")]
|
|
|
|
{
|
|
|
|
transport::build(local_key_pair, None)?
|
|
|
|
}
|
|
|
|
#[cfg(not(feature = "tor"))]
|
|
|
|
{
|
|
|
|
transport::build(local_key_pair)?
|
|
|
|
}
|
|
|
|
};
|
2020-10-15 18:14:39 -04:00
|
|
|
|
|
|
|
let swarm = libp2p::swarm::SwarmBuilder::new(transport, behaviour, local_peer_id.clone())
|
|
|
|
.executor(Box::new(TokioExecutor {
|
|
|
|
handle: tokio::runtime::Handle::current(),
|
|
|
|
}))
|
|
|
|
.build();
|
|
|
|
|
|
|
|
info!("Initialized swarm with identity {}", local_peer_id);
|
|
|
|
|
|
|
|
Ok(swarm)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::large_enum_variant)]
|
2020-10-27 02:18:19 -04:00
|
|
|
#[derive(Debug, Clone)]
|
2020-10-19 19:10:28 -04:00
|
|
|
pub enum OutEvent {
|
2020-10-15 18:14:39 -04:00
|
|
|
ConnectionEstablished(PeerId),
|
2020-10-21 23:12:49 -04:00
|
|
|
Amounts(SwapAmounts),
|
2020-10-21 20:04:49 -04:00
|
|
|
Message0(alice::Message0),
|
2020-10-21 22:23:12 -04:00
|
|
|
Message1(alice::Message1),
|
2020-10-26 21:11:03 -04:00
|
|
|
Message2(alice::Message2),
|
2020-10-15 18:14:39 -04:00
|
|
|
}
|
|
|
|
|
2020-10-19 19:10:28 -04:00
|
|
|
impl From<peer_tracker::OutEvent> for OutEvent {
|
|
|
|
fn from(event: peer_tracker::OutEvent) -> Self {
|
2020-10-15 18:14:39 -04:00
|
|
|
match event {
|
2020-10-19 19:10:28 -04:00
|
|
|
peer_tracker::OutEvent::ConnectionEstablished(id) => {
|
|
|
|
OutEvent::ConnectionEstablished(id)
|
2020-10-15 18:14:39 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-20 23:41:50 -04:00
|
|
|
impl From<amounts::OutEvent> for OutEvent {
|
|
|
|
fn from(event: amounts::OutEvent) -> Self {
|
2020-10-21 23:12:49 -04:00
|
|
|
match event {
|
|
|
|
amounts::OutEvent::Amounts(amounts) => OutEvent::Amounts(amounts),
|
|
|
|
}
|
2020-10-20 23:41:50 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<message0::OutEvent> for OutEvent {
|
|
|
|
fn from(event: message0::OutEvent) -> Self {
|
|
|
|
match event {
|
2020-10-21 20:04:49 -04:00
|
|
|
message0::OutEvent::Msg(msg) => OutEvent::Message0(msg),
|
2020-10-20 23:41:50 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-21 22:23:12 -04:00
|
|
|
impl From<message1::OutEvent> for OutEvent {
|
|
|
|
fn from(event: message1::OutEvent) -> Self {
|
|
|
|
match event {
|
|
|
|
message1::OutEvent::Msg(msg) => OutEvent::Message1(msg),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-26 21:11:03 -04:00
|
|
|
impl From<message2::OutEvent> for OutEvent {
|
|
|
|
fn from(event: message2::OutEvent) -> Self {
|
|
|
|
match event {
|
|
|
|
message2::OutEvent::Msg(msg) => OutEvent::Message2(msg),
|
|
|
|
}
|
2020-10-25 23:27:41 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-26 22:26:40 -04:00
|
|
|
impl From<Never> for OutEvent {
|
|
|
|
fn from(_: Never) -> Self {
|
|
|
|
panic!("not ever")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-15 18:14:39 -04:00
|
|
|
/// A `NetworkBehaviour` that represents an XMR/BTC swap node as Bob.
|
|
|
|
#[derive(NetworkBehaviour)]
|
2020-10-19 19:10:28 -04:00
|
|
|
#[behaviour(out_event = "OutEvent", event_process = false)]
|
2020-10-15 18:14:39 -04:00
|
|
|
#[allow(missing_debug_implementations)]
|
|
|
|
pub struct Bob {
|
|
|
|
pt: PeerTracker,
|
2020-10-20 23:41:50 -04:00
|
|
|
amounts: Amounts,
|
|
|
|
message0: Message0,
|
2020-10-21 22:23:12 -04:00
|
|
|
message1: Message1,
|
2020-10-25 23:27:41 -04:00
|
|
|
message2: Message2,
|
2020-10-26 22:26:40 -04:00
|
|
|
message3: Message3,
|
2020-10-15 18:14:39 -04:00
|
|
|
#[behaviour(ignore)]
|
|
|
|
identity: Keypair,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Bob {
|
|
|
|
pub fn identity(&self) -> Keypair {
|
|
|
|
self.identity.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn peer_id(&self) -> PeerId {
|
|
|
|
PeerId::from(self.identity.public())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sends a message to Alice to get current amounts based on `btc`.
|
2020-10-20 23:41:50 -04:00
|
|
|
pub fn request_amounts(&mut self, alice: PeerId, btc: u64) {
|
|
|
|
let btc = ::bitcoin::Amount::from_sat(btc);
|
|
|
|
let _id = self.amounts.request_amounts(alice.clone(), btc);
|
2020-10-15 18:14:39 -04:00
|
|
|
debug!("Requesting amounts from: {}", alice);
|
|
|
|
}
|
|
|
|
|
2020-10-21 22:23:12 -04:00
|
|
|
/// Sends Bob's first message to Alice.
|
2020-10-20 23:41:50 -04:00
|
|
|
pub fn send_message0(&mut self, alice: PeerId, msg: bob::Message0) {
|
|
|
|
self.message0.send(alice, msg)
|
|
|
|
}
|
|
|
|
|
2020-10-21 22:23:12 -04:00
|
|
|
/// Sends Bob's second message to Alice.
|
|
|
|
pub fn send_message1(&mut self, alice: PeerId, msg: bob::Message1) {
|
|
|
|
self.message1.send(alice, msg)
|
|
|
|
}
|
|
|
|
|
2020-10-25 23:27:41 -04:00
|
|
|
/// Sends Bob's third message to Alice.
|
|
|
|
pub fn send_message2(&mut self, alice: PeerId, msg: bob::Message2) {
|
|
|
|
self.message2.send(alice, msg)
|
|
|
|
}
|
|
|
|
|
2020-10-26 22:26:40 -04:00
|
|
|
/// Sends Bob's fourth message to Alice.
|
|
|
|
pub fn send_message3(&mut self, alice: PeerId, tx_redeem_encsig: EncryptedSignature) {
|
|
|
|
let msg = bob::Message3 { tx_redeem_encsig };
|
|
|
|
self.message3.send(alice, msg)
|
|
|
|
}
|
|
|
|
|
2020-10-15 18:14:39 -04:00
|
|
|
/// Returns Alice's peer id if we are connected.
|
|
|
|
pub fn peer_id_of_alice(&self) -> Option<PeerId> {
|
2020-10-19 19:10:28 -04:00
|
|
|
self.pt.counterparty_peer_id()
|
2020-10-15 18:14:39 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for Bob {
|
|
|
|
fn default() -> Bob {
|
|
|
|
let identity = Keypair::generate_ed25519();
|
|
|
|
|
|
|
|
Self {
|
|
|
|
pt: PeerTracker::default(),
|
2020-10-21 23:12:49 -04:00
|
|
|
amounts: Amounts::default(),
|
|
|
|
message0: Message0::default(),
|
|
|
|
message1: Message1::default(),
|
2020-10-25 23:27:41 -04:00
|
|
|
message2: Message2::default(),
|
2020-10-26 22:26:40 -04:00
|
|
|
message3: Message3::default(),
|
2020-10-15 18:14:39 -04:00
|
|
|
identity,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|