WIP: Refactor test setup to make it easier to write new tests

Alice setup has been refactored while Bob has not. Monerod/Cli
lifetime issues need to be resolved
This commit is contained in:
rishflab 2021-01-13 13:31:36 +11:00
parent 485220929e
commit 923ab85a86
15 changed files with 1513 additions and 1570 deletions

View file

@ -26,7 +26,12 @@ use swap::{
database::{Database, Swap}, database::{Database, Swap},
monero, network, monero, network,
network::transport::build, network::transport::build,
protocol::{alice, alice::AliceState, bob, bob::BobState}, protocol::{
alice,
alice::{swap::AliceActor, AliceState},
bob,
bob::BobState,
},
seed::Seed, seed::Seed,
trace::init_tracing, trace::init_tracing,
SwapAmounts, SwapAmounts,
@ -295,19 +300,20 @@ async fn alice_swap(
info!("Own Peer-ID: {}", alice_peer_id); info!("Own Peer-ID: {}", alice_peer_id);
let alice_transport = build(alice_behaviour.identity())?; let alice_transport = build(alice_behaviour.identity())?;
let (mut event_loop, handle) = let (mut event_loop, event_loop_handle) =
alice::event_loop::EventLoop::new(alice_transport, alice_behaviour, listen_addr)?; alice::event_loop::EventLoop::new(alice_transport, alice_behaviour, listen_addr)?;
let swap = alice::swap::swap( let alice_actor = AliceActor::new(
state, event_loop_handle,
handle, bitcoin_wallet,
bitcoin_wallet.clone(), monero_wallet,
monero_wallet.clone(), db,
config, config,
swap_id, swap_id,
db,
); );
let swap = alice_actor.swap(state);
tokio::spawn(async move { event_loop.run().await }); tokio::spawn(async move { event_loop.run().await });
swap.await swap.await
} }

View file

@ -19,7 +19,10 @@ use crate::{
SwapAmounts, SwapAmounts,
}; };
pub use self::{amounts::*, message0::Message0, message1::Message1, message2::Message2, state::*}; pub use self::{
amounts::*, event_loop::EventLoop, message0::Message0, message1::Message1, message2::Message2,
state::*,
};
mod amounts; mod amounts;
pub mod event_loop; pub mod event_loop;

View file

@ -344,3 +344,13 @@ where
Ok(txid) Ok(txid)
} }
pub async fn watch_for_tx_refund<W>(
tx_id: bitcoin::Txid,
bitcoin_wallet: Arc<W>,
) -> bitcoin::Transaction
where
W: WatchForRawTransaction,
{
bitcoin_wallet.watch_for_raw_transaction(tx_id).await
}

View file

@ -13,7 +13,7 @@ use uuid::Uuid;
use crate::{ use crate::{
bitcoin, bitcoin,
bitcoin::{TransactionBlockHeight, WatchForRawTransaction}, bitcoin::TransactionBlockHeight,
config::Config, config::Config,
database::{Database, Swap}, database::{Database, Swap},
monero, monero,
@ -25,6 +25,7 @@ use crate::{
extract_monero_private_key, lock_xmr, negotiate, publish_bitcoin_punish_transaction, extract_monero_private_key, lock_xmr, negotiate, publish_bitcoin_punish_transaction,
publish_bitcoin_redeem_transaction, publish_cancel_transaction, publish_bitcoin_redeem_transaction, publish_cancel_transaction,
wait_for_bitcoin_encrypted_signature, wait_for_bitcoin_refund, wait_for_locked_bitcoin, wait_for_bitcoin_encrypted_signature, wait_for_bitcoin_refund, wait_for_locked_bitcoin,
watch_for_tx_refund,
}, },
AliceState, AliceState,
}, },
@ -35,26 +36,341 @@ trait Rng: RngCore + CryptoRng + Send {}
impl<T> Rng for T where T: RngCore + CryptoRng + Send {} impl<T> Rng for T where T: RngCore + CryptoRng + Send {}
pub async fn swap( pub struct AliceActor {
state: AliceState,
event_loop_handle: EventLoopHandle, event_loop_handle: EventLoopHandle,
bitcoin_wallet: Arc<bitcoin::Wallet>, bitcoin_wallet: Arc<bitcoin::Wallet>,
monero_wallet: Arc<monero::Wallet>, monero_wallet: Arc<monero::Wallet>,
db: Database,
config: Config, config: Config,
swap_id: Uuid, swap_id: Uuid,
}
impl AliceActor {
pub fn new(
event_loop_handle: EventLoopHandle,
bitcoin_wallet: Arc<bitcoin::Wallet>,
monero_wallet: Arc<monero::Wallet>,
db: Database, db: Database,
) -> Result<AliceState> { config: Config,
run_until( swap_id: Uuid,
state, ) -> Self {
is_complete, Self {
event_loop_handle, event_loop_handle,
bitcoin_wallet, bitcoin_wallet,
monero_wallet, monero_wallet,
db,
config, config,
swap_id, swap_id,
db, }
}
pub async fn swap(self, start_state: AliceState) -> Result<AliceState> {
self.run_until(start_state, is_complete).await
}
// State machine driver for swap execution
#[async_recursion]
pub async fn run_until(
mut self,
start_state: AliceState,
is_target_state: fn(&AliceState) -> bool,
) -> Result<AliceState> {
info!("Current state:{}", start_state);
if is_target_state(&start_state) {
Ok(start_state)
} else {
match start_state {
AliceState::Started { amounts, state0 } => {
let (channel, state3) =
negotiate(state0, amounts, &mut self.event_loop_handle, self.config)
.await?;
let state = AliceState::Negotiated {
channel: Some(channel),
amounts,
state3: Box::new(state3),
};
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
AliceState::Negotiated {
state3,
channel,
amounts,
} => {
let state = match channel {
Some(channel) => {
let _ = wait_for_locked_bitcoin(
state3.tx_lock.txid(),
self.bitcoin_wallet.clone(),
self.config,
) )
.await .await?;
AliceState::BtcLocked {
channel: Some(channel),
amounts,
state3,
}
}
None => {
tracing::info!("Cannot resume swap from negotiated state, aborting");
// Alice did not lock Xmr yet
AliceState::SafelyAborted
}
};
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
AliceState::BtcLocked {
channel,
amounts,
state3,
} => {
let state = match channel {
Some(channel) => {
lock_xmr(
channel,
amounts,
*state3.clone(),
&mut self.event_loop_handle,
self.monero_wallet.clone(),
)
.await?;
AliceState::XmrLocked { state3 }
}
None => {
tracing::info!("Cannot resume swap from BTC locked state, aborting");
// Alice did not lock Xmr yet
AliceState::SafelyAborted
}
};
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
AliceState::XmrLocked { state3 } => {
// todo: match statement and wait for cancel timelock to expire can probably be
// expressed more cleanly
let state = match state3
.expired_timelocks(self.bitcoin_wallet.as_ref())
.await?
{
ExpiredTimelocks::None => {
let wait_for_enc_sig = wait_for_bitcoin_encrypted_signature(
&mut self.event_loop_handle,
self.config.monero_max_finality_time,
);
let state3_clone = state3.clone();
let cancel_timelock_expires = state3_clone
.wait_for_cancel_timelock_to_expire(self.bitcoin_wallet.as_ref());
pin_mut!(wait_for_enc_sig);
pin_mut!(cancel_timelock_expires);
match select(cancel_timelock_expires, wait_for_enc_sig).await {
Either::Left(_) => AliceState::CancelTimelockExpired { state3 },
Either::Right((enc_sig, _)) => AliceState::EncSigLearned {
state3,
encrypted_signature: enc_sig?,
},
}
}
_ => AliceState::CancelTimelockExpired { state3 },
};
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
AliceState::EncSigLearned {
state3,
encrypted_signature,
} => {
// TODO: Evaluate if it is correct for Alice to Redeem no matter what.
// If cancel timelock expired she should potentially not try redeem. (The
// implementation gives her an advantage.)
let signed_tx_redeem = match build_bitcoin_redeem_transaction(
encrypted_signature,
&state3.tx_lock,
state3.a.clone(),
state3.s_a,
state3.B,
&state3.redeem_address,
) {
Ok(tx) => tx,
Err(_) => {
state3
.wait_for_cancel_timelock_to_expire(self.bitcoin_wallet.as_ref())
.await?;
let state = AliceState::CancelTimelockExpired { state3 };
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
return self.run_until(state, is_target_state).await;
}
};
// TODO(Franck): Error handling is delicate here.
// If Bob sees this transaction he can redeem Monero
// e.g. If the Bitcoin node is down then the user needs to take action.
publish_bitcoin_redeem_transaction(
signed_tx_redeem,
self.bitcoin_wallet.clone(),
self.config,
)
.await?;
let state = AliceState::BtcRedeemed;
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
AliceState::CancelTimelockExpired { state3 } => {
let tx_cancel = publish_cancel_transaction(
state3.tx_lock.clone(),
state3.a.clone(),
state3.B,
state3.cancel_timelock,
state3.tx_cancel_sig_bob.clone(),
self.bitcoin_wallet.clone(),
)
.await?;
let state = AliceState::BtcCancelled { state3, tx_cancel };
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
AliceState::BtcCancelled { state3, tx_cancel } => {
let tx_cancel_height = self
.bitcoin_wallet
.transaction_block_height(tx_cancel.txid())
.await;
let (tx_refund, published_refund_tx) = wait_for_bitcoin_refund(
&tx_cancel,
tx_cancel_height,
state3.punish_timelock,
&state3.refund_address,
self.bitcoin_wallet.clone(),
)
.await?;
// TODO(Franck): Review error handling
match published_refund_tx {
None => {
let state = AliceState::BtcPunishable { tx_refund, state3 };
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.swap(state).await
}
Some(published_refund_tx) => {
let spend_key = extract_monero_private_key(
published_refund_tx,
tx_refund,
state3.s_a,
state3.a.clone(),
state3.S_b_bitcoin,
)?;
let state = AliceState::BtcRefunded { spend_key, state3 };
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
}
}
AliceState::BtcRefunded { spend_key, state3 } => {
let view_key = state3.v;
self.monero_wallet
.create_and_load_wallet_for_output(spend_key, view_key)
.await?;
let state = AliceState::XmrRefunded;
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
Ok(state)
}
AliceState::BtcPunishable { tx_refund, state3 } => {
let signed_tx_punish = build_bitcoin_punish_transaction(
&state3.tx_lock,
state3.cancel_timelock,
&state3.punish_address,
state3.punish_timelock,
state3.tx_punish_sig_bob.clone(),
state3.a.clone(),
state3.B,
)?;
let punish_tx_finalised = publish_bitcoin_punish_transaction(
signed_tx_punish,
self.bitcoin_wallet.clone(),
self.config,
);
let refund_tx_seen =
watch_for_tx_refund(tx_refund.txid(), self.bitcoin_wallet.clone());
pin_mut!(punish_tx_finalised);
pin_mut!(refund_tx_seen);
let state = match select(punish_tx_finalised, refund_tx_seen).await {
Either::Left(_) => AliceState::BtcPunished,
Either::Right((published_refund_tx, _)) => {
let spend_key = extract_monero_private_key(
published_refund_tx,
tx_refund,
state3.s_a,
state3.a.clone(),
state3.S_b_bitcoin,
)?;
AliceState::BtcRefunded { spend_key, state3 }
}
};
let db_state = (&state).into();
self.db
.insert_latest_state(self.swap_id, Swap::Alice(db_state))
.await?;
self.run_until(state, is_target_state).await
}
AliceState::XmrRefunded => Ok(AliceState::XmrRefunded),
AliceState::BtcRedeemed => Ok(AliceState::BtcRedeemed),
AliceState::BtcPunished => Ok(AliceState::BtcPunished),
AliceState::SafelyAborted => Ok(AliceState::SafelyAborted),
}
}
}
} }
pub fn is_complete(state: &AliceState) -> bool { pub fn is_complete(state: &AliceState) -> bool {
@ -80,412 +396,3 @@ pub fn is_encsig_learned(state: &AliceState) -> bool {
AliceState::EncSigLearned{..} AliceState::EncSigLearned{..}
) )
} }
// State machine driver for swap execution
#[async_recursion]
#[allow(clippy::too_many_arguments)]
pub async fn run_until(
state: AliceState,
is_target_state: fn(&AliceState) -> bool,
mut event_loop_handle: EventLoopHandle,
bitcoin_wallet: Arc<crate::bitcoin::Wallet>,
monero_wallet: Arc<crate::monero::Wallet>,
config: Config,
swap_id: Uuid,
db: Database,
// TODO: Remove EventLoopHandle!
) -> Result<AliceState> {
info!("Current state:{}", state);
if is_target_state(&state) {
Ok(state)
} else {
match state {
AliceState::Started { amounts, state0 } => {
let (channel, state3) =
negotiate(state0, amounts, &mut event_loop_handle, config).await?;
let state = AliceState::Negotiated {
channel: Some(channel),
amounts,
state3: Box::new(state3),
};
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet,
monero_wallet,
config,
swap_id,
db,
)
.await
}
AliceState::Negotiated {
state3,
channel,
amounts,
} => {
let state = match channel {
Some(channel) => {
let _ = wait_for_locked_bitcoin(
state3.tx_lock.txid(),
bitcoin_wallet.clone(),
config,
)
.await?;
AliceState::BtcLocked {
channel: Some(channel),
amounts,
state3,
}
}
None => {
tracing::info!("Cannot resume swap from negotiated state, aborting");
// Alice did not lock Xmr yet
AliceState::SafelyAborted
}
};
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet,
monero_wallet,
config,
swap_id,
db,
)
.await
}
AliceState::BtcLocked {
channel,
amounts,
state3,
} => {
let state = match channel {
Some(channel) => {
lock_xmr(
channel,
amounts,
*state3.clone(),
&mut event_loop_handle,
monero_wallet.clone(),
)
.await?;
AliceState::XmrLocked { state3 }
}
None => {
tracing::info!("Cannot resume swap from BTC locked state, aborting");
// Alice did not lock Xmr yet
AliceState::SafelyAborted
}
};
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet,
monero_wallet,
config,
swap_id,
db,
)
.await
}
AliceState::XmrLocked { state3 } => {
// todo: match statement and wait for cancel timelock to expire can probably be
// expressed more cleanly
let state = match state3.expired_timelocks(bitcoin_wallet.as_ref()).await? {
ExpiredTimelocks::None => {
let wait_for_enc_sig = wait_for_bitcoin_encrypted_signature(
&mut event_loop_handle,
config.monero_max_finality_time,
);
let state3_clone = state3.clone();
let cancel_timelock_expires = state3_clone
.wait_for_cancel_timelock_to_expire(bitcoin_wallet.as_ref());
pin_mut!(wait_for_enc_sig);
pin_mut!(cancel_timelock_expires);
match select(cancel_timelock_expires, wait_for_enc_sig).await {
Either::Left(_) => AliceState::CancelTimelockExpired { state3 },
Either::Right((enc_sig, _)) => AliceState::EncSigLearned {
state3,
encrypted_signature: enc_sig?,
},
}
}
_ => AliceState::CancelTimelockExpired { state3 },
};
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet.clone(),
monero_wallet,
config,
swap_id,
db,
)
.await
}
AliceState::EncSigLearned {
state3,
encrypted_signature,
} => {
// TODO: Evaluate if it is correct for Alice to Redeem no matter what.
// If cancel timelock expired she should potentially not try redeem. (The
// implementation gives her an advantage.)
let signed_tx_redeem = match build_bitcoin_redeem_transaction(
encrypted_signature,
&state3.tx_lock,
state3.a.clone(),
state3.s_a,
state3.B,
&state3.redeem_address,
) {
Ok(tx) => tx,
Err(_) => {
state3
.wait_for_cancel_timelock_to_expire(bitcoin_wallet.as_ref())
.await?;
let state = AliceState::CancelTimelockExpired { state3 };
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
return run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet,
monero_wallet,
config,
swap_id,
db,
)
.await;
}
};
// TODO(Franck): Error handling is delicate here.
// If Bob sees this transaction he can redeem Monero
// e.g. If the Bitcoin node is down then the user needs to take action.
publish_bitcoin_redeem_transaction(
signed_tx_redeem,
bitcoin_wallet.clone(),
config,
)
.await?;
let state = AliceState::BtcRedeemed;
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet,
monero_wallet,
config,
swap_id,
db,
)
.await
}
AliceState::CancelTimelockExpired { state3 } => {
let tx_cancel = publish_cancel_transaction(
state3.tx_lock.clone(),
state3.a.clone(),
state3.B,
state3.cancel_timelock,
state3.tx_cancel_sig_bob.clone(),
bitcoin_wallet.clone(),
)
.await?;
let state = AliceState::BtcCancelled { state3, tx_cancel };
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet,
monero_wallet,
config,
swap_id,
db,
)
.await
}
AliceState::BtcCancelled { state3, tx_cancel } => {
let tx_cancel_height = bitcoin_wallet
.transaction_block_height(tx_cancel.txid())
.await;
let (tx_refund, published_refund_tx) = wait_for_bitcoin_refund(
&tx_cancel,
tx_cancel_height,
state3.punish_timelock,
&state3.refund_address,
bitcoin_wallet.clone(),
)
.await?;
// TODO(Franck): Review error handling
match published_refund_tx {
None => {
let state = AliceState::BtcPunishable { tx_refund, state3 };
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
swap(
state,
event_loop_handle,
bitcoin_wallet.clone(),
monero_wallet,
config,
swap_id,
db,
)
.await
}
Some(published_refund_tx) => {
let spend_key = extract_monero_private_key(
published_refund_tx,
tx_refund,
state3.s_a,
state3.a.clone(),
state3.S_b_bitcoin,
)?;
let state = AliceState::BtcRefunded { spend_key, state3 };
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet.clone(),
monero_wallet,
config,
swap_id,
db,
)
.await
}
}
}
AliceState::BtcRefunded { spend_key, state3 } => {
let view_key = state3.v;
monero_wallet
.create_and_load_wallet_for_output(spend_key, view_key)
.await?;
let state = AliceState::XmrRefunded;
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
Ok(state)
}
AliceState::BtcPunishable { tx_refund, state3 } => {
let signed_tx_punish = build_bitcoin_punish_transaction(
&state3.tx_lock,
state3.cancel_timelock,
&state3.punish_address,
state3.punish_timelock,
state3.tx_punish_sig_bob.clone(),
state3.a.clone(),
state3.B,
)?;
let punish_tx_finalised = publish_bitcoin_punish_transaction(
signed_tx_punish,
bitcoin_wallet.clone(),
config,
);
let refund_tx_seen = bitcoin_wallet.watch_for_raw_transaction(tx_refund.txid());
pin_mut!(punish_tx_finalised);
pin_mut!(refund_tx_seen);
match select(punish_tx_finalised, refund_tx_seen).await {
Either::Left(_) => {
let state = AliceState::BtcPunished;
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet.clone(),
monero_wallet,
config,
swap_id,
db,
)
.await
}
Either::Right((published_refund_tx, _)) => {
let spend_key = extract_monero_private_key(
published_refund_tx,
tx_refund,
state3.s_a,
state3.a.clone(),
state3.S_b_bitcoin,
)?;
let state = AliceState::BtcRefunded { spend_key, state3 };
let db_state = (&state).into();
db.insert_latest_state(swap_id, Swap::Alice(db_state))
.await?;
run_until(
state,
is_target_state,
event_loop_handle,
bitcoin_wallet.clone(),
monero_wallet,
config,
swap_id,
db,
)
.await
}
}
}
AliceState::XmrRefunded => Ok(AliceState::XmrRefunded),
AliceState::BtcRedeemed => Ok(AliceState::BtcRedeemed),
AliceState::BtcPunished => Ok(AliceState::BtcPunished),
AliceState::SafelyAborted => Ok(AliceState::SafelyAborted),
}
}
}

View file

@ -19,8 +19,8 @@ use crate::{
}; };
pub use self::{ pub use self::{
amounts::*, message0::Message0, message1::Message1, message2::Message2, message3::Message3, amounts::*, event_loop::EventLoop, message0::Message0, message1::Message1, message2::Message2,
state::*, message3::Message3, state::*,
}; };
mod amounts; mod amounts;

View file

@ -7,7 +7,9 @@ use tracing::info;
use uuid::Uuid; use uuid::Uuid;
use crate::{ use crate::{
bitcoin,
database::{Database, Swap}, database::{Database, Swap},
monero,
protocol::bob::{self, event_loop::EventLoopHandle, state::*}, protocol::bob::{self, event_loop::EventLoopHandle, state::*},
ExpiredTimelocks, SwapAmounts, ExpiredTimelocks, SwapAmounts,
}; };
@ -18,8 +20,8 @@ pub async fn swap<R>(
state: BobState, state: BobState,
event_loop_handle: EventLoopHandle, event_loop_handle: EventLoopHandle,
db: Database, db: Database,
bitcoin_wallet: Arc<crate::bitcoin::Wallet>, bitcoin_wallet: Arc<bitcoin::Wallet>,
monero_wallet: Arc<crate::monero::Wallet>, monero_wallet: Arc<monero::Wallet>,
rng: R, rng: R,
swap_id: Uuid, swap_id: Uuid,
) -> Result<BobState> ) -> Result<BobState>

View file

