Merge #72
72: Add refund test and complete punish test r=da-kami a=rishflab Added a test for the scenario when both Alice and Bob refund Added assertions to check balances are correct after the Alice punish test Co-authored-by: rishflab <rishflab@hotmail.com>pull/89/head
commit
bbe454d269
@ -1,98 +0,0 @@
|
||||
pub mod harness;
|
||||
|
||||
mod tests {
|
||||
use crate::{
|
||||
harness,
|
||||
harness::{
|
||||
init_bitcoind, init_test,
|
||||
node::{run_alice_until, run_bob_until},
|
||||
},
|
||||
};
|
||||
use futures::future;
|
||||
use monero_harness::Monero;
|
||||
use rand::rngs::OsRng;
|
||||
use std::convert::TryInto;
|
||||
use testcontainers::clients::Cli;
|
||||
use xmr_btc::{
|
||||
alice,
|
||||
bitcoin::{Amount, TX_FEE},
|
||||
bob,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn both_refund() {
|
||||
let cli = Cli::default();
|
||||
let (monero, _container) = Monero::new(&cli, Some("br".to_string()), vec![
|
||||
"alice".to_string(),
|
||||
"bob".to_string(),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
let bitcoind = init_bitcoind(&cli).await;
|
||||
|
||||
let (
|
||||
alice_state0,
|
||||
bob_state0,
|
||||
mut alice_node,
|
||||
mut bob_node,
|
||||
initial_balances,
|
||||
swap_amounts,
|
||||
) = init_test(&monero, &bitcoind, None, None).await;
|
||||
|
||||
let (alice_state, bob_state) = future::try_join(
|
||||
run_alice_until(
|
||||
&mut alice_node,
|
||||
alice_state0.into(),
|
||||
harness::alice::is_state5,
|
||||
&mut OsRng,
|
||||
),
|
||||
run_bob_until(
|
||||
&mut bob_node,
|
||||
bob_state0.into(),
|
||||
harness::bob::is_state3,
|
||||
&mut OsRng,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let alice_state5: alice::State5 = alice_state.try_into().unwrap();
|
||||
let bob_state3: bob::State3 = bob_state.try_into().unwrap();
|
||||
|
||||
bob_state3
|
||||
.refund_btc(&bob_node.bitcoin_wallet)
|
||||
.await
|
||||
.unwrap();
|
||||
alice_state5
|
||||
.refund_xmr(&alice_node.bitcoin_wallet, &alice_node.monero_wallet)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let alice_final_btc_balance = alice_node.bitcoin_wallet.balance().await.unwrap();
|
||||
let bob_final_btc_balance = bob_node.bitcoin_wallet.balance().await.unwrap();
|
||||
|
||||
// lock_tx_bitcoin_fee is determined by the wallet, it is not necessarily equal
|
||||
// to TX_FEE
|
||||
let lock_tx_bitcoin_fee = bob_node
|
||||
.bitcoin_wallet
|
||||
.transaction_fee(bob_state3.tx_lock_id())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
monero.wallet("alice").unwrap().refresh().await.unwrap();
|
||||
let alice_final_xmr_balance = alice_node.monero_wallet.get_balance().await.unwrap();
|
||||
let bob_final_xmr_balance = bob_node.monero_wallet.get_balance().await.unwrap();
|
||||
|
||||
assert_eq!(alice_final_btc_balance, initial_balances.alice_btc);
|
||||
assert_eq!(
|
||||
bob_final_btc_balance,
|
||||
// The 2 * TX_FEE corresponds to tx_refund and tx_cancel.
|
||||
initial_balances.bob_btc - Amount::from_sat(2 * TX_FEE) - lock_tx_bitcoin_fee
|
||||
);
|
||||
|
||||
// Because we create a new wallet when claiming Monero, we can only assert on
|
||||
// this new wallet owning all of `xmr_amount` after refund
|
||||
assert_eq!(alice_final_xmr_balance, swap_amounts.xmr);
|
||||
assert_eq!(bob_final_xmr_balance, initial_balances.bob_xmr);
|
||||
}
|
||||
}
|
@ -1,202 +0,0 @@
|
||||
pub mod node;
|
||||
pub mod transport;
|
||||
pub mod wallet;
|
||||
|
||||
pub mod bob {
|
||||
use xmr_btc::bob::State;
|
||||
|
||||
pub fn is_state2(state: &State) -> bool {
|
||||
matches!(state, State::State2 { .. })
|
||||
}
|
||||
|
||||
// TODO: use macro or generics
|
||||
pub fn is_state5(state: &State) -> bool {
|
||||
matches!(state, State::State5 { .. })
|
||||
}
|
||||
|
||||
// TODO: use macro or generics
|
||||
pub fn is_state3(state: &State) -> bool {
|
||||
matches!(state, State::State3 { .. })
|
||||
}
|
||||
}
|
||||
|
||||
pub mod alice {
|
||||
use xmr_btc::alice::State;
|
||||
|
||||
pub fn is_state3(state: &State) -> bool {
|
||||
matches!(state, State::State3 { .. })
|
||||
}
|
||||
|
||||
// TODO: use macro or generics
|
||||
pub fn is_state4(state: &State) -> bool {
|
||||
matches!(state, State::State4 { .. })
|
||||
}
|
||||
|
||||
// TODO: use macro or generics
|
||||
pub fn is_state5(state: &State) -> bool {
|
||||
matches!(state, State::State5 { .. })
|
||||
}
|
||||
|
||||
// TODO: use macro or generics
|
||||
pub fn is_state6(state: &State) -> bool {
|
||||
matches!(state, State::State6 { .. })
|
||||
}
|
||||
}
|
||||
|
||||
use bitcoin_harness::Bitcoind;
|
||||
use monero_harness::Monero;
|
||||
use node::{AliceNode, BobNode};
|
||||
use rand::rngs::OsRng;
|
||||
use testcontainers::clients::Cli;
|
||||
use tokio::sync::{
|
||||
mpsc,
|
||||
mpsc::{Receiver, Sender},
|
||||
};
|
||||
use transport::Transport;
|
||||
use xmr_btc::{bitcoin, monero};
|
||||
|
||||
const TEN_XMR: u64 = 10_000_000_000_000;
|
||||
const RELATIVE_REFUND_TIMELOCK: u32 = 1;
|
||||
const RELATIVE_PUNISH_TIMELOCK: u32 = 1;
|
||||
pub const ALICE_TEST_DB_FOLDER: &str = "../target/e2e-test-alice-recover";
|
||||
pub const BOB_TEST_DB_FOLDER: &str = "../target/e2e-test-bob-recover";
|
||||
|
||||
pub async fn init_bitcoind(tc_client: &Cli) -> Bitcoind<'_> {
|
||||
let bitcoind = Bitcoind::new(tc_client, "0.19.1").expect("failed to create bitcoind");
|
||||
let _ = bitcoind.init(5).await;
|
||||
|
||||
bitcoind
|
||||
}
|
||||
|
||||
pub struct InitialBalances {
|
||||
pub alice_xmr: monero::Amount,
|
||||
pub alice_btc: bitcoin::Amount,
|
||||
pub bob_xmr: monero::Amount,
|
||||
pub bob_btc: bitcoin::Amount,
|
||||
}
|
||||
|
||||
pub struct SwapAmounts {
|
||||
pub xmr: monero::Amount,
|
||||
pub btc: bitcoin::Amount,
|
||||
}
|
||||
|
||||
pub fn init_alice_and_bob_transports() -> (
|
||||
Transport<xmr_btc::alice::Message, xmr_btc::bob::Message>,
|
||||
Transport<xmr_btc::bob::Message, xmr_btc::alice::Message>,
|
||||
) {
|
||||
let (a_sender, b_receiver): (
|
||||
Sender<xmr_btc::alice::Message>,
|
||||
Receiver<xmr_btc::alice::Message>,
|
||||
) = mpsc::channel(5);
|
||||
let (b_sender, a_receiver): (
|
||||
Sender<xmr_btc::bob::Message>,
|
||||
Receiver<xmr_btc::bob::Message>,
|
||||
) = mpsc::channel(5);
|
||||
|
||||
let a_transport = Transport {
|
||||
sender: a_sender,
|
||||
receiver: a_receiver,
|
||||
};
|
||||
|
||||
let b_transport = Transport {
|
||||
sender: b_sender,
|
||||
receiver: b_receiver,
|
||||
};
|
||||
|
||||
(a_transport, b_transport)
|
||||
}
|
||||
|
||||
pub async fn init_test(
|
||||
monero: &Monero,
|
||||
bitcoind: &Bitcoind<'_>,
|
||||
refund_timelock: Option<u32>,
|
||||
punish_timelock: Option<u32>,
|
||||
) -> (
|
||||
xmr_btc::alice::State0,
|
||||
xmr_btc::bob::State0,
|
||||
AliceNode,
|
||||
BobNode,
|
||||
InitialBalances,
|
||||
SwapAmounts,
|
||||
) {
|
||||
// must be bigger than our hardcoded fee of 10_000
|
||||
let btc_amount = bitcoin::Amount::from_sat(10_000_000);
|
||||
let xmr_amount = monero::Amount::from_piconero(1_000_000_000_000);
|
||||
|
||||
let swap_amounts = SwapAmounts {
|
||||
xmr: xmr_amount,
|
||||
btc: btc_amount,
|
||||
};
|
||||
|
||||
let fund_alice = TEN_XMR;
|
||||
let fund_bob = 0;
|
||||
monero
|
||||
.init(vec![("alice", fund_alice), ("bob", fund_bob)])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let alice_monero_wallet = wallet::monero::Wallet(monero.wallet("alice").unwrap().client());
|
||||
let bob_monero_wallet = wallet::monero::Wallet(monero.wallet("bob").unwrap().client());
|
||||
|
||||
let alice_btc_wallet = wallet::bitcoin::Wallet::new("alice", &bitcoind.node_url)
|
||||
.await
|
||||
.unwrap();
|
||||
let bob_btc_wallet = wallet::bitcoin::make_wallet("bob", &bitcoind, btc_amount)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (alice_transport, bob_transport) = init_alice_and_bob_transports();
|
||||
let alice = AliceNode::new(alice_transport, alice_btc_wallet, alice_monero_wallet);
|
||||
|
||||
let bob = BobNode::new(bob_transport, bob_btc_wallet, bob_monero_wallet);
|
||||
|
||||
let alice_initial_btc_balance = alice.bitcoin_wallet.balance().await.unwrap();
|
||||
let bob_initial_btc_balance = bob.bitcoin_wallet.balance().await.unwrap();
|
||||
|
||||
let alice_initial_xmr_balance = alice.monero_wallet.get_balance().await.unwrap();
|
||||
let bob_initial_xmr_balance = bob.monero_wallet.get_balance().await.unwrap();
|
||||
|
||||
let redeem_address = alice.bitcoin_wallet.new_address().await.unwrap();
|
||||
let punish_address = redeem_address.clone();
|
||||
let refund_address = bob.bitcoin_wallet.new_address().await.unwrap();
|
||||
|
||||
let alice_state0 = {
|
||||
let a = bitcoin::SecretKey::new_random(&mut OsRng);
|
||||
let s_a = cross_curve_dleq::Scalar::random(&mut OsRng);
|
||||
let v_a = monero::PrivateViewKey::new_random(&mut OsRng);
|
||||
|
||||
xmr_btc::alice::State0::new(
|
||||
a,
|
||||
s_a,
|
||||
v_a,
|
||||
btc_amount,
|
||||
xmr_amount,
|
||||
refund_timelock.unwrap_or(RELATIVE_REFUND_TIMELOCK),
|
||||
punish_timelock.unwrap_or(RELATIVE_PUNISH_TIMELOCK),
|
||||
redeem_address.clone(),
|
||||
punish_address.clone(),
|
||||
)
|
||||
};
|
||||
let bob_state0 = xmr_btc::bob::State0::new(
|
||||
&mut OsRng,
|
||||
btc_amount,
|
||||
xmr_amount,
|
||||
refund_timelock.unwrap_or(RELATIVE_REFUND_TIMELOCK),
|
||||
punish_timelock.unwrap_or(RELATIVE_PUNISH_TIMELOCK),
|
||||
refund_address,
|
||||
);
|
||||
let initial_balances = InitialBalances {
|
||||
alice_xmr: alice_initial_xmr_balance,
|
||||
alice_btc: alice_initial_btc_balance,
|
||||
bob_xmr: bob_initial_xmr_balance,
|
||||
bob_btc: bob_initial_btc_balance,
|
||||
};
|
||||
(
|
||||
alice_state0,
|
||||
bob_state0,
|
||||
alice,
|
||||
bob,
|
||||
initial_balances,
|
||||
swap_amounts,
|
||||
)
|
||||
}
|
@ -1,92 +0,0 @@
|
||||
use crate::harness::{transport::Transport, wallet};
|
||||
use anyhow::Result;
|
||||
use rand::{CryptoRng, RngCore};
|
||||
use xmr_btc::{alice, bob};
|
||||
|
||||
// TODO: merge this with bob node
|
||||
// This struct is responsible for I/O
|
||||
pub struct AliceNode {
|
||||
transport: Transport<alice::Message, bob::Message>,
|
||||
pub bitcoin_wallet: wallet::bitcoin::Wallet,
|
||||
pub monero_wallet: wallet::monero::Wallet,
|
||||
}
|
||||
|
||||
impl AliceNode {
|
||||
pub fn new(
|
||||
transport: Transport<alice::Message, bob::Message>,
|
||||
bitcoin_wallet: wallet::bitcoin::Wallet,
|
||||
monero_wallet: wallet::monero::Wallet,
|
||||
) -> AliceNode {
|
||||
Self {
|
||||
transport,
|
||||
bitcoin_wallet,
|
||||
monero_wallet,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_alice_until<R: RngCore + CryptoRng>(
|
||||
alice: &mut AliceNode,
|
||||
initial_state: alice::State,
|
||||
is_state: fn(&alice::State) -> bool,
|
||||
rng: &mut R,
|
||||
) -> Result<alice::State> {
|
||||
let mut result = initial_state;
|
||||
loop {
|
||||
result = alice::next_state(
|
||||
&alice.bitcoin_wallet,
|
||||
&alice.monero_wallet,
|
||||
&mut alice.transport,
|
||||
result,
|
||||
rng,
|
||||
)
|
||||
.await?;
|
||||
if is_state(&result) {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: merge this with alice node
|
||||
// This struct is responsible for I/O
|
||||
pub struct BobNode {
|
||||
transport: Transport<bob::Message, alice::Message>,
|
||||
pub bitcoin_wallet: wallet::bitcoin::Wallet,
|
||||
pub monero_wallet: wallet::monero::Wallet,
|
||||
}
|
||||
|
||||
impl BobNode {
|
||||
pub fn new(
|
||||
transport: Transport<bob::Message, alice::Message>,
|
||||
bitcoin_wallet: wallet::bitcoin::Wallet,
|
||||
monero_wallet: wallet::monero::Wallet,
|
||||
) -> BobNode {
|
||||
Self {
|
||||
transport,
|
||||
bitcoin_wallet,
|
||||
monero_wallet,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_bob_until<R: RngCore + CryptoRng>(
|
||||
bob: &mut BobNode,
|
||||
initial_state: bob::State,
|
||||
is_state: fn(&bob::State) -> bool,
|
||||
rng: &mut R,
|
||||
) -> Result<bob::State> {
|
||||
let mut result = initial_state;
|
||||
loop {
|
||||
result = bob::next_state(
|
||||
&bob.bitcoin_wallet,
|
||||
&bob.monero_wallet,
|
||||
&mut bob.transport,
|
||||
result,
|
||||
rng,
|
||||
)
|
||||
.await?;
|
||||
if is_state(&result) {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_trait::async_trait;
|
||||
use tokio::{
|
||||
stream::StreamExt,
|
||||
sync::mpsc::{Receiver, Sender},
|
||||
};
|
||||
use xmr_btc::transport::{ReceiveMessage, SendMessage};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Transport<SendMsg, RecvMsg> {
|
||||
pub sender: Sender<SendMsg>,
|
||||
pub receiver: Receiver<RecvMsg>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<SendMsg, RecvMsg> SendMessage<SendMsg> for Transport<SendMsg, RecvMsg>
|
||||
where
|
||||
SendMsg: Send + Sync,
|
||||
RecvMsg: std::marker::Send,
|
||||
{
|
||||
async fn send_message(&mut self, message: SendMsg) -> Result<()> {
|
||||
let _ = self
|
||||
.sender
|
||||
.send(message)
|
||||
.await
|
||||
.map_err(|_| anyhow!("failed to send message"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<SendMsg, RecvMsg> ReceiveMessage<RecvMsg> for Transport<SendMsg, RecvMsg>
|
||||
where
|
||||
SendMsg: std::marker::Send,
|
||||
RecvMsg: Send + Sync,
|
||||
{
|
||||
async fn receive_message(&mut self) -> Result<RecvMsg> {
|
||||
let message = self
|
||||
.receiver
|
||||
.next()
|
||||
.await
|
||||
.ok_or_else(|| anyhow!("failed to receive message"))?;
|
||||
Ok(message)
|
||||
}
|
||||
}
|
@ -1,170 +0,0 @@
|
||||
use anyhow::{Context, Result};
|
||||
use async_trait::async_trait;
|
||||
use backoff::{backoff::Constant as ConstantBackoff, future::FutureOperation as _};
|
||||
use bitcoin::{util::psbt::PartiallySignedTransaction, Address, Amount, Transaction, Txid};
|
||||
use bitcoin_harness::{bitcoind_rpc::PsbtBase64, Bitcoind, BitcoindRpcApi};
|
||||
use reqwest::Url;
|
||||
use std::time::Duration;
|
||||
use tokio::time;
|
||||
use xmr_btc::bitcoin::{
|
||||
BlockHeight, BroadcastSignedTransaction, BuildTxLockPsbt, Network, SignTxLock,
|
||||
TransactionBlockHeight, TxLock, WatchForRawTransaction,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Wallet(pub bitcoin_harness::Wallet);
|
||||
|
||||
impl Wallet {
|
||||
pub async fn new(name: &str, url: &Url) -> Result<Self> {
|
||||
let wallet = bitcoin_harness::Wallet::new(name, url.clone()).await?;
|
||||
|
||||
Ok(Self(wallet))
|
||||
}
|
||||
|
||||
pub async fn balance(&self) -> Result<Amount> {
|
||||
let balance = self.0.balance().await?;
|
||||
Ok(balance)
|
||||
}
|
||||
|
||||
pub async fn new_address(&self) -> Result<Address> {
|
||||
self.0.new_address().await.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub async fn transaction_fee(&self, txid: Txid) -> Result<Amount> {
|
||||
let fee = self
|
||||
.0
|
||||
.get_wallet_transaction(txid)
|
||||
.await
|
||||
.map(|res| {
|
||||
res.fee.map(|signed_amount| {
|
||||
signed_amount
|
||||
.abs()
|
||||
.to_unsigned()
|
||||
.expect("Absolute value is always positive")
|
||||
})
|
||||
})?
|
||||
.context("Rpc response did not contain a fee")?;
|
||||
|
||||
Ok(fee)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn make_wallet(
|
||||
name: &str,
|
||||
bitcoind: &Bitcoind<'_>,
|
||||
fund_amount: Amount,
|
||||
) -> Result<Wallet> {
|
||||
let wallet = Wallet::new(name, &bitcoind.node_url).await?;
|
||||
let buffer = Amount::from_btc(1.0).unwrap();
|
||||
let amount = fund_amount + buffer;
|
||||
|
||||
let address = wallet.0.new_address().await.unwrap();
|
||||
|
||||
bitcoind.mint(address, amount).await.unwrap();
|
||||
|
||||
Ok(wallet)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BuildTxLockPsbt for Wallet {
|
||||
async fn build_tx_lock_psbt(
|
||||
&self,
|
||||
output_address: Address,
|
||||
output_amount: Amount,
|
||||
) -> Result<PartiallySignedTransaction> {
|
||||
let psbt = self.0.fund_psbt(output_address, output_amount).await?;
|
||||
let as_hex = base64::decode(psbt)?;
|
||||
|
||||
let psbt = bitcoin::consensus::deserialize(&as_hex)?;
|
||||
|
||||
Ok(psbt)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SignTxLock for Wallet {
|
||||
async fn sign_tx_lock(&self, tx_lock: TxLock) -> Result<Transaction> {
|
||||
let psbt = PartiallySignedTransaction::from(tx_lock);
|
||||
|
||||
let psbt = bitcoin::consensus::serialize(&psbt);
|
||||
let as_base64 = base64::encode(psbt);
|
||||
|
||||
let psbt = self.0.wallet_process_psbt(PsbtBase64(as_base64)).await?;
|
||||
let PsbtBase64(signed_psbt) = PsbtBase64::from(psbt);
|
||||
|
||||
let as_hex = base64::decode(signed_psbt)?;
|
||||
let psbt: PartiallySignedTransaction = bitcoin::consensus::deserialize(&as_hex)?;
|
||||
|
||||
let tx = psbt.extract_tx();
|
||||
|
||||
Ok(tx)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BroadcastSignedTransaction for Wallet {
|
||||
async fn broadcast_signed_transaction(&self, transaction: Transaction) -> Result<Txid> {
|
||||
let txid = self.0.send_raw_transaction(transaction).await?;
|
||||
|
||||
// TODO: Instead of guessing how long it will take for the transaction to be
|
||||
// mined we should ask bitcoind for the number of confirmations on `txid`
|
||||
|
||||
// give time for transaction to be mined
|
||||
time::delay_for(Duration::from_millis(1100)).await;
|
||||
|
||||
Ok(txid)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WatchForRawTransaction for Wallet {
|
||||
async fn watch_for_raw_transaction(&self, txid: Txid) -> Transaction {
|
||||
(|| async { Ok(self.0.get_raw_transaction(txid).await?) })
|
||||
.retry(ConstantBackoff::new(Duration::from_secs(1)))
|
||||
.await
|
||||
.expect("transient errors to be retried")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BlockHeight for Wallet {
|
||||
async fn block_height(&self) -> u32 {
|
||||
(|| async { Ok(self.0.client.getblockcount().await?) })
|
||||
.retry(ConstantBackoff::new(Duration::from_secs(1)))
|
||||
.await
|
||||
.expect("transient errors to be retried")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TransactionBlockHeight for Wallet {
|
||||
async fn transaction_block_height(&self, txid: Txid) -> u32 {
|
||||
#[derive(Debug)]
|
||||
enum Error {
|
||||
Io,
|
||||
NotYetMined,
|
||||
}
|
||||
|
||||
(|| async {
|
||||
let block_height = self
|
||||
.0
|
||||
.transaction_block_height(txid)
|
||||
.await
|
||||
.map_err(|_| backoff::Error::Transient(Error::Io))?;
|
||||
|
||||
let block_height =
|
||||
block_height.ok_or_else(|| backoff::Error::Transient(Error::NotYetMined))?;
|
||||
|
||||
Result::<_, backoff::Error<Error>>::Ok(block_height)
|
||||
})
|
||||
.retry(ConstantBackoff::new(Duration::from_secs(1)))
|
||||
.await
|
||||
.expect("transient errors to be retried")
|
||||
}
|
||||
}
|
||||
|
||||
impl Network for Wallet {
|
||||
fn get_network(&self) -> bitcoin::Network {
|
||||
bitcoin::Network::Regtest
|
||||
}
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
pub mod bitcoin;
|
||||
pub mod monero;
|
@ -1,126 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use backoff::{backoff::Constant as ConstantBackoff, future::FutureOperation as _};
|
||||
use monero_harness::rpc::wallet;
|
||||
use std::{str::FromStr, time::Duration};
|
||||
use xmr_btc::monero::{
|
||||
Address, Amount, CreateWalletForOutput, InsufficientFunds, Network, PrivateKey, PrivateViewKey,
|
||||
PublicKey, PublicViewKey, Transfer, TransferProof, TxHash, WatchForTransfer,
|
||||
};
|
||||
|
||||
pub struct Wallet(pub wallet::Client);
|
||||
|
||||
impl Wallet {
|
||||
/// Get the balance of the primary account.
|
||||
pub async fn get_balance(&self) -> Result<Amount> {
|
||||
let amount = self.0.get_balance(0).await?;
|
||||
|
||||
Ok(Amount::from_piconero(amount))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Transfer for Wallet {
|
||||
async fn transfer(
|
||||
&self,
|
||||
public_spend_key: PublicKey,
|
||||
public_view_key: PublicViewKey,
|
||||
amount: Amount,
|
||||
) -> Result<(TransferProof, Amount)> {
|
||||
let destination_address =
|
||||
Address::standard(Network::Mainnet, public_spend_key, public_view_key.into());
|
||||
|
||||
let res = self
|
||||
.0
|
||||
.transfer(0, amount.as_piconero(), &destination_address.to_string())
|
||||
.await?;
|
||||
|
||||
let tx_hash = TxHash(res.tx_hash);
|
||||
let tx_key = PrivateKey::from_str(&res.tx_key)?;
|
||||
|
||||
let fee = Amount::from_piconero(res.fee);
|
||||
|
||||
Ok((TransferProof::new(tx_hash, tx_key), fee))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CreateWalletForOutput for Wallet {
|
||||
async fn create_and_load_wallet_for_output(
|
||||
&self,
|
||||
private_spend_key: PrivateKey,
|
||||
private_view_key: PrivateViewKey,
|
||||
) -> Result<()> {
|
||||
let public_spend_key = PublicKey::from_private_key(&private_spend_key);
|
||||
let public_view_key = PublicKey::from_private_key(&private_view_key.into());
|
||||
|
||||
let address = Address::standard(Network::Mainnet, public_spend_key, public_view_key);
|
||||
|
||||
let _ = self
|
||||
.0
|
||||
.generate_from_keys(
|
||||
&address.to_string(),
|
||||
&private_spend_key.to_string(),
|
||||
&PrivateKey::from(private_view_key).to_string(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WatchForTransfer for Wallet {
|
||||
async fn watch_for_transfer(
|
||||
&self,
|
||||
public_spend_key: PublicKey,
|
||||
public_view_key: PublicViewKey,
|
||||
transfer_proof: TransferProof,
|
||||
expected_amount: Amount,
|
||||
expected_confirmations: u32,
|
||||
) -> Result<(), InsufficientFunds> {
|
||||
enum Error {
|
||||
TxNotFound,
|
||||
InsufficientConfirmations,
|
||||
InsufficientFunds { expected: Amount, actual: Amount },
|
||||
}
|
||||
|
||||
let address = Address::standard(Network::Mainnet, public_spend_key, public_view_key.into());
|
||||
|
||||
let res = (|| async {
|
||||
// NOTE: Currently, this is conflating IO errors with the transaction not being
|
||||
// in the blockchain yet, or not having enough confirmations on it. All these
|
||||
// errors warrant a retry, but the strategy should probably differ per case
|
||||
let proof = self
|
||||
.0
|
||||
.check_tx_key(
|
||||
&String::from(transfer_proof.tx_hash()),
|
||||
&transfer_proof.tx_key().to_string(),
|
||||
&address.to_string(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| backoff::Error::Transient(Error::TxNotFound))?;
|
||||
|
||||
if proof.received != expected_amount.as_piconero() {
|
||||
return Err(backoff::Error::Permanent(Error::InsufficientFunds {
|
||||
expected: expected_amount,
|
||||
actual: Amount::from_piconero(proof.received),
|
||||
}));
|
||||
}
|
||||
|
||||
if proof.confirmations < expected_confirmations {
|
||||
return Err(backoff::Error::Transient(Error::InsufficientConfirmations));
|
||||
}
|
||||
|
||||
Ok(proof)
|
||||
})
|
||||
.retry(ConstantBackoff::new(Duration::from_secs(1)))
|
||||
.await;
|
||||
|
||||
if let Err(Error::InsufficientFunds { expected, actual }) = res {
|
||||
return Err(InsufficientFunds { expected, actual });
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue