Bob refunds swap after restart that requires communication

As Bob is dialing Alice, we now ensure that we are connected to Alice
at each step that needs communication.
If we are not connected, we proceed with dialing.

In an attempt to improve libp2p usage, we also add known address of
Alice first and only use peer_id to dial.
This ensures that we use the expected peer id.
This commit is contained in:
Franck Royer 2020-12-18 17:39:04 +11:00
parent d9ea7ab605
commit 1a4bd0e2b4
No known key found for this signature in database
GPG key ID: A82ED75A8DFC50A4
14 changed files with 347 additions and 72 deletions

View file

@ -242,4 +242,8 @@ impl EventLoop {
}
}
}
pub fn peer_id(&self) -> PeerId {
self.swarm.peer_id()
}
}

View file

@ -13,7 +13,7 @@
#![forbid(unsafe_code)]
use anyhow::{Context, Result};
use libp2p::core::Multiaddr;
use libp2p::{core::Multiaddr, PeerId};
use prettytable::{row, Table};
use rand::rngs::OsRng;
use std::{convert::TryFrom, sync::Arc};
@ -111,6 +111,7 @@ async fn main() -> Result<()> {
.await?;
}
Command::BuyXmr {
alice_peer_id,
alice_addr,
bitcoind_url,
bitcoin_wallet_name,
@ -144,7 +145,7 @@ async fn main() -> Result<()> {
let bob_state = BobState::Started {
state0,
amounts,
addr: alice_addr,
alice_peer_id: alice_peer_id.clone(),
};
let swap_id = Uuid::new_v4();
@ -153,7 +154,16 @@ async fn main() -> Result<()> {
send_bitcoin, receive_monero, swap_id
);
bob_swap(swap_id, bob_state, bitcoin_wallet, monero_wallet, db).await?;
bob_swap(
swap_id,
bob_state,
bitcoin_wallet,
monero_wallet,
db,
alice_peer_id,
alice_addr,
)
.await?;
}
Command::History => {
let mut table = Table::new();
@ -173,6 +183,8 @@ async fn main() -> Result<()> {
bitcoin_wallet_name,
monero_wallet_rpc_url,
listen_addr,
alice_peer_id,
alice_addr,
} => {
let db_swap = db.get_state(swap_id)?;
@ -202,7 +214,16 @@ async fn main() -> Result<()> {
config,
)
.await?;
bob_swap(swap_id, bob_state, bitcoin_wallet, monero_wallet, db).await?;
bob_swap(
swap_id,
bob_state,
bitcoin_wallet,
monero_wallet,
db,
alice_peer_id,
alice_addr,
)
.await?;
} else {
anyhow::bail!("Unable to construct swap state for swap with id {}")
}
@ -277,6 +298,8 @@ async fn bob_swap(
bitcoin_wallet: Arc<bitcoin::Wallet>,
monero_wallet: Arc<monero::Wallet>,
db: Database,
alice_peer_id: PeerId,
alice_addr: Multiaddr,
) -> Result<BobState> {
let bob_behaviour = bob::Behaviour::default();
let bob_transport = build(bob_behaviour.identity())?;
@ -291,6 +314,8 @@ async fn bob_swap(
monero_wallet.clone(),
OsRng,
swap_id,
alice_peer_id,
alice_addr,
);
tokio::spawn(async move { event_loop.run().await });

View file

@ -10,7 +10,10 @@ use crate::{
SwapAmounts,
};
use anyhow::Result;
use libp2p::{core::identity::Keypair, NetworkBehaviour, PeerId};
use libp2p::{
core::{identity::Keypair, Multiaddr},
NetworkBehaviour, PeerId,
};
use tracing::{debug, info};
use xmr_btc::{
alice,
@ -159,9 +162,9 @@ impl Behaviour {
debug!("Sent Message3");
}
/// Returns Alice's peer id if we are connected.
pub fn peer_id_of_alice(&self) -> Option<PeerId> {
self.pt.counterparty_peer_id()
/// Add a known address for the given peer
pub fn add_address(&mut self, peer_id: PeerId, address: Multiaddr) {
self.pt.add_address(peer_id, address)
}
}

View file

@ -9,7 +9,7 @@ use tokio::{
stream::StreamExt,
sync::mpsc::{Receiver, Sender},
};
use tracing::info;
use tracing::{debug, error, info};
use xmr_btc::{alice, bitcoin::EncryptedSignature, bob};
pub struct Channels<T> {
@ -36,7 +36,8 @@ pub struct EventLoopHandle {
msg2: Receiver<alice::Message2>,
request_amounts: Sender<(PeerId, ::bitcoin::Amount)>,
conn_established: Receiver<PeerId>,
dial_alice: Sender<Multiaddr>,
dial_alice: Sender<PeerId>,
add_address: Sender<(PeerId, Multiaddr)>,
send_msg0: Sender<(PeerId, bob::Message0)>,
send_msg1: Sender<(PeerId, bob::Message1)>,
send_msg2: Sender<(PeerId, bob::Message2)>,
@ -44,13 +45,6 @@ pub struct EventLoopHandle {
}
impl EventLoopHandle {
pub async fn recv_conn_established(&mut self) -> Result<PeerId> {
self.conn_established
.recv()
.await
.ok_or_else(|| anyhow!("Failed to receive connection established from Bob"))
}
pub async fn recv_message0(&mut self) -> Result<alice::Message0> {
self.msg0
.recv()
@ -72,9 +66,24 @@ impl EventLoopHandle {
.ok_or_else(|| anyhow!("Failed o receive message 2 from Bob"))
}
pub async fn dial_alice(&mut self, addr: Multiaddr) -> Result<()> {
info!("sending msg to ourselves to dial alice: {}", addr);
let _ = self.dial_alice.send(addr).await?;
/// Dials other party and wait for the connection to be established.
/// Do nothing if we are already connected
pub async fn dial(&mut self, peer_id: PeerId) -> Result<()> {
let _ = self.dial_alice.send(peer_id).await?;
std::thread::sleep(std::time::Duration::from_millis(100));
self.conn_established
.recv()
.await
.ok_or_else(|| anyhow!("Failed to receive connection established from Alice"))?;
Ok(())
}
pub async fn add_address(&mut self, peer_id: PeerId, addr: Multiaddr) -> Result<()> {
debug!("Add address {} for peer id {}", addr, peer_id);
self.add_address.send((peer_id, addr)).await?;
Ok(())
}
@ -119,7 +128,8 @@ pub struct EventLoop {
msg2: Sender<alice::Message2>,
conn_established: Sender<PeerId>,
request_amounts: Receiver<(PeerId, ::bitcoin::Amount)>,
dial_alice: Receiver<Multiaddr>,
dial_alice: Receiver<PeerId>,
add_address: Receiver<(PeerId, Multiaddr)>,
send_msg0: Receiver<(PeerId, bob::Message0)>,
send_msg1: Receiver<(PeerId, bob::Message1)>,
send_msg2: Receiver<(PeerId, bob::Message2)>,
@ -142,6 +152,7 @@ impl EventLoop {
let msg2 = Channels::new();
let conn_established = Channels::new();
let dial_alice = Channels::new();
let add_address = Channels::new();
let send_msg0 = Channels::new();
let send_msg1 = Channels::new();
let send_msg2 = Channels::new();
@ -155,6 +166,7 @@ impl EventLoop {
msg2: msg2.sender,
conn_established: conn_established.sender,
dial_alice: dial_alice.receiver,
add_address: add_address.receiver,
send_msg0: send_msg0.receiver,
send_msg1: send_msg1.receiver,
send_msg2: send_msg2.receiver,
@ -168,6 +180,7 @@ impl EventLoop {
msg2: msg2.receiver,
conn_established: conn_established.receiver,
dial_alice: dial_alice.sender,
add_address: add_address.sender,
send_msg0: send_msg0.sender,
send_msg1: send_msg1.sender,
send_msg2: send_msg2.sender,
@ -182,8 +195,8 @@ impl EventLoop {
tokio::select! {
swarm_event = self.swarm.next().fuse() => {
match swarm_event {
OutEvent::ConnectionEstablished(alice) => {
let _ = self.conn_established.send(alice).await;
OutEvent::ConnectionEstablished(peer_id) => {
let _ = self.conn_established.send(peer_id).await;
}
OutEvent::Amounts(_amounts) => info!("Amounts received from Alice"),
OutEvent::Message0(msg) => {
@ -198,10 +211,25 @@ impl EventLoop {
OutEvent::Message3 => info!("Alice acknowledged message 3 received"),
}
},
addr = self.dial_alice.next().fuse() => {
if let Some(addr) = addr {
info!("dialing alice: {}", addr);
libp2p::Swarm::dial_addr(&mut self.swarm, addr).expect("Could not dial alice");
peer_id_addr = self.add_address.next().fuse() => {
if let Some((peer_id, addr)) = peer_id_addr {
debug!("Add address for {}: {}", peer_id, addr);
self.swarm.add_address(peer_id, addr);
}
},
peer_id = self.dial_alice.next().fuse() => {
if let Some(peer_id) = peer_id {
if self.swarm.pt.is_connected(&peer_id) {
debug!("Already connected to Alice: {}", peer_id);
let _ = self.conn_established.send(peer_id).await;
} else {
info!("dialing alice: {}", peer_id);
if let Err(err) = libp2p::Swarm::dial(&mut self.swarm, &peer_id) {
error!("Could not dial alice: {}", err);
// TODO(Franck): If Dial fails then we should report it.
}
}
}
},
amounts = self.request_amounts.next().fuse() => {

View file

@ -23,12 +23,12 @@ pub enum BobState {
Started {
state0: bob::State0,
amounts: SwapAmounts,
addr: Multiaddr,
alice_peer_id: PeerId,
},
Negotiated(bob::State2, PeerId),
BtcLocked(bob::State3, PeerId),
XmrLocked(bob::State4, PeerId),
EncSigSent(bob::State4, PeerId),
EncSigSent(bob::State4),
BtcRedeemed(bob::State5),
T1Expired(bob::State4),
Cancelled(bob::State4),
@ -67,7 +67,7 @@ impl From<BobState> for state::Bob {
BobState::Negotiated(state2, peer_id) => Bob::Negotiated { state2, peer_id },
BobState::BtcLocked(state3, peer_id) => Bob::BtcLocked { state3, peer_id },
BobState::XmrLocked(state4, peer_id) => Bob::XmrLocked { state4, peer_id },
BobState::EncSigSent(state4, peer_id) => Bob::EncSigSent { state4, peer_id },
BobState::EncSigSent(state4) => Bob::EncSigSent { state4 },
BobState::BtcRedeemed(state5) => Bob::BtcRedeemed(state5),
BobState::T1Expired(state4) => Bob::T1Expired(state4),
BobState::Cancelled(state4) => Bob::BtcCancelled(state4),
@ -88,7 +88,7 @@ impl TryFrom<state::Swap> for BobState {
Bob::Negotiated { state2, peer_id } => BobState::Negotiated(state2, peer_id),
Bob::BtcLocked { state3, peer_id } => BobState::BtcLocked(state3, peer_id),
Bob::XmrLocked { state4, peer_id } => BobState::XmrLocked(state4, peer_id),
Bob::EncSigSent { state4, peer_id } => BobState::EncSigSent(state4, peer_id),
Bob::EncSigSent { state4 } => BobState::EncSigSent(state4),
Bob::BtcRedeemed(state5) => BobState::BtcRedeemed(state5),
Bob::T1Expired(state4) => BobState::T1Expired(state4),
Bob::BtcCancelled(state4) => BobState::Cancelled(state4),
@ -102,18 +102,26 @@ impl TryFrom<state::Swap> for BobState {
}
}
// TODO(Franck): Make this a method on a struct
#[allow(clippy::too_many_arguments)]
pub async fn swap<R>(
state: BobState,
event_loop_handle: EventLoopHandle,
mut event_loop_handle: EventLoopHandle,
db: Database,
bitcoin_wallet: Arc<crate::bitcoin::Wallet>,
monero_wallet: Arc<crate::monero::Wallet>,
rng: R,
swap_id: Uuid,
alice_peer_id: PeerId,
alice_addr: Multiaddr,
) -> Result<BobState>
where
R: RngCore + CryptoRng + Send,
{
event_loop_handle
.add_address(alice_peer_id, alice_addr)
.await?;
run_until(
state,
is_complete,
@ -173,13 +181,15 @@ where
BobState::Started {
state0,
amounts,
addr,
alice_peer_id,
} => {
event_loop_handle.dial(alice_peer_id.clone()).await?;
let (state2, alice_peer_id) = negotiate(
state0,
amounts,
&mut event_loop_handle,
addr,
alice_peer_id.clone(),
&mut rng,
bitcoin_wallet.clone(),
)
@ -202,6 +212,8 @@ where
.await
}
BobState::Negotiated(state2, alice_peer_id) => {
// Do not lock Bitcoin if not connected to Alice.
event_loop_handle.dial(alice_peer_id.clone()).await?;
// Alice and Bob have exchanged info
let state3 = state2.lock_btc(bitcoin_wallet.as_ref()).await?;
@ -224,7 +236,10 @@ where
// Bob has locked Btc
// Watch for Alice to Lock Xmr or for t1 to elapse
BobState::BtcLocked(state3, alice_peer_id) => {
// todo: watch until t1, not indefinetely
// TODO(Franck): Refund if cannot connect to Alice.
event_loop_handle.dial(alice_peer_id.clone()).await?;
// todo: watch until t1, not indefinitely
let msg2 = event_loop_handle.recv_message2().await?;
let state4 = state3
.watch_for_lock_xmr(monero_wallet.as_ref(), msg2)
@ -247,12 +262,16 @@ where
.await
}
BobState::XmrLocked(state, alice_peer_id) => {
// TODO(Franck): Refund if cannot connect to Alice.
event_loop_handle.dial(alice_peer_id.clone()).await?;
let state = if let Epoch::T0 = state.current_epoch(bitcoin_wallet.as_ref()).await? {
// Alice has locked Xmr
// Bob sends Alice his key
let tx_redeem_encsig = state.tx_redeem_encsig();
let state4_clone = state.clone();
// TODO(Franck): Refund if message cannot be sent.
let enc_sig_sent_watcher =
event_loop_handle.send_message3(alice_peer_id.clone(), tx_redeem_encsig);
let bitcoin_wallet = bitcoin_wallet.clone();
@ -260,7 +279,7 @@ where
select! {
_ = enc_sig_sent_watcher => {
BobState::EncSigSent(state, alice_peer_id)
BobState::EncSigSent(state)
},
_ = t1_timeout => {
BobState::T1Expired(state)
@ -284,7 +303,7 @@ where
)
.await
}
BobState::EncSigSent(state, ..) => {
BobState::EncSigSent(state) => {
let state = if let Epoch::T0 = state.current_epoch(bitcoin_wallet.as_ref()).await? {
let state_clone = state.clone();
let redeem_watcher = state_clone.watch_for_redeem_btc(bitcoin_wallet.as_ref());
@ -401,7 +420,7 @@ pub async fn negotiate<R>(
state0: xmr_btc::bob::State0,
amounts: SwapAmounts,
swarm: &mut EventLoopHandle,
addr: Multiaddr,
alice_peer_id: PeerId,
mut rng: R,
bitcoin_wallet: Arc<crate::bitcoin::Wallet>,
) -> Result<(State2, PeerId)>
@ -409,10 +428,6 @@ where
R: RngCore + CryptoRng + Send,
{
tracing::trace!("Starting negotiate");
swarm.dial_alice(addr).await?;
let alice_peer_id = swarm.recv_conn_established().await?;
swarm
.request_amounts(alice_peer_id.clone(), amounts.btc)
.await?;

View file

@ -1,4 +1,4 @@
use libp2p::core::Multiaddr;
use libp2p::{core::Multiaddr, PeerId};
use url::Url;
use uuid::Uuid;
@ -47,6 +47,9 @@ pub enum Command {
receive_bitcoin: bitcoin::Amount,
},
BuyXmr {
#[structopt(short = "p", long = "connect-peer-id")]
alice_peer_id: PeerId,
#[structopt(short = "a", long = "connect-addr")]
alice_addr: Multiaddr,
@ -78,6 +81,12 @@ pub enum Command {
#[structopt(short = "id", long = "swap-id")]
swap_id: Uuid,
#[structopt(short = "p", long = "connect-peer-id")]
alice_peer_id: PeerId,
#[structopt(short = "a", long = "connect-addr")]
alice_addr: Multiaddr,
#[structopt(
short = "b",
long = "bitcoind-rpc",

View file

@ -7,7 +7,10 @@ use libp2p::{
},
Multiaddr, PeerId,
};
use std::{collections::VecDeque, task::Poll};
use std::{
collections::{HashMap, VecDeque},
task::Poll,
};
#[derive(Debug)]
pub enum OutEvent {
@ -21,10 +24,21 @@ pub enum OutEvent {
#[derive(Default, Debug)]
pub struct PeerTracker {
connected: Option<(PeerId, Multiaddr)>,
address_of_peer: HashMap<PeerId, Multiaddr>,
events: VecDeque<OutEvent>,
}
impl PeerTracker {
/// Return whether we are connected to the given peer.
pub fn is_connected(&self, peer_id: &PeerId) -> bool {
if let Some((connected_peer_id, _)) = &self.connected {
if connected_peer_id == peer_id {
return true;
}
}
false
}
/// Returns the peer id of counterparty if we are connected.
pub fn counterparty_peer_id(&self) -> Option<PeerId> {
if let Some((id, _)) = &self.connected {
@ -33,13 +47,18 @@ impl PeerTracker {
None
}
/// Returns the multiaddr of counterparty if we are connected.
pub fn counterparty_addr(&self) -> Option<Multiaddr> {
if let Some((_, addr)) = &self.connected {
return Some(addr.clone());
/// Returns the peer_id and multiaddr of counterparty if we are connected.
pub fn counterparty(&self) -> Option<(PeerId, Multiaddr)> {
if let Some((peer_id, addr)) = &self.connected {
return Some((peer_id.clone(), addr.clone()));
}
None
}
/// Add an address for a given peer. We only store one address per peer.
pub fn add_address(&mut self, peer_id: PeerId, address: Multiaddr) {
self.address_of_peer.insert(peer_id, address);
}
}
impl NetworkBehaviour for PeerTracker {
@ -50,11 +69,17 @@ impl NetworkBehaviour for PeerTracker {
DummyProtocolsHandler::default()
}
fn addresses_of_peer(&mut self, _: &PeerId) -> Vec<Multiaddr> {
fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
let mut addresses: Vec<Multiaddr> = vec![];
if let Some(addr) = self.counterparty_addr() {
addresses.push(addr)
if let Some((counterparty_peer_id, addr)) = self.counterparty() {
if counterparty_peer_id == *peer_id {
addresses.push(addr)
}
}
if let Some(addr) = self.address_of_peer.get(peer_id) {
addresses.push(addr.clone());
}
addresses

View file

@ -56,8 +56,6 @@ pub enum Bob {
},
EncSigSent {
state4: bob::State4,
#[serde(with = "crate::serde::peer_id")]
peer_id: PeerId,
},
BtcRedeemed(bob::State5),
T1Expired(bob::State4),