@ -1,21 +1,6 @@
use crate::testutils::{init_alice, init_bob}; use crate::testutils::Test;
use futures::{ use swap::{bitcoin, monero};
future::{join, select}, use tokio::join;
FutureExt,
};
use get_port::get_port;
use libp2p::Multiaddr;
use rand::rngs::OsRng;
use swap::{
bitcoin,
config::Config,
monero,
protocol::{alice, bob},
seed::Seed,
};
use testcontainers::clients::Cli;
use testutils::init_tracing;
use uuid::Uuid;
pub mod testutils; pub mod testutils;
@ -23,108 +8,14 @@ pub mod testutils;
#[tokio::test] #[tokio::test]
async fn happy_path() { async fn happy_path() {
let _guard = init_tracing(); let mut test = Test::new(
bitcoin::Amount::from_sat(1_000_000),
let cli = Cli::default(); monero::Amount::from_piconero(1_000_000_000_000),
let (
monero,
testutils::Containers {
bitcoind,
monerods: _monerods,
},
) = testutils::init_containers(&cli).await;
let btc_to_swap = bitcoin::Amount::from_sat(1_000_000);
let btc_alice = bitcoin::Amount::ZERO;
let btc_bob = btc_to_swap * 10;
// this xmr value matches the logic of alice::calculate_amounts i.e. btc *
// 10_000 * 100
let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000);
let xmr_alice = xmr_to_swap * 10;
let xmr_bob = monero::Amount::ZERO;
let port = get_port().expect("Failed to find a free port");
let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port)
.parse()
.expect("failed to parse Alice's address");
let config = Config::regtest();
let (
alice_state,
mut alice_event_loop,
alice_event_loop_handle,
alice_btc_wallet,
alice_xmr_wallet,
alice_db,
) = init_alice(
&bitcoind,
&monero,
btc_to_swap,
xmr_to_swap,
xmr_alice,
alice_multiaddr.clone(),
config,
Seed::random().unwrap(),
) )
.await; .await;
let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet, bob_xmr_wallet, bob_db) = join!(test.alice.swap(), test.bob.swap());
init_bob(
alice_multiaddr.clone(),
alice_event_loop.peer_id(),
&bitcoind,
&monero,
btc_to_swap,
btc_bob,
xmr_to_swap,
config,
)
.await;
let alice_swap_fut = alice::swap::swap( test.alice.assert_btc_redeemed();
alice_state, test.bob.assert_btc_redeemed();
alice_event_loop_handle,
alice_btc_wallet.clone(),
alice_xmr_wallet.clone(),
config,
Uuid::new_v4(),
alice_db,
)
.boxed();
let alice_fut = select(alice_swap_fut, alice_event_loop.run().boxed());
let bob_swap_fut = bob::swap::swap(
bob_state,
bob_event_loop_handle,
bob_db,
bob_btc_wallet.clone(),
bob_xmr_wallet.clone(),
OsRng,
Uuid::new_v4(),
)
.boxed();
let bob_fut = select(bob_swap_fut, bob_event_loop.run().boxed());
join(alice_fut, bob_fut).await;
let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap();
let btc_bob_final = bob_btc_wallet.as_ref().balance().await.unwrap();
let xmr_alice_final = alice_xmr_wallet.as_ref().get_balance().await.unwrap();
bob_xmr_wallet.as_ref().inner.refresh().await.unwrap();
let xmr_bob_final = bob_xmr_wallet.as_ref().get_balance().await.unwrap();
assert_eq!(
btc_alice_final,
btc_alice + btc_to_swap - bitcoin::Amount::from_sat(bitcoin::TX_FEE)
);
assert!(btc_bob_final <= btc_bob - btc_to_swap);
assert!(xmr_alice_final <= xmr_alice - xmr_to_swap);
assert_eq!(xmr_bob_final, xmr_bob + xmr_to_swap);
} }

View file

@ -1,166 +1,170 @@
use crate::testutils::{init_alice, init_bob}; // use crate::testutils::{init_alice, init_bob};
use get_port::get_port; // use get_port::get_port;
use libp2p::Multiaddr; // use libp2p::Multiaddr;
use rand::rngs::OsRng; // use rand::rngs::OsRng;
use swap::{ // use swap::{
bitcoin, // bitcoin,
config::Config, // config::Config,
database::Database, // database::Database,
monero, // monero,
protocol::{alice, alice::AliceState, bob}, // protocol::{alice, alice::AliceState, bob},
seed::Seed, // seed::Seed,
}; // };
use tempfile::tempdir; // use tempfile::tempdir;
use testcontainers::clients::Cli; // use testcontainers::clients::Cli;
use testutils::init_tracing; // use testutils::init_tracing;
use uuid::Uuid; // use uuid::Uuid;
//
pub mod testutils; // pub mod testutils;
//
#[tokio::test] // #[tokio::test]
async fn given_alice_restarts_after_encsig_is_learned_resume_swap() { // async fn given_alice_restarts_after_encsig_is_learned_resume_swap() {
let _guard = init_tracing(); // let _guard = init_tracing();
//
let cli = Cli::default(); // let cli = Cli::default();
let ( // let (
monero, // monero,
testutils::Containers { // testutils::Containers {
bitcoind, // bitcoind,
monerods: _monerods, // monerods: _monerods,
}, // },
) = testutils::init_containers(&cli).await; // ) = testutils::init_containers(&cli).await;
//
let btc_to_swap = bitcoin::Amount::from_sat(1_000_000); // let btc_to_swap = bitcoin::Amount::from_sat(1_000_000);
let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000); // let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000);
//
let bob_btc_starting_balance = btc_to_swap * 10; // let bob_btc_starting_balance = btc_to_swap * 10;
let alice_xmr_starting_balance = xmr_to_swap * 10; // let alice_xmr_starting_balance = xmr_to_swap * 10;
//
let port = get_port().expect("Failed to find a free port"); // let port = get_port().expect("Failed to find a free port");
let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port) // let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port)
.parse() // .parse()
.expect("failed to parse Alice's address"); // .expect("failed to parse Alice's address");
//
let config = Config::regtest(); // let config = Config::regtest();
//
let alice_seed = Seed::random().unwrap(); // let alice_seed = Seed::random().unwrap();
let ( // let (
start_state, // start_state,
mut alice_event_loop, // mut alice_event_loop,
alice_event_loop_handle, // alice_event_loop_handle,
alice_btc_wallet, // alice_btc_wallet,
alice_xmr_wallet, // alice_xmr_wallet,
_, // _,
) = init_alice( // ) = init_alice(
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
xmr_to_swap, // xmr_to_swap,
alice_xmr_starting_balance, // alice_xmr_starting_balance,
alice_multiaddr.clone(), // alice_multiaddr.clone(),
config, // config,
alice_seed, // alice_seed,
) // )
.await; // .await;
//
let alice_peer_id = alice_event_loop.peer_id(); // let alice_peer_id = alice_event_loop.peer_id();
//
let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet, bob_xmr_wallet, bob_db) = // let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet,
init_bob( // bob_xmr_wallet, bob_db) = init_bob(
alice_multiaddr.clone(), // alice_multiaddr.clone(),
alice_peer_id.clone(), // alice_peer_id.clone(),
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
bob_btc_starting_balance, // bob_btc_starting_balance,
xmr_to_swap, // xmr_to_swap,
config, // config,
) // )
.await; // .await;
//
// TODO: we are making a clone of Bob's wallets here to keep them in scope after // // TODO: we are making a clone of Bob's wallets here to keep them in
// Bob's wallets are moved into an async task. // scope after // Bob's wallets are moved into an async task.
let bob_btc_wallet_clone = bob_btc_wallet.clone(); // let bob_btc_wallet_clone = bob_btc_wallet.clone();
let bob_xmr_wallet_clone = bob_xmr_wallet.clone(); // let bob_xmr_wallet_clone = bob_xmr_wallet.clone();
//
let bob_fut = bob::swap::swap( // let bob_fut = bob::swap::swap(
bob_state, // bob_state,
bob_event_loop_handle, // bob_event_loop_handle,
bob_db, // bob_db,
bob_btc_wallet.clone(), // bob_btc_wallet.clone(),
bob_xmr_wallet.clone(), // bob_xmr_wallet.clone(),
OsRng, // OsRng,
Uuid::new_v4(), // Uuid::new_v4(),
); // );
//
let alice_db_datadir = tempdir().unwrap(); // let alice_db_datadir = tempdir().unwrap();
let alice_db = Database::open(alice_db_datadir.path()).unwrap(); // let alice_db = Database::open(alice_db_datadir.path()).unwrap();
//
tokio::spawn(async move { alice_event_loop.run().await }); // tokio::spawn(async move { alice_event_loop.run().await });
let bob_swap_handle = tokio::spawn(bob_fut); // let bob_swap_handle = tokio::spawn(bob_fut);
tokio::spawn(bob_event_loop.run()); // tokio::spawn(bob_event_loop.run());
//
let alice_swap_id = Uuid::new_v4(); // let alice_swap_id = Uuid::new_v4();
//
let alice_state = alice::swap::run_until( // let alice_state = alice::swap::run_until(
start_state, // start_state,
alice::swap::is_encsig_learned, // alice::swap::is_encsig_learned,
alice_event_loop_handle, // alice_event_loop_handle,
alice_btc_wallet.clone(), // alice_btc_wallet.clone(),
alice_xmr_wallet.clone(), // alice_xmr_wallet.clone(),
config, // config,
alice_swap_id, // alice_swap_id,
alice_db, // alice_db,
) // )
.await // .await
.unwrap(); // .unwrap();
//
assert!(matches!(alice_state, AliceState::EncSigLearned {..})); // assert!(matches!(alice_state, AliceState::EncSigLearned {..}));
//
let alice_db = Database::open(alice_db_datadir.path()).unwrap(); // let alice_db = Database::open(alice_db_datadir.path()).unwrap();
//
let resume_state = // let resume_state =
if let swap::database::Swap::Alice(state) = alice_db.get_state(alice_swap_id).unwrap() { // if let swap::database::Swap::Alice(state) =
assert!(matches!(state, swap::database::Alice::EncSigLearned {..})); // alice_db.get_state(alice_swap_id).unwrap() {
state.into() // assert!(matches!(state, swap::database::Alice::EncSigLearned {..}));
} else { // state.into()
unreachable!() // } else {
}; // unreachable!()
// };
let (mut event_loop_after_restart, event_loop_handle_after_restart) = //
testutils::init_alice_event_loop(alice_multiaddr, alice_seed); // let (mut event_loop_after_restart, event_loop_handle_after_restart) =
tokio::spawn(async move { event_loop_after_restart.run().await }); // testutils::init_alice_event_loop(alice_multiaddr, alice_seed);
// tokio::spawn(async move { event_loop_after_restart.run().await });
let alice_state = alice::swap::swap( //
resume_state, // let alice_state = alice::swap::swap(
event_loop_handle_after_restart, // resume_state,
alice_btc_wallet.clone(), // event_loop_handle_after_restart,
alice_xmr_wallet.clone(), // alice_btc_wallet.clone(),
config, // alice_xmr_wallet.clone(),
alice_swap_id, // config,
alice_db, // alice_swap_id,
) // alice_db,
.await // )
.unwrap(); // .await
// .unwrap();
// Wait for Bob to finish //
bob_swap_handle.await.unwrap().unwrap(); // // Wait for Bob to finish
// bob_swap_handle.await.unwrap().unwrap();
assert!(matches!(alice_state, AliceState::BtcRedeemed {..})); //
// assert!(matches!(alice_state, AliceState::BtcRedeemed {..}));
let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap(); //
let btc_bob_final = bob_btc_wallet_clone.as_ref().balance().await.unwrap(); // let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap();
// let btc_bob_final =
assert_eq!( // bob_btc_wallet_clone.as_ref().balance().await.unwrap();
btc_alice_final, //
btc_to_swap - bitcoin::Amount::from_sat(bitcoin::TX_FEE) // assert_eq!(
); // btc_alice_final,
assert!(btc_bob_final <= bob_btc_starting_balance - btc_to_swap); // btc_to_swap - bitcoin::Amount::from_sat(bitcoin::TX_FEE)
// );
let xmr_alice_final = alice_xmr_wallet.as_ref().get_balance().await.unwrap(); // assert!(btc_bob_final <= bob_btc_starting_balance - btc_to_swap);
bob_xmr_wallet_clone.as_ref().inner.refresh().await.unwrap(); //
let xmr_bob_final = bob_xmr_wallet_clone.as_ref().get_balance().await.unwrap(); // let xmr_alice_final =
// alice_xmr_wallet.as_ref().get_balance().await.unwrap();
assert!(xmr_alice_final <= alice_xmr_starting_balance - xmr_to_swap); // bob_xmr_wallet_clone.as_ref().inner.refresh().await.unwrap();
assert_eq!(xmr_bob_final, xmr_to_swap); // let xmr_bob_final =
} // bob_xmr_wallet_clone.as_ref().get_balance().await.unwrap();
//
// assert!(xmr_alice_final <= alice_xmr_starting_balance - xmr_to_swap);
// assert_eq!(xmr_bob_final, xmr_to_swap);
// }

View file

@ -1,168 +1,141 @@
use crate::testutils::{init_alice, init_bob}; // use crate::testutils::{init_alice, init_bob};
use get_port::get_port; // use get_port::get_port;
use libp2p::Multiaddr; // use libp2p::Multiaddr;
use rand::rngs::OsRng; // use rand::rngs::OsRng;
use swap::{ // use swap::{
bitcoin, // bitcoin,
config::Config, // config::Config,
database::Database, // database::Database,
monero, // monero,
protocol::{alice, bob, bob::BobState}, // protocol::{alice, bob, bob::BobState},
seed::Seed, // seed::Seed,
}; // };
use tempfile::tempdir; // use tempfile::tempdir;
use testcontainers::clients::Cli; // use testcontainers::clients::Cli;
use testutils::init_tracing; // use testutils::init_tracing;
use uuid::Uuid; // use uuid::Uuid;
//
pub mod testutils; // pub mod testutils;
//
#[tokio::test] // #[tokio::test]
async fn given_bob_restarts_after_encsig_is_sent_resume_swap() { // async fn given_bob_restarts_after_encsig_is_sent_resume_swap() {
let _guard = init_tracing(); // let _guard = init_tracing();
//
let cli = Cli::default(); // let (
let ( // alice_state,
monero, // mut alice_event_loop,
testutils::Containers { // alice_event_loop_handle,
bitcoind, // alice_btc_wallet,
monerods: _monerods, // alice_xmr_wallet,
}, // alice_db,
) = testutils::init_containers(&cli).await; // ) = init_alice(
// &bitcoind,
let btc_to_swap = bitcoin::Amount::from_sat(1_000_000); // &monero,
let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000); // btc_to_swap,
// xmr_to_swap,
let bob_btc_starting_balance = btc_to_swap * 10; // alice_xmr_starting_balance,
let alice_xmr_starting_balance = xmr_to_swap * 10; // alice_multiaddr.clone(),
// config,
let port = get_port().expect("Failed to find a free port"); // Seed::random().unwrap(),
let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port) // )
.parse() // .await;
.expect("failed to parse Alice's address"); //
// let alice_peer_id = alice_event_loop.peer_id();
let config = Config::regtest(); // let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet,
// bob_xmr_wallet, _) = init_bob(
let ( // alice_multiaddr.clone(),
alice_state, // alice_peer_id.clone(),
mut alice_event_loop, // &bitcoind,
alice_event_loop_handle, // &monero,
alice_btc_wallet, // btc_to_swap,
alice_xmr_wallet, // bob_btc_starting_balance,
alice_db, // xmr_to_swap,
) = init_alice( // config,
&bitcoind, // )
&monero, // .await;
btc_to_swap, //
xmr_to_swap, // let alice_swap_ = tokio::spawn(alice::swap::swap(
alice_xmr_starting_balance, // alice_state,
alice_multiaddr.clone(), // alice_event_loop_handle,
config, // alice_btc_wallet.clone(),
Seed::random().unwrap(), // alice_xmr_wallet.clone(),
) // config,
.await; // Uuid::new_v4(),
// alice_db,
let alice_peer_id = alice_event_loop.peer_id(); // ));
let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet, bob_xmr_wallet, _) = //
init_bob( // tokio::spawn(async move { alice_event_loop.run().await });
alice_multiaddr.clone(), //
alice_peer_id.clone(), // tokio::spawn(bob_event_loop.run());
&bitcoind, //
&monero, // let bob_swap_id = Uuid::new_v4();
btc_to_swap, // let bob_db_datadir = tempdir().unwrap();
bob_btc_starting_balance, // let bob_db = Database::open(bob_db_datadir.path()).unwrap();
xmr_to_swap, //
config, // let bob_state = bob::swap::run_until(
) // bob_state,
.await; // bob::swap::is_encsig_sent,
// bob_event_loop_handle,
// TODO: we are making a clone of Alices's wallets here to keep them in scope // bob_db,
// after Alices's wallets are moved into an async task. // bob_btc_wallet.clone(),
let alice_btc_wallet_clone = alice_btc_wallet.clone(); // bob_xmr_wallet.clone(),
let alice_xmr_wallet_clone = alice_xmr_wallet.clone(); // OsRng,
// bob_swap_id,
// TODO: we are making a clone of Bob's wallets here to keep them in scope after // )
// Bob's wallets are moved into an async task. // .await
let bob_btc_wallet_clone = bob_btc_wallet.clone(); // .unwrap();
let bob_xmr_wallet_clone = bob_xmr_wallet.clone(); //
// assert!(matches!(bob_state, BobState::EncSigSent {..}));
let alice_swap_handle = tokio::spawn(alice::swap::swap( //
alice_state, // let bob_db = Database::open(bob_db_datadir.path()).unwrap();
alice_event_loop_handle, //
alice_btc_wallet.clone(), // let resume_state =
alice_xmr_wallet.clone(), // if let swap::database::Swap::Bob(state) =
config, // bob_db.get_state(bob_swap_id).unwrap() { assert!(matches!(state,
Uuid::new_v4(), // swap::database::Bob::EncSigSent {..}));
alice_db, // state.into()
)); // } else {
// unreachable!()
tokio::spawn(async move { alice_event_loop.run().await }); // };
//
tokio::spawn(bob_event_loop.run()); // let (event_loop_after_restart, event_loop_handle_after_restart) =
// testutils::init_bob_event_loop(alice_peer_id, alice_multiaddr);
let bob_swap_id = Uuid::new_v4(); // tokio::spawn(event_loop_after_restart.run());
let bob_db_datadir = tempdir().unwrap(); //
let bob_db = Database::open(bob_db_datadir.path()).unwrap(); // let bob_state = bob::swap::swap(
// resume_state,
let bob_state = bob::swap::run_until( // event_loop_handle_after_restart,
bob_state, // bob_db,
bob::swap::is_encsig_sent, // bob_btc_wallet,
bob_event_loop_handle, // bob_xmr_wallet,
bob_db, // OsRng,
bob_btc_wallet.clone(), // bob_swap_id,
bob_xmr_wallet.clone(), // )
OsRng, // .await
bob_swap_id, // .unwrap();
) //
.await // // Wait for Alice to finish too
.unwrap(); // alice_swap_handle.await.unwrap().unwrap();
//
assert!(matches!(bob_state, BobState::EncSigSent {..})); // assert!(matches!(bob_state, BobState::XmrRedeemed {..}));
//
let bob_db = Database::open(bob_db_datadir.path()).unwrap(); // let btc_alice_final =
// alice_btc_wallet_clone.as_ref().balance().await.unwrap();
let resume_state = // let btc_bob_final =
if let swap::database::Swap::Bob(state) = bob_db.get_state(bob_swap_id).unwrap() { // bob_btc_wallet_clone.as_ref().balance().await.unwrap();
assert!(matches!(state, swap::database::Bob::EncSigSent {..})); //
state.into() // assert_eq!(
} else { // btc_alice_final,
unreachable!() // btc_to_swap - bitcoin::Amount::from_sat(bitcoin::TX_FEE)
}; // );
// assert!(btc_bob_final <= bob_btc_starting_balance - btc_to_swap);
let (event_loop_after_restart, event_loop_handle_after_restart) = //
testutils::init_bob_event_loop(alice_peer_id, alice_multiaddr); // let xmr_alice_final =
tokio::spawn(event_loop_after_restart.run()); // alice_xmr_wallet_clone.as_ref().get_balance().await.unwrap();
// bob_xmr_wallet_clone.as_ref().inner.refresh().await.unwrap();
let bob_state = bob::swap::swap( // let xmr_bob_final =
resume_state, // bob_xmr_wallet_clone.as_ref().get_balance().await.unwrap();
event_loop_handle_after_restart, //
bob_db, // assert!(xmr_alice_final <= alice_xmr_starting_balance - xmr_to_swap);
bob_btc_wallet, // assert_eq!(xmr_bob_final, xmr_to_swap);
bob_xmr_wallet, // }
OsRng,
bob_swap_id,
)
.await
.unwrap();
// Wait for Alice to finish too
alice_swap_handle.await.unwrap().unwrap();
assert!(matches!(bob_state, BobState::XmrRedeemed {..}));
let btc_alice_final = alice_btc_wallet_clone.as_ref().balance().await.unwrap();
let btc_bob_final = bob_btc_wallet_clone.as_ref().balance().await.unwrap();
assert_eq!(
btc_alice_final,
btc_to_swap - bitcoin::Amount::from_sat(bitcoin::TX_FEE)
);
assert!(btc_bob_final <= bob_btc_starting_balance - btc_to_swap);
let xmr_alice_final = alice_xmr_wallet_clone.as_ref().get_balance().await.unwrap();
bob_xmr_wallet_clone.as_ref().inner.refresh().await.unwrap();
let xmr_bob_final = bob_xmr_wallet_clone.as_ref().get_balance().await.unwrap();
assert!(xmr_alice_final <= alice_xmr_starting_balance - xmr_to_swap);
assert_eq!(xmr_bob_final, xmr_to_swap);
}

View file

@ -1,159 +1,160 @@
use crate::testutils::{init_alice, init_bob}; // use crate::testutils::{init_alice, init_bob};
use get_port::get_port; // use get_port::get_port;
use libp2p::Multiaddr; // use libp2p::Multiaddr;
use rand::rngs::OsRng; // use rand::rngs::OsRng;
use swap::{ // use swap::{
bitcoin, // bitcoin,
config::Config, // config::Config,
database::Database, // database::Database,
monero, // monero,
protocol::{alice, alice::AliceState, bob, bob::BobState}, // protocol::{alice, alice::AliceState, bob, bob::BobState},
seed::Seed, // seed::Seed,
}; // };
use tempfile::tempdir; // use tempfile::tempdir;
use testcontainers::clients::Cli; // use testcontainers::clients::Cli;
use testutils::init_tracing; // use testutils::init_tracing;
use tokio::select; // use tokio::select;
use uuid::Uuid; // use uuid::Uuid;
//
pub mod testutils; // pub mod testutils;
//
#[tokio::test] // #[tokio::test]
async fn given_bob_restarts_after_xmr_is_locked_resume_swap() { // async fn given_bob_restarts_after_xmr_is_locked_resume_swap() {
let _guard = init_tracing(); // let _guard = init_tracing();
//
let cli = Cli::default(); // let cli = Cli::default();
let ( // let (
monero, // monero,
testutils::Containers { // testutils::Containers {
bitcoind, // bitcoind,
monerods: _monerods, // monerods: _monerods,
}, // },
) = testutils::init_containers(&cli).await; // ) = testutils::init_containers(&cli).await;
//
let btc_to_swap = bitcoin::Amount::from_sat(1_000_000); // let btc_to_swap = bitcoin::Amount::from_sat(1_000_000);
let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000); // let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000);
//
let bob_btc_starting_balance = btc_to_swap * 10; // let bob_btc_starting_balance = btc_to_swap * 10;
let bob_xmr_starting_balance = monero::Amount::from_piconero(0); // let bob_xmr_starting_balance = monero::Amount::from_piconero(0);
//
let alice_btc_starting_balance = bitcoin::Amount::ZERO; // let alice_btc_starting_balance = bitcoin::Amount::ZERO;
let alice_xmr_starting_balance = xmr_to_swap * 10; // let alice_xmr_starting_balance = xmr_to_swap * 10;
//
let port = get_port().expect("Failed to find a free port"); // let port = get_port().expect("Failed to find a free port");
let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port) // let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port)
.parse() // .parse()
.expect("failed to parse Alice's address"); // .expect("failed to parse Alice's address");
//
let ( // let (
alice_state, // alice_state,
mut alice_event_loop, // mut alice_event_loop,
alice_event_loop_handle, // alice_event_loop_handle,
alice_btc_wallet, // alice_btc_wallet,
alice_xmr_wallet, // alice_xmr_wallet,
alice_db, // alice_db,
) = init_alice( // ) = init_alice(
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
xmr_to_swap, // xmr_to_swap,
alice_xmr_starting_balance, // alice_xmr_starting_balance,
alice_multiaddr.clone(), // alice_multiaddr.clone(),
Config::regtest(), // Config::regtest(),
Seed::random().unwrap(), // Seed::random().unwrap(),
) // )
.await; // .await;
//
let alice_peer_id = alice_event_loop.peer_id(); // let alice_peer_id = alice_event_loop.peer_id();
let (bob_state, bob_event_loop_1, bob_event_loop_handle_1, bob_btc_wallet, bob_xmr_wallet, _) = // let (bob_state, bob_event_loop_1, bob_event_loop_handle_1,
init_bob( // bob_btc_wallet, bob_xmr_wallet, _) = init_bob(
alice_multiaddr.clone(), // alice_multiaddr.clone(),
alice_peer_id.clone(), // alice_peer_id.clone(),
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
bob_btc_starting_balance, // bob_btc_starting_balance,
xmr_to_swap, // xmr_to_swap,
Config::regtest(), // Config::regtest(),
) // )
.await; // .await;
//
let alice_fut = alice::swap::swap( // let alice_fut = alice::swap::swap(
alice_state, // alice_state,
alice_event_loop_handle, // alice_event_loop_handle,
alice_btc_wallet.clone(), // alice_btc_wallet.clone(),
alice_xmr_wallet.clone(), // alice_xmr_wallet.clone(),
Config::regtest(), // Config::regtest(),
Uuid::new_v4(), // Uuid::new_v4(),
alice_db, // alice_db,
); // );
//
let bob_swap_id = Uuid::new_v4(); // let bob_swap_id = Uuid::new_v4();
let bob_db_datadir = tempdir().unwrap(); // let bob_db_datadir = tempdir().unwrap();
//
let bob_xmr_locked_fut = { // let bob_xmr_locked_fut = {
let bob_db = Database::open(bob_db_datadir.path()).unwrap(); // let bob_db = Database::open(bob_db_datadir.path()).unwrap();
bob::swap::run_until( // bob::swap::run_until(
bob_state, // bob_state,
bob::swap::is_xmr_locked, // bob::swap::is_xmr_locked,
bob_event_loop_handle_1, // bob_event_loop_handle_1,
bob_db, // bob_db,
bob_btc_wallet.clone(), // bob_btc_wallet.clone(),
bob_xmr_wallet.clone(), // bob_xmr_wallet.clone(),
OsRng, // OsRng,
bob_swap_id, // bob_swap_id,
) // )
}; // };
//
tokio::spawn(async move { alice_event_loop.run().await }); // tokio::spawn(async move { alice_event_loop.run().await });
//
let alice_fut_handle = tokio::spawn(alice_fut); // let alice_fut_handle = tokio::spawn(alice_fut);
//
// We are selecting with bob_event_loop_1 so that we stop polling on it once // // We are selecting with bob_event_loop_1 so that we stop polling on it
// bob reaches `xmr locked` state. // once // bob reaches `xmr locked` state.
let bob_restart_state = select! { // let bob_restart_state = select! {
res = bob_xmr_locked_fut => res.unwrap(), // res = bob_xmr_locked_fut => res.unwrap(),
_ = bob_event_loop_1.run() => panic!("The event loop should never finish") // _ = bob_event_loop_1.run() => panic!("The event loop should never
}; // finish") };
//
let (bob_event_loop_2, bob_event_loop_handle_2) = // let (bob_event_loop_2, bob_event_loop_handle_2) =
testutils::init_bob_event_loop(alice_peer_id, alice_multiaddr); // testutils::init_bob_event_loop(alice_peer_id, alice_multiaddr);
//
let bob_fut = bob::swap::swap( // let bob_fut = bob::swap::swap(
bob_restart_state, // bob_restart_state,
bob_event_loop_handle_2, // bob_event_loop_handle_2,
Database::open(bob_db_datadir.path()).unwrap(), // Database::open(bob_db_datadir.path()).unwrap(),
bob_btc_wallet.clone(), // bob_btc_wallet.clone(),
bob_xmr_wallet.clone(), // bob_xmr_wallet.clone(),
OsRng, // OsRng,
bob_swap_id, // bob_swap_id,
); // );
//
let bob_final_state = select! { // let bob_final_state = select! {
bob_final_state = bob_fut => bob_final_state.unwrap(), // bob_final_state = bob_fut => bob_final_state.unwrap(),
_ = bob_event_loop_2.run() => panic!("Event loop is not expected to stop") // _ = bob_event_loop_2.run() => panic!("Event loop is not expected to
}; // stop") };
//
assert!(matches!(bob_final_state, BobState::XmrRedeemed)); // assert!(matches!(bob_final_state, BobState::XmrRedeemed));
//
// Wait for Alice to finish too. // // Wait for Alice to finish too.
let alice_final_state = alice_fut_handle.await.unwrap().unwrap(); // let alice_final_state = alice_fut_handle.await.unwrap().unwrap();
assert!(matches!(alice_final_state, AliceState::BtcRedeemed)); // assert!(matches!(alice_final_state, AliceState::BtcRedeemed));
//
let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap(); // let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap();
let btc_bob_final = bob_btc_wallet.as_ref().balance().await.unwrap(); // let btc_bob_final = bob_btc_wallet.as_ref().balance().await.unwrap();
//
let xmr_alice_final = alice_xmr_wallet.as_ref().get_balance().await.unwrap(); // let xmr_alice_final =
// alice_xmr_wallet.as_ref().get_balance().await.unwrap();
bob_xmr_wallet.as_ref().inner.refresh().await.unwrap(); //
let xmr_bob_final = bob_xmr_wallet.as_ref().get_balance().await.unwrap(); // bob_xmr_wallet.as_ref().inner.refresh().await.unwrap();
// let xmr_bob_final = bob_xmr_wallet.as_ref().get_balance().await.unwrap();
assert_eq!( //
btc_alice_final, // assert_eq!(
alice_btc_starting_balance + btc_to_swap - bitcoin::Amount::from_sat(bitcoin::TX_FEE) // btc_alice_final,
); // alice_btc_starting_balance + btc_to_swap -
assert!(btc_bob_final <= bob_btc_starting_balance - btc_to_swap); // bitcoin::Amount::from_sat(bitcoin::TX_FEE) );
// assert!(btc_bob_final <= bob_btc_starting_balance - btc_to_swap);
assert!(xmr_alice_final <= alice_xmr_starting_balance - xmr_to_swap); //
assert_eq!(xmr_bob_final, bob_xmr_starting_balance + xmr_to_swap); // assert!(xmr_alice_final <= alice_xmr_starting_balance - xmr_to_swap);
} // assert_eq!(xmr_bob_final, bob_xmr_starting_balance + xmr_to_swap);
// }

View file

