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.
pull/261/head
Daniel Karzel 3 years ago
parent 5111a12706
commit 66c8401c95

@ -147,6 +147,28 @@ impl Client {
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`.
pub async fn create_wallet(&self, filename: &str) -> Result<()> {
let params = CreateWalletParams {
@ -313,6 +335,28 @@ impl Client {
let r: Response<Refreshed> = serde_json::from_str(&response)?;
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)]
@ -453,3 +497,41 @@ pub struct Refreshed {
pub blocks_fetched: u32,
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();
}
}

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

@ -18,13 +18,16 @@ pub struct Arguments {
pub debug: bool,
#[structopt(subcommand)]
pub cmd: Option<Command>,
pub cmd: Command,
}
#[derive(structopt::StructOpt, Debug)]
#[structopt(name = "xmr_btc-swap", about = "XMR BTC atomic swap")]
pub enum Command {
BuyXmr {
#[structopt(long = "receive-address")]
receive_monero_address: monero::Address,
#[structopt(long = "connect-peer-id", default_value = DEFAULT_ALICE_PEER_ID)]
alice_peer_id: PeerId,
@ -36,6 +39,9 @@ pub enum Command {
},
History,
Resume {
#[structopt(long = "receive-address")]
receive_monero_address: monero::Address,
#[structopt(long = "swap-id")]
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)]
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};
#[test]
@ -97,9 +90,4 @@ mod tests {
.parse::<Multiaddr>()
.expect("default alice multiaddr str is a valid Multiaddr>");
}
#[test]
fn default_command_success() {
Command::default();
}
}

@ -91,8 +91,7 @@ mod testnet {
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 = 5;
pub static MONERO_FINALITY_CONFIRMATIONS: u32 = 10;
// This does not reflect recommended values for mainnet!
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 MONERO_FINALITY_CONFIRMATIONS: u32 = 1;
pub static MONERO_FINALITY_CONFIRMATIONS: u32 = 10;
pub static BITCOIN_CANCEL_TIMELOCK: CancelTimelock = CancelTimelock::new(100);

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

@ -61,6 +61,15 @@ impl Wallet {
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 {
// 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")
@ -112,10 +121,13 @@ impl CreateWalletForOutput for Wallet {
let address = Address::standard(self.network, public_spend_key, public_view_key);
let _ = 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
.generate_from_keys(
&address.to_string(),
&private_spend_key.to_string(),
@ -143,6 +155,10 @@ impl CreateWalletForOutputThenReloadWallet for Wallet {
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
.generate_from_keys(
&address.to_string(),

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

@ -43,6 +43,7 @@ pub async fn run_until(
swap.monero_wallet,
swap.swap_id,
swap.execution_params,
swap.receive_monero_address,
)
.await
}
@ -59,6 +60,7 @@ async fn run_until_internal(
monero_wallet: Arc<monero::Wallet>,
swap_id: Uuid,
execution_params: ExecutionParams,
receive_monero_address: monero::Address,
) -> Result<BobState> {
trace!("Current state: {}", state);
if is_target_state(&state) {
@ -90,6 +92,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -111,6 +114,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -159,6 +163,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -213,6 +218,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -255,6 +261,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -290,6 +297,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -297,6 +305,11 @@ async fn run_until_internal(
// Bob redeems XMR using revealed s_a
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 {
tx_lock_id: state.tx_lock_id(),
};
@ -311,6 +324,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -336,6 +350,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}
@ -367,6 +382,7 @@ async fn run_until_internal(
monero_wallet,
swap_id,
execution_params,
receive_monero_address,
)
.await
}

@ -22,6 +22,7 @@ use swap::{
execution_params,
execution_params::{ExecutionParams, GetExecutionParams},
monero,
monero::OpenWallet,
protocol::{alice, alice::AliceState, bob, bob::BobState},
seed::Seed,
};
@ -56,15 +57,18 @@ struct BobParams {
}
impl BobParams {
pub fn builder(&self, event_loop_handle: bob::EventLoopHandle) -> bob::Builder {
bob::Builder::new(
pub async fn builder(&self, event_loop_handle: bob::EventLoopHandle) -> Result<bob::Builder> {
let receive_address = self.monero_wallet.get_main_address().await?;
Ok(bob::Builder::new(
Database::open(&self.db_path.clone().as_path()).unwrap(),
self.swap_id,
self.bitcoin_wallet.clone(),
self.monero_wallet.clone(),
self.execution_params,
event_loop_handle,
)
receive_address,
))
}
pub fn new_eventloop(&self) -> Result<(bob::EventLoop, bob::EventLoopHandle)> {
@ -109,6 +113,8 @@ impl TestContext {
let swap = self
.bob_params
.builder(event_loop_handle)
.await
.unwrap()
.with_init_params(self.btc_amount)
.build()
.unwrap();
@ -126,7 +132,13 @@ impl TestContext {
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());
@ -239,13 +251,15 @@ impl TestContext {
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
self.bob_monero_wallet.as_ref().refresh().await.unwrap();
let xmr_balance_after_swap = self.bob_monero_wallet.as_ref().get_balance().await.unwrap();
assert_eq!(
xmr_balance_after_swap,
self.bob_starting_balances.xmr + self.xmr_amount
);
assert!(xmr_balance_after_swap > self.bob_starting_balances.xmr);
}
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 swap_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 testcontainers_filter = tracing::Level::DEBUG;
use tracing_subscriber::util::SubscriberInitExt as _;
tracing_subscriber::fmt()
.with_env_filter(format!(
"{},swap={},xmr_btc={},monero_harness={},bitcoin_harness={},testcontainers={}",
"{},swap={},xmr_btc={},monero_harness={},monero_rpc={},bitcoin_harness={},testcontainers={}",
global_filter,
swap_filter,
xmr_btc_filter,
monero_harness_filter,
monero_rpc_filter,
bitcoin_harness_filter,
testcontainers_filter
))

Loading…
Cancel
Save