Sweep all from generated wallet to user wallet

The default implementation for the command was removed because it does not
add additional value if we have a mandatory parameter anyway.
This commit is contained in:
Daniel Karzel 2021-03-02 22:07:48 +11:00
parent 5111a12706
commit 66c8401c95
9 changed files with 166 additions and 40 deletions

View File

@ -147,6 +147,28 @@ impl Client {
Ok(()) Ok(())
} }
/// Opens a wallet using `filename`.
pub async fn close_wallet(&self) -> Result<()> {
let request = Request::new("close_wallet", "");
let response = self
.inner
.post(self.url.clone())
.json(&request)
.send()
.await?
.text()
.await?;
debug!("close wallet RPC response: {}", response);
if response.contains("error") {
bail!("Failed to close wallet")
}
Ok(())
}
/// Creates a wallet using `filename`. /// Creates a wallet using `filename`.
pub async fn create_wallet(&self, filename: &str) -> Result<()> { pub async fn create_wallet(&self, filename: &str) -> Result<()> {
let params = CreateWalletParams { let params = CreateWalletParams {
@ -313,6 +335,28 @@ impl Client {
let r: Response<Refreshed> = serde_json::from_str(&response)?; let r: Response<Refreshed> = serde_json::from_str(&response)?;
Ok(r.result) Ok(r.result)
} }
/// Transfers the complete balance of the account to `address`.
pub async fn sweep_all(&self, address: &str) -> Result<SweepAll> {
let params = SweepAllParams {
address: address.into(),
};
let request = Request::new("sweep_all", params);
let response = self
.inner
.post(self.url.clone())
.json(&request)
.send()
.await?
.text()
.await?;
debug!("sweep_all RPC response: {}", response);
let r: Response<SweepAll> = serde_json::from_str(&response)?;
Ok(r.result)
}
} }
#[derive(Serialize, Debug, Clone)] #[derive(Serialize, Debug, Clone)]
@ -453,3 +497,41 @@ pub struct Refreshed {
pub blocks_fetched: u32, pub blocks_fetched: u32,
pub received_money: bool, pub received_money: bool,
} }
#[derive(Debug, Clone, Serialize)]
pub struct SweepAllParams {
pub address: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SweepAll {
amount_list: Vec<u64>,
fee_list: Vec<u64>,
multisig_txset: String,
pub tx_hash_list: Vec<String>,
unsigned_txset: String,
weight_list: Vec<u32>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_deserialize_sweep_all_response() {
let response = r#"{
"id": "0",
"jsonrpc": "2.0",
"result": {
"amount_list": [29921410000],
"fee_list": [78590000],
"multisig_txset": "",
"tx_hash_list": ["c1d8cfa87d445c1915a59d67be3e93ba8a29018640cf69b465f07b1840a8f8c8"],
"unsigned_txset": "",
"weight_list": [1448]
}
}"#;
let _: Response<SweepAll> = serde_json::from_str(&response).unwrap();
}
}

View File