@ -1,150 +1,150 @@
use crate::testutils::{init_alice, init_bob}; // use crate::testutils::{init_alice, init_bob};
use futures::{ // use futures::{
future::{join, select, Either}, // future::{join, select, Either},
FutureExt, // FutureExt,
}; // };
use get_port::get_port; // use get_port::get_port;
use libp2p::Multiaddr; // use libp2p::Multiaddr;
use rand::rngs::OsRng; // use rand::rngs::OsRng;
use swap::{ // use swap::{
bitcoin, // bitcoin,
config::Config, // config::Config,
monero, // monero,
protocol::{alice, alice::AliceState, bob, bob::BobState}, // protocol::{alice, alice::AliceState, bob, bob::BobState},
seed::Seed, // seed::Seed,
}; // };
use testcontainers::clients::Cli; // use testcontainers::clients::Cli;
use testutils::init_tracing; // use testutils::init_tracing;
use uuid::Uuid; // use uuid::Uuid;
//
pub mod testutils; // pub mod testutils;
//
/// Bob locks Btc and Alice locks Xmr. Bob does not act; he fails to send Alice // /// Bob locks Btc and Alice locks Xmr. Bob does not act; he fails to send
/// the encsig and fail to refund or redeem. Alice punishes. // Alice /// the encsig and fail to refund or redeem. Alice punishes.
#[tokio::test] // #[tokio::test]
async fn alice_punishes_if_bob_never_acts_after_fund() { // async fn alice_punishes_if_bob_never_acts_after_fund() {
let _guard = init_tracing(); // let _guard = init_tracing();
//
let cli = Cli::default(); // let cli = Cli::default();
let ( // let (
monero, // monero,
testutils::Containers { // testutils::Containers {
bitcoind, // bitcoind,
monerods: _monerods, // monerods: _monerods,
}, // },
) = testutils::init_containers(&cli).await; // ) = testutils::init_containers(&cli).await;
//
let btc_to_swap = bitcoin::Amount::from_sat(1_000_000); // let btc_to_swap = bitcoin::Amount::from_sat(1_000_000);
let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000); // let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000);
//
let bob_btc_starting_balance = btc_to_swap * 10; // let bob_btc_starting_balance = btc_to_swap * 10;
//
let alice_btc_starting_balance = bitcoin::Amount::ZERO; // let alice_btc_starting_balance = bitcoin::Amount::ZERO;
let alice_xmr_starting_balance = xmr_to_swap * 10; // let alice_xmr_starting_balance = xmr_to_swap * 10;
//
let port = get_port().expect("Failed to find a free port"); // let port = get_port().expect("Failed to find a free port");
let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port) // let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port)
.parse() // .parse()
.expect("failed to parse Alice's address"); // .expect("failed to parse Alice's address");
//
let config = Config::regtest(); // let config = Config::regtest();
//
let ( // let (
alice_state, // alice_state,
mut alice_event_loop, // mut alice_event_loop,
alice_event_loop_handle, // alice_event_loop_handle,
alice_btc_wallet, // alice_btc_wallet,
alice_xmr_wallet, // alice_xmr_wallet,
alice_db, // alice_db,
) = init_alice( // ) = init_alice(
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
xmr_to_swap, // xmr_to_swap,
alice_xmr_starting_balance, // alice_xmr_starting_balance,
alice_multiaddr.clone(), // alice_multiaddr.clone(),
config, // config,
Seed::random().unwrap(), // Seed::random().unwrap(),
) // )
.await; // .await;
//
let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet, bob_xmr_wallet, bob_db) = // let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet,
init_bob( // bob_xmr_wallet, bob_db) = init_bob(
alice_multiaddr, // alice_multiaddr,
alice_event_loop.peer_id(), // alice_event_loop.peer_id(),
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
bob_btc_starting_balance, // bob_btc_starting_balance,
xmr_to_swap, // xmr_to_swap,
config, // config,
) // )
.await; // .await;
//
let bob_btc_locked_fut = bob::swap::run_until( // let bob_btc_locked_fut = bob::swap::run_until(
bob_state, // bob_state,
bob::swap::is_btc_locked, // bob::swap::is_btc_locked,
bob_event_loop_handle, // bob_event_loop_handle,
bob_db, // bob_db,
bob_btc_wallet.clone(), // bob_btc_wallet.clone(),
bob_xmr_wallet.clone(), // bob_xmr_wallet.clone(),
OsRng, // OsRng,
Uuid::new_v4(), // Uuid::new_v4(),
) // )
.boxed(); // .boxed();
//
let bob_fut = select(bob_btc_locked_fut, bob_event_loop.run().boxed()); // let bob_fut = select(bob_btc_locked_fut, bob_event_loop.run().boxed());
//
let alice_fut = alice::swap::swap( // let alice_fut = alice::swap::swap(
alice_state, // alice_state,
alice_event_loop_handle, // alice_event_loop_handle,
alice_btc_wallet.clone(), // alice_btc_wallet.clone(),
alice_xmr_wallet.clone(), // alice_xmr_wallet.clone(),
Config::regtest(), // Config::regtest(),
Uuid::new_v4(), // Uuid::new_v4(),
alice_db, // alice_db,
) // )
.boxed(); // .boxed();
//
let alice_fut = select(alice_fut, alice_event_loop.run().boxed()); // let alice_fut = select(alice_fut, alice_event_loop.run().boxed());
//
// Wait until alice has locked xmr and bob has locked btc // // Wait until alice has locked xmr and bob has locked btc
let (alice_state, bob_state) = join(alice_fut, bob_fut).await; // let (alice_state, bob_state) = join(alice_fut, bob_fut).await;
//
let alice_state = match alice_state { // let alice_state = match alice_state {
Either::Left((state, _)) => state.unwrap(), // Either::Left((state, _)) => state.unwrap(),
Either::Right(_) => panic!("Alice event loop should not terminate."), // Either::Right(_) => panic!("Alice event loop should not terminate."),
}; // };
//
let bob_state = match bob_state { // let bob_state = match bob_state {
Either::Left((state, _)) => state.unwrap(), // Either::Left((state, _)) => state.unwrap(),
Either::Right(_) => panic!("Bob event loop should not terminate."), // Either::Right(_) => panic!("Bob event loop should not terminate."),
}; // };
//
assert!(matches!(alice_state, AliceState::BtcPunished)); // assert!(matches!(alice_state, AliceState::BtcPunished));
let bob_state3 = if let BobState::BtcLocked(state3, ..) = bob_state { // let bob_state3 = if let BobState::BtcLocked(state3, ..) = bob_state {
state3 // state3
} else { // } else {
panic!("Bob in unexpected state"); // panic!("Bob in unexpected state");
}; // };
//
let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap(); // let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap();
let btc_bob_final = bob_btc_wallet.as_ref().balance().await.unwrap(); // let btc_bob_final = bob_btc_wallet.as_ref().balance().await.unwrap();
//
// lock_tx_bitcoin_fee is determined by the wallet, it is not necessarily equal // // lock_tx_bitcoin_fee is determined by the wallet, it is not necessarily
// to TX_FEE // equal // to TX_FEE
let lock_tx_bitcoin_fee = bob_btc_wallet // let lock_tx_bitcoin_fee = bob_btc_wallet
.transaction_fee(bob_state3.tx_lock_id()) // .transaction_fee(bob_state3.tx_lock_id())
.await // .await
.unwrap(); // .unwrap();
//
assert_eq!( // assert_eq!(
btc_alice_final, // btc_alice_final,
alice_btc_starting_balance + btc_to_swap - bitcoin::Amount::from_sat(2 * bitcoin::TX_FEE) // alice_btc_starting_balance + btc_to_swap -
); // bitcoin::Amount::from_sat(2 * bitcoin::TX_FEE) );
//
assert_eq!( // assert_eq!(
btc_bob_final, // btc_bob_final,
bob_btc_starting_balance - btc_to_swap - lock_tx_bitcoin_fee // bob_btc_starting_balance - btc_to_swap - lock_tx_bitcoin_fee
); // );
} // }

View file

@ -1,174 +1,177 @@
use crate::testutils::{init_alice, init_bob}; // use crate::testutils::{init_alice, init_bob};
use futures::future::try_join; // use futures::future::try_join;
use get_port::get_port; // use get_port::get_port;
use libp2p::Multiaddr; // use libp2p::Multiaddr;
use rand::rngs::OsRng; // use rand::rngs::OsRng;
use swap::{ // use swap::{
bitcoin, // bitcoin,
config::Config, // config::Config,
database::Database, // database::Database,
monero, // monero,
protocol::{alice, alice::AliceState, bob, bob::BobState}, // protocol::{alice, alice::AliceState, bob, bob::BobState},
seed::Seed, // seed::Seed,
}; // };
use tempfile::tempdir; // use tempfile::tempdir;
use testcontainers::clients::Cli; // use testcontainers::clients::Cli;
use testutils::init_tracing; // use testutils::init_tracing;
use tokio::select; // use tokio::select;
use uuid::Uuid; // use uuid::Uuid;
//
pub mod testutils; // pub mod testutils;
//
// Bob locks btc and Alice locks xmr. Alice fails to act so Bob refunds. Alice // // Bob locks btc and Alice locks xmr. Alice fails to act so Bob refunds.
// then also refunds. // Alice // then also refunds.
#[tokio::test] // #[tokio::test]
async fn given_alice_restarts_after_xmr_is_locked_abort_swap() { // async fn given_alice_restarts_after_xmr_is_locked_abort_swap() {
let _guard = init_tracing(); // let _guard = init_tracing();
//
let cli = Cli::default(); // let cli = Cli::default();
let ( // let (
monero, // monero,
testutils::Containers { // testutils::Containers {
bitcoind, // bitcoind,
monerods: _monerods, // monerods: _monerods,
}, // },
) = testutils::init_containers(&cli).await; // ) = testutils::init_containers(&cli).await;
//
let btc_to_swap = bitcoin::Amount::from_sat(1_000_000); // let btc_to_swap = bitcoin::Amount::from_sat(1_000_000);
let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000); // let xmr_to_swap = monero::Amount::from_piconero(1_000_000_000_000);
//
let bob_btc_starting_balance = btc_to_swap * 10; // let bob_btc_starting_balance = btc_to_swap * 10;
let bob_xmr_starting_balance = monero::Amount::from_piconero(0); // let bob_xmr_starting_balance = monero::Amount::from_piconero(0);
//
let alice_btc_starting_balance = bitcoin::Amount::ZERO; // let alice_btc_starting_balance = bitcoin::Amount::ZERO;
let alice_xmr_starting_balance = xmr_to_swap * 10; // let alice_xmr_starting_balance = xmr_to_swap * 10;
//
let port = get_port().expect("Failed to find a free port"); // let port = get_port().expect("Failed to find a free port");
let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port) // let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port)
.parse() // .parse()
.expect("failed to parse Alice's address"); // .expect("failed to parse Alice's address");
//
let alice_seed = Seed::random().unwrap(); // let alice_seed = Seed::random().unwrap();
let ( // let (
alice_state, // alice_state,
mut alice_event_loop_1, // mut alice_event_loop_1,
alice_event_loop_handle_1, // alice_event_loop_handle_1,
alice_btc_wallet, // alice_btc_wallet,
alice_xmr_wallet, // alice_xmr_wallet,
_, // _,
) = init_alice( // ) = init_alice(
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
xmr_to_swap, // xmr_to_swap,
alice_xmr_starting_balance, // alice_xmr_starting_balance,
alice_multiaddr.clone(), // alice_multiaddr.clone(),
Config::regtest(), // Config::regtest(),
alice_seed, // alice_seed,
) // )
.await; // .await;
//
let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet, bob_xmr_wallet, bob_db) = // let (bob_state, bob_event_loop, bob_event_loop_handle, bob_btc_wallet,
init_bob( // bob_xmr_wallet, bob_db) = init_bob(
alice_multiaddr.clone(), // alice_multiaddr.clone(),
alice_event_loop_1.peer_id(), // alice_event_loop_1.peer_id(),
&bitcoind, // &bitcoind,
&monero, // &monero,
btc_to_swap, // btc_to_swap,
bob_btc_starting_balance, // bob_btc_starting_balance,
xmr_to_swap, // xmr_to_swap,
Config::regtest(), // Config::regtest(),
) // )
.await; // .await;
//
let bob_fut = bob::swap::swap( // let bob_fut = bob::swap::swap(
bob_state, // bob_state,
bob_event_loop_handle, // bob_event_loop_handle,
bob_db, // bob_db,
bob_btc_wallet.clone(), // bob_btc_wallet.clone(),
bob_xmr_wallet.clone(), // bob_xmr_wallet.clone(),
OsRng, // OsRng,
Uuid::new_v4(), // Uuid::new_v4(),
); // );
//
let alice_swap_id = Uuid::new_v4(); // let alice_swap_id = Uuid::new_v4();
let alice_db_datadir = tempdir().unwrap(); // let alice_db_datadir = tempdir().unwrap();
//
let alice_xmr_locked_fut = { // let alice_xmr_locked_fut = {
let alice_db = Database::open(alice_db_datadir.path()).unwrap(); // let alice_db = Database::open(alice_db_datadir.path()).unwrap();
alice::swap::run_until( // alice::swap::run_until(
alice_state, // alice_state,
alice::swap::is_xmr_locked, // alice::swap::is_xmr_locked,
alice_event_loop_handle_1, // alice_event_loop_handle_1,
alice_btc_wallet.clone(), // alice_btc_wallet.clone(),
alice_xmr_wallet.clone(), // alice_xmr_wallet.clone(),
Config::regtest(), // Config::regtest(),
alice_swap_id, // alice_swap_id,
alice_db, // alice_db,
) // )
}; // };
//
tokio::spawn(bob_event_loop.run()); // tokio::spawn(bob_event_loop.run());
//
// We are selecting with alice_event_loop_1 so that we stop polling on it once // // We are selecting with alice_event_loop_1 so that we stop polling on it
// the try_join is finished. // once // the try_join is finished.
let (bob_state, alice_restart_state) = select! { // let (bob_state, alice_restart_state) = select! {
res = try_join(bob_fut, alice_xmr_locked_fut) => res.unwrap(), // res = try_join(bob_fut, alice_xmr_locked_fut) => res.unwrap(),
_ = alice_event_loop_1.run() => panic!("The event loop should never finish") // _ = alice_event_loop_1.run() => panic!("The event loop should never
}; // finish") };
//
let tx_lock_id = if let BobState::BtcRefunded(state4) = bob_state { // let tx_lock_id = if let BobState::BtcRefunded(state4) = bob_state {
state4.tx_lock_id() // state4.tx_lock_id()
} else { // } else {
panic!("Bob in unexpected state"); // panic!("Bob in unexpected state");
}; // };
//
let (mut alice_event_loop_2, alice_event_loop_handle_2) = // let (mut alice_event_loop_2, alice_event_loop_handle_2) =
testutils::init_alice_event_loop(alice_multiaddr, alice_seed); // testutils::init_alice_event_loop(alice_multiaddr, alice_seed);
//
let alice_final_state = { // let alice_final_state = {
let alice_db = Database::open(alice_db_datadir.path()).unwrap(); // let alice_db = Database::open(alice_db_datadir.path()).unwrap();
alice::swap::swap( // alice::swap::swap(
alice_restart_state, // alice_restart_state,
alice_event_loop_handle_2, // alice_event_loop_handle_2,
alice_btc_wallet.clone(), // alice_btc_wallet.clone(),
alice_xmr_wallet.clone(), // alice_xmr_wallet.clone(),
Config::regtest(), // Config::regtest(),
alice_swap_id, // alice_swap_id,
alice_db, // alice_db,
) // )
.await // .await
.unwrap() // .unwrap()
}; // };
tokio::spawn(async move { alice_event_loop_2.run().await }); // tokio::spawn(async move { alice_event_loop_2.run().await });
//
assert!(matches!(alice_final_state, AliceState::XmrRefunded)); // assert!(matches!(alice_final_state, AliceState::XmrRefunded));
//
let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap(); // let btc_alice_final = alice_btc_wallet.as_ref().balance().await.unwrap();
let btc_bob_final = bob_btc_wallet.as_ref().balance().await.unwrap(); // let btc_bob_final = bob_btc_wallet.as_ref().balance().await.unwrap();
//
let lock_tx_bitcoin_fee = bob_btc_wallet.transaction_fee(tx_lock_id).await.unwrap(); // let lock_tx_bitcoin_fee =
// bob_btc_wallet.transaction_fee(tx_lock_id).await.unwrap();
assert_eq!(btc_alice_final, alice_btc_starting_balance); //
// assert_eq!(btc_alice_final, alice_btc_starting_balance);
// Alice or Bob could publish TxCancel. This means Bob could pay tx fees for //
// TxCancel and TxRefund or only TxRefund // // Alice or Bob could publish TxCancel. This means Bob could pay tx fees
let btc_bob_final_alice_submitted_cancel = btc_bob_final // for // TxCancel and TxRefund or only TxRefund
== bob_btc_starting_balance // let btc_bob_final_alice_submitted_cancel = btc_bob_final
- lock_tx_bitcoin_fee // == bob_btc_starting_balance
- bitcoin::Amount::from_sat(bitcoin::TX_FEE); // - lock_tx_bitcoin_fee
// - bitcoin::Amount::from_sat(bitcoin::TX_FEE);
let btc_bob_final_bob_submitted_cancel = btc_bob_final //
== bob_btc_starting_balance // let btc_bob_final_bob_submitted_cancel = btc_bob_final
- lock_tx_bitcoin_fee // == bob_btc_starting_balance
- bitcoin::Amount::from_sat(2 * bitcoin::TX_FEE); // - lock_tx_bitcoin_fee
assert!(btc_bob_final_alice_submitted_cancel || btc_bob_final_bob_submitted_cancel); // - bitcoin::Amount::from_sat(2 * bitcoin::TX_FEE);
// assert!(btc_bob_final_alice_submitted_cancel ||
alice_xmr_wallet.as_ref().inner.refresh().await.unwrap(); // btc_bob_final_bob_submitted_cancel);
let xmr_alice_final = alice_xmr_wallet.as_ref().get_balance().await.unwrap(); //
assert_eq!(xmr_alice_final, xmr_to_swap); // alice_xmr_wallet.as_ref().inner.refresh().await.unwrap();
// let xmr_alice_final =
bob_xmr_wallet.as_ref().inner.refresh().await.unwrap(); // alice_xmr_wallet.as_ref().get_balance().await.unwrap(); assert_eq!
let xmr_bob_final = bob_xmr_wallet.as_ref().get_balance().await.unwrap(); // (xmr_alice_final, xmr_to_swap);
assert_eq!(xmr_bob_final, bob_xmr_starting_balance); //
} // bob_xmr_wallet.as_ref().inner.refresh().await.unwrap();
// let xmr_bob_final = bob_xmr_wallet.as_ref().get_balance().await.unwrap();
// assert_eq!(xmr_bob_final, bob_xmr_starting_balance);
// }

View file

@ -0,0 +1,135 @@
use crate::testutils::init_wallets;
use anyhow::Result;
use bitcoin_harness::Bitcoind;
use libp2p::{core::Multiaddr, PeerId};
use monero_harness::Monero;
use rand::rngs::OsRng;
use std::sync::Arc;
use swap::{
bitcoin,
config::Config,
database::Database,
monero, network,
network::transport::build,
protocol::{
alice,
alice::{swap::AliceActor, AliceState, EventLoop},
},
seed::Seed,
SwapAmounts,
};
use tempfile::tempdir;
use tokio::select;
use uuid::Uuid;
pub struct Alice {
state: AliceState,
actor: AliceActor,
event_loop: EventLoop,
}
impl Alice {
#[allow(clippy::too_many_arguments)]
pub async fn new(
bitcoind: &Bitcoind<'_>,
monero: &Monero,
btc_to_swap: bitcoin::Amount,
xmr_to_swap: monero::Amount,
xmr_starting_balance: monero::Amount,
listen: Multiaddr,
config: Config,
seed: Seed,
) -> Alice {
let (alice_btc_wallet, alice_xmr_wallet) = init_wallets(
"alice",
bitcoind,
monero,
None,
Some(xmr_starting_balance),
config,
)
.await;
let alice_start_state =
init_alice_state(btc_to_swap, xmr_to_swap, alice_btc_wallet.clone(), config).await;
let (event_loop, event_loop_handle) = init_alice_event_loop(listen, seed);
let alice_db_datadir = tempdir().unwrap();
let alice_db = Database::open(alice_db_datadir.path()).unwrap();
let alice_actor = AliceActor::new(
event_loop_handle,
alice_btc_wallet,
alice_xmr_wallet,
alice_db,
config,
Uuid::new_v4(),
);
Alice {
state: alice_start_state,
actor: alice_actor,
event_loop,
}
}
pub fn peer_id(&self) -> PeerId {
self.event_loop.peer_id()
}
pub async fn swap(mut self) -> Result<()> {
let final_state = select! {
res = self.actor.swap(self.state) => res.unwrap(),
_ = self.event_loop.run() => panic!("The event loop should never finish")
};
self.state = final_state;
Ok(())
}
pub async fn assert_btc_redeemed(&self) {}
}
pub async fn init_alice_state(
btc_to_swap: bitcoin::Amount,
xmr_to_swap: monero::Amount,
alice_btc_wallet: Arc<bitcoin::Wallet>,
config: Config,
) -> AliceState {
let rng = &mut OsRng;
let amounts = SwapAmounts {
btc: btc_to_swap,
xmr: xmr_to_swap,
};
let a = bitcoin::SecretKey::new_random(rng);
let s_a = cross_curve_dleq::Scalar::random(rng);
let v_a = monero::PrivateViewKey::new_random(rng);
let redeem_address = alice_btc_wallet.as_ref().new_address().await.unwrap();
let punish_address = redeem_address.clone();
let state0 = alice::State0::new(
a,
s_a,
v_a,
amounts.btc,
amounts.xmr,
config.bitcoin_cancel_timelock,
config.bitcoin_punish_timelock,
redeem_address,
punish_address,
);
AliceState::Started { amounts, state0 }
}
pub fn init_alice_event_loop(
listen: Multiaddr,
seed: Seed,
) -> (
alice::event_loop::EventLoop,
alice::event_loop::EventLoopHandle,
) {
let alice_behaviour = alice::Behaviour::new(network::Seed::new(seed));
let alice_transport = build(alice_behaviour.identity()).unwrap();
alice::event_loop::EventLoop::new(alice_transport, alice_behaviour, listen).unwrap()
}

124
swap/tests/testutils/bob.rs Normal file
View file