@ -102,8 +102,9 @@ async fn main() -> Result<()> {
.run(monero_network, "stagenet.community.xmr.to") .run(monero_network, "stagenet.community.xmr.to")
.await?; .await?;
match args.cmd.unwrap_or_default() { match args.cmd {
Command::BuyXmr { Command::BuyXmr {
receive_monero_address,
alice_peer_id, alice_peer_id,
alice_addr, alice_addr,
} => { } => {
@ -153,6 +154,7 @@ async fn main() -> Result<()> {
Arc::new(monero_wallet), Arc::new(monero_wallet),
execution_params, execution_params,
event_loop_handle, event_loop_handle,
receive_monero_address,
) )
.with_init_params(send_bitcoin) .with_init_params(send_bitcoin)
.build()?; .build()?;
@ -180,6 +182,7 @@ async fn main() -> Result<()> {
table.printstd(); table.printstd();
} }
Command::Resume { Command::Resume {
receive_monero_address,
swap_id, swap_id,
alice_peer_id, alice_peer_id,
alice_addr, alice_addr,
@ -205,6 +208,7 @@ async fn main() -> Result<()> {
Arc::new(monero_wallet), Arc::new(monero_wallet),
execution_params, execution_params,
event_loop_handle, event_loop_handle,
receive_monero_address,
) )
.build()?; .build()?;

View File

@ -18,13 +18,16 @@ pub struct Arguments {
pub debug: bool, pub debug: bool,
#[structopt(subcommand)] #[structopt(subcommand)]
pub cmd: Option<Command>, pub cmd: Command,
} }
#[derive(structopt::StructOpt, Debug)] #[derive(structopt::StructOpt, Debug)]
#[structopt(name = "xmr_btc-swap", about = "XMR BTC atomic swap")] #[structopt(name = "xmr_btc-swap", about = "XMR BTC atomic swap")]
pub enum Command { pub enum Command {
BuyXmr { BuyXmr {
#[structopt(long = "receive-address")]
receive_monero_address: monero::Address,
#[structopt(long = "connect-peer-id", default_value = DEFAULT_ALICE_PEER_ID)] #[structopt(long = "connect-peer-id", default_value = DEFAULT_ALICE_PEER_ID)]
alice_peer_id: PeerId, alice_peer_id: PeerId,
@ -36,6 +39,9 @@ pub enum Command {
}, },
History, History,
Resume { Resume {
#[structopt(long = "receive-address")]
receive_monero_address: monero::Address,
#[structopt(long = "swap-id")] #[structopt(long = "swap-id")]
swap_id: Uuid, swap_id: Uuid,
@ -66,22 +72,9 @@ pub enum Command {
}, },
} }
impl Default for Command {
fn default() -> Self {
Self::BuyXmr {
alice_peer_id: DEFAULT_ALICE_PEER_ID
.parse()
.expect("default alice peer id str is a valid Multiaddr>"),
alice_addr: DEFAULT_ALICE_MULTIADDR
.parse()
.expect("default alice multiaddr str is a valid PeerId"),
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::cli::command::{Command, DEFAULT_ALICE_MULTIADDR, DEFAULT_ALICE_PEER_ID}; use crate::cli::command::{DEFAULT_ALICE_MULTIADDR, DEFAULT_ALICE_PEER_ID};
use libp2p::{core::Multiaddr, PeerId}; use libp2p::{core::Multiaddr, PeerId};
#[test] #[test]
@ -97,9 +90,4 @@ mod tests {
.parse::<Multiaddr>() .parse::<Multiaddr>()
.expect("default alice multiaddr str is a valid Multiaddr>"); .expect("default alice multiaddr str is a valid Multiaddr>");
} }
#[test]
fn default_command_success() {
Command::default();
}
} }

View File

@ -91,8 +91,7 @@ mod testnet {
pub static BITCOIN_AVG_BLOCK_TIME: Lazy<Duration> = Lazy::new(|| Duration::from_secs(5 * 60)); pub static BITCOIN_AVG_BLOCK_TIME: Lazy<Duration> = Lazy::new(|| Duration::from_secs(5 * 60));
// This does not reflect recommended values for mainnet! pub static MONERO_FINALITY_CONFIRMATIONS: u32 = 10;
pub static MONERO_FINALITY_CONFIRMATIONS: u32 = 5;
// This does not reflect recommended values for mainnet! // This does not reflect recommended values for mainnet!
pub static BITCOIN_CANCEL_TIMELOCK: CancelTimelock = CancelTimelock::new(12); pub static BITCOIN_CANCEL_TIMELOCK: CancelTimelock = CancelTimelock::new(12);
@ -109,7 +108,7 @@ mod regtest {
pub static BITCOIN_AVG_BLOCK_TIME: Lazy<Duration> = Lazy::new(|| Duration::from_secs(5)); pub static BITCOIN_AVG_BLOCK_TIME: Lazy<Duration> = Lazy::new(|| Duration::from_secs(5));
pub static MONERO_FINALITY_CONFIRMATIONS: u32 = 1; pub static MONERO_FINALITY_CONFIRMATIONS: u32 = 10;
pub static BITCOIN_CANCEL_TIMELOCK: CancelTimelock = CancelTimelock::new(100); pub static BITCOIN_CANCEL_TIMELOCK: CancelTimelock = CancelTimelock::new(100);

View File

@ -1,7 +1,7 @@
pub mod wallet; pub mod wallet;
mod wallet_rpc; mod wallet_rpc;
pub use ::monero::{Network, PrivateKey, PublicKey}; pub use ::monero::{Address, Network, PrivateKey, PublicKey};
pub use curve25519_dalek::scalar::Scalar; pub use curve25519_dalek::scalar::Scalar;
pub use wallet::Wallet; pub use wallet::Wallet;
pub use wallet_rpc::{WalletRpc, WalletRpcProcess}; pub use wallet_rpc::{WalletRpc, WalletRpcProcess};
@ -10,7 +10,6 @@ use crate::bitcoin;
use ::bitcoin::hashes::core::fmt::Formatter; use ::bitcoin::hashes::core::fmt::Formatter;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use monero::Address;
use monero_rpc::wallet::{BlockHeight, Refreshed}; use monero_rpc::wallet::{BlockHeight, Refreshed};
use rand::{CryptoRng, RngCore}; use rand::{CryptoRng, RngCore};
use rust_decimal::{ use rust_decimal::{

View File

@ -61,6 +61,15 @@ impl Wallet {
self.inner.lock().await.refresh().await self.inner.lock().await.refresh().await
} }
pub async fn sweep_all(&self, address: Address) -> Result<Vec<TxHash>> {
self.inner
.lock()
.await
.sweep_all(address.to_string().as_str())
.await
.map(|sweep_all| sweep_all.tx_hash_list.into_iter().map(TxHash).collect())
}
pub fn static_tx_fee_estimate(&self) -> Amount { pub fn static_tx_fee_estimate(&self) -> Amount {
// Median tx fees on Monero as found here: https://www.monero.how/monero-transaction-fees, 0.000_015 * 2 (to be on the safe side) // Median tx fees on Monero as found here: https://www.monero.how/monero-transaction-fees, 0.000_015 * 2 (to be on the safe side)
Amount::from_monero(0.000_03f64).expect("static fee to be convertible without problems") Amount::from_monero(0.000_03f64).expect("static fee to be convertible without problems")
@ -112,10 +121,13 @@ impl CreateWalletForOutput for Wallet {
let address = Address::standard(self.network, public_spend_key, public_view_key); let address = Address::standard(self.network, public_spend_key, public_view_key);
let _ = self let wallet = self.inner.lock().await;
.inner
.lock() // Properly close the wallet before generating the other wallet to ensure that
.await // it saves its state correctly
let _ = wallet.close_wallet().await?;
let _ = wallet
.generate_from_keys( .generate_from_keys(
&address.to_string(), &address.to_string(),
&private_spend_key.to_string(), &private_spend_key.to_string(),
@ -143,6 +155,10 @@ impl CreateWalletForOutputThenReloadWallet for Wallet {
let wallet = self.inner.lock().await; let wallet = self.inner.lock().await;
// Properly close the wallet before generating the other wallet to ensure that
// it saves its state correctly
let _ = wallet.close_wallet().await?;
let _ = wallet let _ = wallet
.generate_from_keys( .generate_from_keys(
&address.to_string(), &address.to_string(),

View File

@ -44,6 +44,7 @@ pub struct Swap {
pub monero_wallet: Arc<monero::Wallet>, pub monero_wallet: Arc<monero::Wallet>,
pub execution_params: ExecutionParams, pub execution_params: ExecutionParams,
pub swap_id: Uuid, pub swap_id: Uuid,
pub receive_monero_address: ::monero::Address,
} }
pub struct Builder { pub struct Builder {
@ -57,6 +58,8 @@ pub struct Builder {
execution_params: ExecutionParams, execution_params: ExecutionParams,
event_loop_handle: bob::EventLoopHandle, event_loop_handle: bob::EventLoopHandle,
receive_monero_address: ::monero::Address,
} }
enum InitParams { enum InitParams {
@ -73,6 +76,7 @@ impl Builder {
monero_wallet: Arc<monero::Wallet>, monero_wallet: Arc<monero::Wallet>,
execution_params: ExecutionParams, execution_params: ExecutionParams,
event_loop_handle: bob::EventLoopHandle, event_loop_handle: bob::EventLoopHandle,
receive_monero_address: ::monero::Address,
) -> Self { ) -> Self {
Self { Self {
swap_id, swap_id,
@ -82,6 +86,7 @@ impl Builder {
init_params: InitParams::None, init_params: InitParams::None,
execution_params, execution_params,
event_loop_handle, event_loop_handle,
receive_monero_address,
} }
} }
@ -106,6 +111,7 @@ impl Builder {
monero_wallet: self.monero_wallet.clone(), monero_wallet: self.monero_wallet.clone(),
swap_id: self.swap_id, swap_id: self.swap_id,
execution_params: self.execution_params, execution_params: self.execution_params,
receive_monero_address: self.receive_monero_address,
}) })
} }
} }

View File

@ -43,6 +43,7 @@ pub async fn run_until(
swap.monero_wallet, swap.monero_wallet,
swap.swap_id, swap.swap_id,
swap.execution_params, swap.execution_params,
swap.receive_monero_address,
) )
.await .await
} }
@ -59,6 +60,7 @@ async fn run_until_internal(
monero_wallet: Arc<monero::Wallet>, monero_wallet: Arc<monero::Wallet>,
swap_id: Uuid, swap_id: Uuid,
execution_params: ExecutionParams, execution_params: ExecutionParams,
receive_monero_address: monero::Address,
) -> Result<BobState> { ) -> Result<BobState> {
trace!("Current state: {}", state); trace!("Current state: {}", state);
if is_target_state(&state) { if is_target_state(&state) {
@ -90,6 +92,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -111,6 +114,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -159,6 +163,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -213,6 +218,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -255,6 +261,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -290,6 +297,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -297,6 +305,11 @@ async fn run_until_internal(
// Bob redeems XMR using revealed s_a // Bob redeems XMR using revealed s_a
state.claim_xmr(monero_wallet.as_ref()).await?; state.claim_xmr(monero_wallet.as_ref()).await?;
// Ensure that the generated wallet is synced so we have a proper balance
monero_wallet.refresh().await?;
// Sweep (transfer all funds) to the given address
monero_wallet.sweep_all(receive_monero_address).await?;
let state = BobState::XmrRedeemed { let state = BobState::XmrRedeemed {
tx_lock_id: state.tx_lock_id(), tx_lock_id: state.tx_lock_id(),
}; };
@ -311,6 +324,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -336,6 +350,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }
@ -367,6 +382,7 @@ async fn run_until_internal(
monero_wallet, monero_wallet,
swap_id, swap_id,
execution_params, execution_params,
receive_monero_address,
) )
.await .await
} }

View File

@ -22,6 +22,7 @@ use swap::{
execution_params, execution_params,
execution_params::{ExecutionParams, GetExecutionParams}, execution_params::{ExecutionParams, GetExecutionParams},
monero, monero,
monero::OpenWallet,
protocol::{alice, alice::AliceState, bob, bob::BobState}, protocol::{alice, alice::AliceState, bob, bob::BobState},
seed::Seed, seed::Seed,
}; };
@ -56,15 +57,18 @@ struct BobParams {
} }
impl BobParams { impl BobParams {
pub fn builder(&self, event_loop_handle: bob::EventLoopHandle) -> bob::Builder { pub async fn builder(&self, event_loop_handle: bob::EventLoopHandle) -> Result<bob::Builder> {
bob::Builder::new( let receive_address = self.monero_wallet.get_main_address().await?;
Ok(bob::Builder::new(
Database::open(&self.db_path.clone().as_path()).unwrap(), Database::open(&self.db_path.clone().as_path()).unwrap(),
self.swap_id, self.swap_id,
self.bitcoin_wallet.clone(), self.bitcoin_wallet.clone(),
self.monero_wallet.clone(), self.monero_wallet.clone(),
self.execution_params, self.execution_params,
event_loop_handle, event_loop_handle,
) receive_address,
))
} }
pub fn new_eventloop(&self) -> Result<(bob::EventLoop, bob::EventLoopHandle)> { pub fn new_eventloop(&self) -> Result<(bob::EventLoop, bob::EventLoopHandle)> {
@ -109,6 +113,8 @@ impl TestContext {
let swap = self let swap = self
.bob_params .bob_params
.builder(event_loop_handle) .builder(event_loop_handle)
.await
.unwrap()
.with_init_params(self.btc_amount) .with_init_params(self.btc_amount)
.build() .build()
.unwrap(); .unwrap();
@ -126,7 +132,13 @@ impl TestContext {
let (event_loop, event_loop_handle) = self.bob_params.new_eventloop().unwrap(); let (event_loop, event_loop_handle) = self.bob_params.new_eventloop().unwrap();
let swap = self.bob_params.builder(event_loop_handle).build().unwrap(); let swap = self
.bob_params
.builder(event_loop_handle)
.await
.unwrap()
.build()
.unwrap();
let join_handle = tokio::spawn(event_loop.run()); let join_handle = tokio::spawn(event_loop.run());
@ -239,13 +251,15 @@ impl TestContext {
self.bob_starting_balances.btc - self.btc_amount - lock_tx_bitcoin_fee self.bob_starting_balances.btc - self.btc_amount - lock_tx_bitcoin_fee
); );
// unload the generated wallet by opening the original wallet
self.bob_monero_wallet.open().await.unwrap();
// refresh the original wallet to make sure the balance is caught up
self.bob_monero_wallet.refresh().await.unwrap();
// Ensure that Bob's balance is refreshed as we use a newly created wallet // Ensure that Bob's balance is refreshed as we use a newly created wallet
self.bob_monero_wallet.as_ref().refresh().await.unwrap(); self.bob_monero_wallet.as_ref().refresh().await.unwrap();
let xmr_balance_after_swap = self.bob_monero_wallet.as_ref().get_balance().await.unwrap(); let xmr_balance_after_swap = self.bob_monero_wallet.as_ref().get_balance().await.unwrap();
assert_eq!( assert!(xmr_balance_after_swap > self.bob_starting_balances.xmr);
xmr_balance_after_swap,
self.bob_starting_balances.xmr + self.xmr_amount
);
} }
pub async fn assert_bob_refunded(&self, state: BobState) { pub async fn assert_bob_refunded(&self, state: BobState) {
@ -685,18 +699,20 @@ pub fn init_tracing() -> DefaultGuard {
let global_filter = tracing::Level::WARN; let global_filter = tracing::Level::WARN;
let swap_filter = tracing::Level::DEBUG; let swap_filter = tracing::Level::DEBUG;
let xmr_btc_filter = tracing::Level::DEBUG; let xmr_btc_filter = tracing::Level::DEBUG;
let monero_harness_filter = tracing::Level::INFO; let monero_rpc_filter = tracing::Level::DEBUG;
let monero_harness_filter = tracing::Level::DEBUG;
let bitcoin_harness_filter = tracing::Level::INFO; let bitcoin_harness_filter = tracing::Level::INFO;
let testcontainers_filter = tracing::Level::DEBUG; let testcontainers_filter = tracing::Level::DEBUG;
use tracing_subscriber::util::SubscriberInitExt as _; use tracing_subscriber::util::SubscriberInitExt as _;
tracing_subscriber::fmt() tracing_subscriber::fmt()
.with_env_filter(format!( .with_env_filter(format!(
"{},swap={},xmr_btc={},monero_harness={},bitcoin_harness={},testcontainers={}", "{},swap={},xmr_btc={},monero_harness={},monero_rpc={},bitcoin_harness={},testcontainers={}",
global_filter, global_filter,
swap_filter, swap_filter,
xmr_btc_filter, xmr_btc_filter,
monero_harness_filter, monero_harness_filter,
monero_rpc_filter,
bitcoin_harness_filter, bitcoin_harness_filter,
testcontainers_filter testcontainers_filter
)) ))