@ -0,0 +1,124 @@
use crate::testutils::init_wallets;
use anyhow::Result;
use bitcoin_harness::Bitcoind;
use futures::future::{select, Select};
use libp2p::{core::Multiaddr, PeerId};
use monero_harness::Monero;
use rand::rngs::OsRng;
use std::{pin::Pin, sync::Arc};
use swap::{
bitcoin,
config::Config,
database::Database,
monero, network,
network::transport::build,
protocol::{bob, bob::BobState},
seed::Seed,
SwapAmounts,
};
use tempfile::tempdir;
use uuid::Uuid;
pub struct Bob {
state: BobState,
event_loop: bob::event_loop::EventLoop,
event_loop_handle: bob::event_loop::EventLoopHandle,
bitcoin_wallet: Arc<swap::bitcoin::Wallet>,
monero_wallet: Arc<swap::monero::Wallet>,
db: Database,
}
impl Bob {
#[allow(clippy::too_many_arguments)]
pub async fn new(
alice_multiaddr: Multiaddr,
alice_peer_id: PeerId,
bitcoind: &Bitcoind<'_>,
monero: &Monero,
btc_to_swap: bitcoin::Amount,
xmr_to_swap: monero::Amount,
btc_starting_balance: bitcoin::Amount,
config: Config,
) -> Bob {
let (bob_btc_wallet, bob_xmr_wallet) = init_wallets(
"bob",
bitcoind,
monero,
Some(btc_starting_balance),
None,
config,
)
.await;
let bob_state =
init_bob_state(btc_to_swap, xmr_to_swap, bob_btc_wallet.clone(), config).await;
let (event_loop, event_loop_handle) = init_bob_event_loop(alice_peer_id, alice_multiaddr);
let bob_db_dir = tempdir().unwrap();
let bob_db = Database::open(bob_db_dir.path()).unwrap();
Bob {
state: bob_state,
event_loop,
event_loop_handle,
bitcoin_wallet: bob_btc_wallet,
monero_wallet: bob_xmr_wallet,
db: bob_db,
}
}
pub async fn swap(
&self,
) -> Select<Pin<Box<Result<BobState>>>, Pin<Box<Result<bob::EventLoop>>>> {
let bob_swap_fut = bob::swap::swap(
self.state.clone(),
self.event_loop_handle,
self.db,
self.bitcoin_wallet,
self.monero_wallet,
OsRng,
Uuid::new_v4(),
);
let bob_fut = select(Box::pin(bob_swap_fut), Box::pin(self.event_loop.run()));
bob_fut
}
pub async fn assert_btc_redeemed(&self) {}
}
pub async fn init_bob_state(
btc_to_swap: bitcoin::Amount,
xmr_to_swap: monero::Amount,
bob_btc_wallet: Arc<bitcoin::Wallet>,
config: Config,
) -> BobState {
let amounts = SwapAmounts {
btc: btc_to_swap,
xmr: xmr_to_swap,
};
let refund_address = bob_btc_wallet.new_address().await.unwrap();
let state0 = bob::State0::new(
&mut OsRng,
btc_to_swap,
xmr_to_swap,
config.bitcoin_cancel_timelock,
config.bitcoin_punish_timelock,
refund_address,
config.monero_finality_confirmations,
);
BobState::Started { state0, amounts }
}
pub fn init_bob_event_loop(
alice_peer_id: PeerId,
alice_addr: Multiaddr,
) -> (bob::event_loop::EventLoop, bob::event_loop::EventLoopHandle) {
let seed = Seed::random().unwrap();
let bob_behaviour = bob::Behaviour::new(network::Seed::new(seed));
let bob_transport = build(bob_behaviour.identity()).unwrap();
bob::event_loop::EventLoop::new(bob_transport, bob_behaviour, alice_peer_id, alice_addr)
.unwrap()
}

View file

@ -1,31 +1,95 @@
use bitcoin_harness::Bitcoind; mod alice;
use libp2p::{core::Multiaddr, PeerId}; mod bob;
use monero_harness::{image, Monero};
use rand::rngs::OsRng; use crate::{
use std::sync::Arc; testutils,
use swap::{ testutils::{alice::Alice, bob::Bob},
bitcoin,
config::Config,
database::Database,
monero, network,
network::transport::build,
protocol::{alice, alice::AliceState, bob, bob::BobState},
seed::Seed,
SwapAmounts,
}; };
use tempfile::tempdir; use bitcoin_harness::Bitcoind;
use get_port::get_port;
use libp2p::core::Multiaddr;
use monero_harness::{image, Monero};
use std::sync::Arc;
use swap::{bitcoin, config::Config, monero, seed::Seed};
use testcontainers::{clients::Cli, Container}; use testcontainers::{clients::Cli, Container};
use tracing_core::dispatcher::DefaultGuard; use tracing_core::dispatcher::DefaultGuard;
use tracing_log::LogTracer; use tracing_log::LogTracer;
pub async fn init_containers(cli: &Cli) -> (Monero, Containers<'_>) { pub struct Test<'a> {
pub alice: Alice,
pub bob: Bob,
containers: Containers<'a>,
}
impl<'a> Test<'a> {
pub async fn new(btc_to_swap: bitcoin::Amount, xmr_to_swap: monero::Amount) -> Test<'a> {
let _guard = init_tracing();
let (monero, containers) = testutils::init_containers().await;
let bob_btc_starting_balance = btc_to_swap * 10;
let alice_xmr_starting_balance = xmr_to_swap * 10;
let port = get_port().expect("Failed to find a free port");
let alice_multiaddr: Multiaddr = format!("/ip4/127.0.0.1/tcp/{}", port)
.parse()
.expect("failed to parse Alice's address");
let config = Config::regtest();
let alice = Alice::new(
&containers.bitcoind,
&monero,
btc_to_swap,
xmr_to_swap,
alice_xmr_starting_balance,
alice_multiaddr.clone(),
config,
Seed::random().unwrap(),
)
.await;
let bob = Bob::new(
alice_multiaddr,
alice.peer_id(),
&containers.bitcoind,
&monero,
btc_to_swap,
xmr_to_swap,
bob_btc_starting_balance,
config,
)
.await;
Test {
alice,
bob,
containers,
}
}
}
// This is just to keep the containers alive
#[allow(dead_code)]
pub struct Containers<'a> {
cli: Cli,
pub bitcoind: Bitcoind<'a>,
pub monerods: Vec<Container<'a, Cli, image::Monero>>,
}
pub async fn init_containers<'a>() -> (Monero, Containers<'a>) {
let cli = Cli::default();
let bitcoind = Bitcoind::new(&cli, "0.19.1").unwrap(); let bitcoind = Bitcoind::new(&cli, "0.19.1").unwrap();
let _ = bitcoind.init(5).await; let _ = bitcoind.init(5).await;
let (monero, monerods) = Monero::new(&cli, None, vec!["alice".to_string(), "bob".to_string()]) let (monero, monerods) = Monero::new(&cli, None, vec!["alice".to_string(), "bob".to_string()])
.await .await
.unwrap(); .unwrap();
(monero, Containers { bitcoind, monerods }) (monero, Containers {
cli,
bitcoind,
monerods,
})
} }
pub async fn init_wallets( pub async fn init_wallets(
@ -71,186 +135,6 @@ pub async fn init_wallets(
(btc_wallet, xmr_wallet) (btc_wallet, xmr_wallet)
} }
pub async fn init_alice_state(
btc_to_swap: bitcoin::Amount,
xmr_to_swap: monero::Amount,
alice_btc_wallet: Arc<bitcoin::Wallet>,
config: Config,
) -> AliceState {
let rng = &mut OsRng;
let amounts = SwapAmounts {
btc: btc_to_swap,
xmr: xmr_to_swap,
};
let a = bitcoin::SecretKey::new_random(rng);
let s_a = cross_curve_dleq::Scalar::random(rng);
let v_a = monero::PrivateViewKey::new_random(rng);
let redeem_address = alice_btc_wallet.as_ref().new_address().await.unwrap();
let punish_address = redeem_address.clone();
let state0 = alice::State0::new(
a,
s_a,
v_a,
amounts.btc,
amounts.xmr,
config.bitcoin_cancel_timelock,
config.bitcoin_punish_timelock,
redeem_address,
punish_address,
);
AliceState::Started { amounts, state0 }
}
pub fn init_alice_event_loop(
listen: Multiaddr,
seed: Seed,
) -> (
alice::event_loop::EventLoop,
alice::event_loop::EventLoopHandle,
) {
let alice_behaviour = alice::Behaviour::new(network::Seed::new(seed));
let alice_transport = build(alice_behaviour.identity()).unwrap();
alice::event_loop::EventLoop::new(alice_transport, alice_behaviour, listen).unwrap()
}
#[allow(clippy::too_many_arguments)]
pub async fn init_alice(
bitcoind: &Bitcoind<'_>,
monero: &Monero,
btc_to_swap: bitcoin::Amount,
xmr_to_swap: monero::Amount,
xmr_starting_balance: monero::Amount,
listen: Multiaddr,
config: Config,
seed: Seed,
) -> (
AliceState,
alice::event_loop::EventLoop,
alice::event_loop::EventLoopHandle,
Arc<swap::bitcoin::Wallet>,
Arc<swap::monero::Wallet>,
Database,
) {
let (alice_btc_wallet, alice_xmr_wallet) = init_wallets(
"alice",
bitcoind,
monero,
None,
Some(xmr_starting_balance),
config,
)
.await;
let alice_start_state =
init_alice_state(btc_to_swap, xmr_to_swap, alice_btc_wallet.clone(), config).await;
let (event_loop, event_loop_handle) = init_alice_event_loop(listen, seed);
let alice_db_datadir = tempdir().unwrap();
let alice_db = Database::open(alice_db_datadir.path()).unwrap();
(
alice_start_state,
event_loop,
event_loop_handle,
alice_btc_wallet,
alice_xmr_wallet,
alice_db,
)
}
pub async fn init_bob_state(
btc_to_swap: bitcoin::Amount,
xmr_to_swap: monero::Amount,
bob_btc_wallet: Arc<bitcoin::Wallet>,
config: Config,
) -> BobState {
let amounts = SwapAmounts {
btc: btc_to_swap,
xmr: xmr_to_swap,
};
let refund_address = bob_btc_wallet.new_address().await.unwrap();
let state0 = bob::State0::new(
&mut OsRng,
btc_to_swap,
xmr_to_swap,
config.bitcoin_cancel_timelock,
config.bitcoin_punish_timelock,
refund_address,
config.monero_finality_confirmations,
);
BobState::Started { state0, amounts }
}
pub fn init_bob_event_loop(
alice_peer_id: PeerId,
alice_addr: Multiaddr,
) -> (bob::event_loop::EventLoop, bob::event_loop::EventLoopHandle) {
let seed = Seed::random().unwrap();
let bob_behaviour = bob::Behaviour::new(network::Seed::new(seed));
let bob_transport = build(bob_behaviour.identity()).unwrap();
bob::event_loop::EventLoop::new(bob_transport, bob_behaviour, alice_peer_id, alice_addr)
.unwrap()
}
#[allow(clippy::too_many_arguments)]
pub async fn init_bob(
alice_multiaddr: Multiaddr,
alice_peer_id: PeerId,
bitcoind: &Bitcoind<'_>,
monero: &Monero,
btc_to_swap: bitcoin::Amount,
btc_starting_balance: bitcoin::Amount,
xmr_to_swap: monero::Amount,
config: Config,
) -> (
BobState,
bob::event_loop::EventLoop,
bob::event_loop::EventLoopHandle,
Arc<swap::bitcoin::Wallet>,
Arc<swap::monero::Wallet>,
Database,
) {
let (bob_btc_wallet, bob_xmr_wallet) = init_wallets(
"bob",
bitcoind,
monero,
Some(btc_starting_balance),
None,
config,
)
.await;
let bob_state = init_bob_state(btc_to_swap, xmr_to_swap, bob_btc_wallet.clone(), config).await;
let (event_loop, event_loop_handle) = init_bob_event_loop(alice_peer_id, alice_multiaddr);
let bob_db_dir = tempdir().unwrap();
let bob_db = Database::open(bob_db_dir.path()).unwrap();
(
bob_state,
event_loop,
event_loop_handle,
bob_btc_wallet,
bob_xmr_wallet,
bob_db,
)
}
// This is just to keep the containers alive
#[allow(dead_code)]
pub struct Containers<'a> {
pub bitcoind: Bitcoind<'a>,
pub monerods: Vec<Container<'a, Cli, image::Monero>>,
}
/// Utility function to initialize logging in the test environment. /// Utility function to initialize logging in the test environment.
/// Note that you have to keep the `_guard` in scope after calling in test: /// Note that you have to keep the `_guard` in scope after calling in test:
/// ///