From 7213907a79c2488f243574efceaf9eaaa976e7ad Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Wed, 17 Mar 2021 13:18:49 +1100 Subject: [PATCH 1/4] Group bitcoin and monero fields together --- swap/src/execution_params.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/swap/src/execution_params.rs b/swap/src/execution_params.rs index db80d543..9eecb85a 100644 --- a/swap/src/execution_params.rs +++ b/swap/src/execution_params.rs @@ -7,10 +7,10 @@ pub struct ExecutionParams { pub bob_time_to_act: Duration, pub bitcoin_finality_confirmations: u32, pub bitcoin_avg_block_time: Duration, - pub monero_avg_block_time: Duration, - pub monero_finality_confirmations: u32, pub bitcoin_cancel_timelock: CancelTimelock, pub bitcoin_punish_timelock: PunishTimelock, + pub monero_avg_block_time: Duration, + pub monero_finality_confirmations: u32, } pub trait GetExecutionParams { @@ -32,10 +32,10 @@ impl GetExecutionParams for Mainnet { bob_time_to_act: 10.minutes(), bitcoin_finality_confirmations: 3, bitcoin_avg_block_time: 10.minutes(), - monero_avg_block_time: 2.minutes(), - monero_finality_confirmations: 15, bitcoin_cancel_timelock: CancelTimelock::new(72), bitcoin_punish_timelock: PunishTimelock::new(72), + monero_avg_block_time: 2.minutes(), + monero_finality_confirmations: 15, } } } @@ -46,10 +46,10 @@ impl GetExecutionParams for Testnet { bob_time_to_act: 60.minutes(), bitcoin_finality_confirmations: 1, bitcoin_avg_block_time: 5.minutes(), - monero_avg_block_time: 2.minutes(), - monero_finality_confirmations: 10, bitcoin_cancel_timelock: CancelTimelock::new(12), bitcoin_punish_timelock: PunishTimelock::new(6), + monero_avg_block_time: 2.minutes(), + monero_finality_confirmations: 10, } } } @@ -60,10 +60,10 @@ impl GetExecutionParams for Regtest { bob_time_to_act: 30.seconds(), bitcoin_finality_confirmations: 1, bitcoin_avg_block_time: 5.seconds(), - monero_avg_block_time: 1.seconds(), - monero_finality_confirmations: 10, bitcoin_cancel_timelock: CancelTimelock::new(100), bitcoin_punish_timelock: PunishTimelock::new(50), + monero_avg_block_time: 1.seconds(), + monero_finality_confirmations: 10, } } } From bc43ed6ebd33fcd25e4051a70ee4d5ca7c32d5ba Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Wed, 17 Mar 2021 13:36:43 +1100 Subject: [PATCH 2/4] Pass execution params directly into wallet for initialization This reduces the amount of parameters that we need to pass in. --- swap/src/bin/asb.rs | 18 ++---- swap/src/bin/swap.rs | 93 ++++++++------------------- swap/src/bitcoin/wallet.rs | 12 ++-- swap/src/execution_params.rs | 8 +++ swap/src/monero/wallet.rs | 19 ++---- swap/src/protocol/alice.rs | 2 +- swap/src/protocol/alice/behaviour.rs | 4 +- swap/src/protocol/alice/event_loop.rs | 10 +-- swap/src/protocol/alice/state.rs | 6 +- swap/src/protocol/alice/swap.rs | 26 ++++---- swap/src/protocol/bob.rs | 10 +-- swap/src/protocol/bob/swap.rs | 32 ++++----- swap/tests/testutils/mod.rs | 24 ++++--- 13 files changed, 111 insertions(+), 153 deletions(-) diff --git a/swap/src/bin/asb.rs b/swap/src/bin/asb.rs index d11af5cb..a3f2b9c1 100644 --- a/swap/src/bin/asb.rs +++ b/swap/src/bin/asb.rs @@ -38,8 +38,6 @@ use tracing_subscriber::filter::LevelFilter; extern crate prettytable; const DEFAULT_WALLET_NAME: &str = "asb-wallet"; -const BITCOIN_NETWORK: bitcoin::Network = bitcoin::Network::Testnet; -const MONERO_NETWORK: monero::Network = monero::Network::Stagenet; #[tokio::main] async fn main() -> Result<()> { @@ -78,13 +76,13 @@ async fn main() -> Result<()> { let seed = Seed::from_file_or_generate(&config.data.dir) .expect("Could not retrieve/initialize seed"); - let execution_params = execution_params::Testnet::get_execution_params(); + let exec_params = execution_params::Testnet::get_execution_params(); let (bitcoin_wallet, monero_wallet) = init_wallets( config.clone(), &wallet_data_dir, - seed.derive_extended_private_key(BITCOIN_NETWORK)?, - execution_params, + seed.derive_extended_private_key(exec_params.bitcoin_network)?, + exec_params, ) .await?; @@ -98,7 +96,7 @@ async fn main() -> Result<()> { let (event_loop, mut swap_receiver) = EventLoop::new( config.network.listen, seed, - execution_params, + exec_params, Arc::new(bitcoin_wallet), Arc::new(monero_wallet), Arc::new(db), @@ -148,14 +146,13 @@ async fn init_wallets( config: Config, bitcoin_wallet_data_dir: &Path, key: impl DerivableKey + Clone, - execution_params: ExecutionParams, + exec_params: ExecutionParams, ) -> Result<(bitcoin::Wallet, monero::Wallet)> { let bitcoin_wallet = bitcoin::Wallet::new( config.bitcoin.electrum_rpc_url, - BITCOIN_NETWORK, - execution_params.bitcoin_finality_confirmations, bitcoin_wallet_data_dir, key, + exec_params, ) .await?; @@ -169,9 +166,8 @@ async fn init_wallets( let monero_wallet = monero::Wallet::new( config.monero.wallet_rpc_url.clone(), - MONERO_NETWORK, DEFAULT_WALLET_NAME.to_string(), - execution_params.monero_avg_block_time, + exec_params, ); // Setup the Monero wallet diff --git a/swap/src/bin/swap.rs b/swap/src/bin/swap.rs index dabed242..2d58b7d2 100644 --- a/swap/src/bin/swap.rs +++ b/swap/src/bin/swap.rs @@ -76,10 +76,7 @@ async fn main() -> Result<()> { let seed = Seed::from_file_or_generate(data_dir.as_path()).context("Failed to read in seed file")?; - // hardcode to testnet/stagenet - let bitcoin_network = bitcoin::Network::Testnet; - let monero_network = monero::Network::Stagenet; - let execution_params = execution_params::Testnet::get_execution_params(); + let exec_params = execution_params::Testnet::get_execution_params(); match args.cmd { Command::BuyXmr { @@ -95,29 +92,18 @@ async fn main() -> Result<()> { }, electrum_rpc_url, } => { - if receive_monero_address.network != monero_network { + if receive_monero_address.network != exec_params.monero_network { bail!( "Given monero address is on network {:?}, expected address on network {:?}", receive_monero_address.network, - monero_network + exec_params.monero_network ) } - let bitcoin_wallet = init_bitcoin_wallet( - bitcoin_network, - electrum_rpc_url, - seed, - data_dir.clone(), - execution_params, - ) - .await?; - let (monero_wallet, _process) = init_monero_wallet( - monero_network, - data_dir, - monero_daemon_host, - execution_params, - ) - .await?; + let bitcoin_wallet = + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir.clone(), exec_params).await?; + let (monero_wallet, _process) = + init_monero_wallet(data_dir, monero_daemon_host, exec_params).await?; let bitcoin_wallet = Arc::new(bitcoin_wallet); let (event_loop, mut event_loop_handle) = EventLoop::new( &seed.derive_libp2p_identity(), @@ -149,7 +135,7 @@ async fn main() -> Result<()> { Uuid::new_v4(), bitcoin_wallet.clone(), Arc::new(monero_wallet), - execution_params, + exec_params, event_loop_handle, receive_monero_address, ) @@ -192,25 +178,14 @@ async fn main() -> Result<()> { }, electrum_rpc_url, } => { - if receive_monero_address.network != monero_network { - bail!("The given monero address is on network {:?}, expected address of network {:?}.", receive_monero_address.network, monero_network) + if receive_monero_address.network != exec_params.monero_network { + bail!("The given monero address is on network {:?}, expected address of network {:?}.", receive_monero_address.network, exec_params.monero_network) } - let bitcoin_wallet = init_bitcoin_wallet( - bitcoin_network, - electrum_rpc_url, - seed, - data_dir.clone(), - execution_params, - ) - .await?; - let (monero_wallet, _process) = init_monero_wallet( - monero_network, - data_dir, - monero_daemon_host, - execution_params, - ) - .await?; + let bitcoin_wallet = + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir.clone(), exec_params).await?; + let (monero_wallet, _process) = + init_monero_wallet(data_dir, monero_daemon_host, exec_params).await?; let bitcoin_wallet = Arc::new(bitcoin_wallet); let (event_loop, event_loop_handle) = EventLoop::new( @@ -226,7 +201,7 @@ async fn main() -> Result<()> { swap_id, bitcoin_wallet.clone(), Arc::new(monero_wallet), - execution_params, + exec_params, event_loop_handle, receive_monero_address, ) @@ -247,14 +222,8 @@ async fn main() -> Result<()> { force, electrum_rpc_url, } => { - let bitcoin_wallet = init_bitcoin_wallet( - bitcoin_network, - electrum_rpc_url, - seed, - data_dir, - execution_params, - ) - .await?; + let bitcoin_wallet = + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir, exec_params).await?; let resume_state = db.get_state(swap_id)?.try_into_bob()?.into(); let cancel = @@ -278,14 +247,8 @@ async fn main() -> Result<()> { force, electrum_rpc_url, } => { - let bitcoin_wallet = init_bitcoin_wallet( - bitcoin_network, - electrum_rpc_url, - seed, - data_dir, - execution_params, - ) - .await?; + let bitcoin_wallet = + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir, exec_params).await?; let resume_state = db.get_state(swap_id)?.try_into_bob()?.into(); @@ -296,20 +259,18 @@ async fn main() -> Result<()> { } async fn init_bitcoin_wallet( - network: bitcoin::Network, electrum_rpc_url: Url, seed: Seed, data_dir: PathBuf, - execution_params: ExecutionParams, + exec_params: ExecutionParams, ) -> Result { let wallet_dir = data_dir.join("wallet"); let wallet = bitcoin::Wallet::new( electrum_rpc_url.clone(), - network, - execution_params.bitcoin_finality_confirmations, &wallet_dir, - seed.derive_extended_private_key(network)?, + seed.derive_extended_private_key(exec_params.bitcoin_network)?, + exec_params, ) .await .context("Failed to initialize Bitcoin wallet")?; @@ -320,24 +281,24 @@ async fn init_bitcoin_wallet( } async fn init_monero_wallet( - monero_network: monero::Network, data_dir: PathBuf, monero_daemon_host: String, - execution_params: ExecutionParams, + exec_params: ExecutionParams, ) -> Result<(monero::Wallet, monero::WalletRpcProcess)> { + let network = exec_params.monero_network; + const MONERO_BLOCKCHAIN_MONITORING_WALLET_NAME: &str = "swap-tool-blockchain-monitoring-wallet"; let monero_wallet_rpc = monero::WalletRpc::new(data_dir.join("monero")).await?; let monero_wallet_rpc_process = monero_wallet_rpc - .run(monero_network, monero_daemon_host.as_str()) + .run(network, monero_daemon_host.as_str()) .await?; let monero_wallet = monero::Wallet::new( monero_wallet_rpc_process.endpoint(), - monero_network, MONERO_BLOCKCHAIN_MONITORING_WALLET_NAME.to_string(), - execution_params.monero_avg_block_time, + exec_params, ); monero_wallet.open_or_create().await?; diff --git a/swap/src/bitcoin/wallet.rs b/swap/src/bitcoin/wallet.rs index 480bf68e..7b58c555 100644 --- a/swap/src/bitcoin/wallet.rs +++ b/swap/src/bitcoin/wallet.rs @@ -1,5 +1,6 @@ use crate::bitcoin::timelocks::BlockHeight; use crate::bitcoin::{Address, Amount, Transaction}; +use crate::execution_params::ExecutionParams; use ::bitcoin::util::psbt::PartiallySignedTransaction; use ::bitcoin::Txid; use anyhow::{anyhow, bail, Context, Result}; @@ -24,16 +25,15 @@ const SLED_TREE_NAME: &str = "default_tree"; pub struct Wallet { client: Arc>, wallet: Arc>>, - bitcoin_finality_confirmations: u32, + finality_confirmations: u32, } impl Wallet { pub async fn new( electrum_rpc_url: Url, - network: bitcoin::Network, - bitcoin_finality_confirmations: u32, wallet_dir: &Path, key: impl DerivableKey + Clone, + exec_params: ExecutionParams, ) -> Result { // Workaround for https://github.com/bitcoindevkit/rust-electrum-client/issues/47. let config = electrum_client::ConfigBuilder::default().retry(2).build(); @@ -47,7 +47,7 @@ impl Wallet { let bdk_wallet = bdk::Wallet::new( bdk::template::BIP84(key.clone(), KeychainKind::External), Some(bdk::template::BIP84(key, KeychainKind::Internal)), - network, + exec_params.bitcoin_network, db, ElectrumBlockchain::from(client), )?; @@ -60,7 +60,7 @@ impl Wallet { Ok(Self { wallet: Arc::new(Mutex::new(bdk_wallet)), client: Arc::new(Mutex::new(Client::new(electrum, interval)?)), - bitcoin_finality_confirmations, + finality_confirmations: exec_params.bitcoin_finality_confirmations, }) } @@ -248,7 +248,7 @@ impl Wallet { where T: Watchable, { - let conf_target = self.bitcoin_finality_confirmations; + let conf_target = self.finality_confirmations; let txid = tx.id(); tracing::info!(%txid, "Waiting for {} confirmation{} of Bitcoin {} transaction", conf_target, if conf_target > 1 { "s" } else { "" }, kind); diff --git a/swap/src/execution_params.rs b/swap/src/execution_params.rs index 9eecb85a..3479357c 100644 --- a/swap/src/execution_params.rs +++ b/swap/src/execution_params.rs @@ -9,8 +9,10 @@ pub struct ExecutionParams { pub bitcoin_avg_block_time: Duration, pub bitcoin_cancel_timelock: CancelTimelock, pub bitcoin_punish_timelock: PunishTimelock, + pub bitcoin_network: bitcoin::Network, pub monero_avg_block_time: Duration, pub monero_finality_confirmations: u32, + pub monero_network: monero::Network, } pub trait GetExecutionParams { @@ -34,8 +36,10 @@ impl GetExecutionParams for Mainnet { bitcoin_avg_block_time: 10.minutes(), bitcoin_cancel_timelock: CancelTimelock::new(72), bitcoin_punish_timelock: PunishTimelock::new(72), + bitcoin_network: bitcoin::Network::Bitcoin, monero_avg_block_time: 2.minutes(), monero_finality_confirmations: 15, + monero_network: monero::Network::Mainnet, } } } @@ -48,8 +52,10 @@ impl GetExecutionParams for Testnet { bitcoin_avg_block_time: 5.minutes(), bitcoin_cancel_timelock: CancelTimelock::new(12), bitcoin_punish_timelock: PunishTimelock::new(6), + bitcoin_network: bitcoin::Network::Testnet, monero_avg_block_time: 2.minutes(), monero_finality_confirmations: 10, + monero_network: monero::Network::Stagenet, } } } @@ -62,8 +68,10 @@ impl GetExecutionParams for Regtest { bitcoin_avg_block_time: 5.seconds(), bitcoin_cancel_timelock: CancelTimelock::new(100), bitcoin_punish_timelock: PunishTimelock::new(50), + bitcoin_network: bitcoin::Network::Regtest, monero_avg_block_time: 1.seconds(), monero_finality_confirmations: 10, + monero_network: monero::Network::Testnet, } } } diff --git a/swap/src/monero/wallet.rs b/swap/src/monero/wallet.rs index 67a139a8..59408177 100644 --- a/swap/src/monero/wallet.rs +++ b/swap/src/monero/wallet.rs @@ -1,10 +1,11 @@ +use crate::execution_params::ExecutionParams; use crate::monero::{ Amount, InsufficientFunds, PrivateViewKey, PublicViewKey, TransferProof, TxHash, }; use ::monero::{Address, Network, PrivateKey, PublicKey}; use anyhow::{Context, Result}; use monero_rpc::wallet; -use monero_rpc::wallet::{BlockHeight, CheckTxKey, Refreshed}; +use monero_rpc::wallet::{BlockHeight, CheckTxKey, Client, Refreshed}; use std::cmp::max; use std::future::Future; use std::str::FromStr; @@ -23,26 +24,20 @@ pub struct Wallet { } impl Wallet { - pub fn new(url: Url, network: Network, name: String, avg_block_time: Duration) -> Self { - Self { - inner: Mutex::new(wallet::Client::new(url)), - network, - name, - avg_block_time, - } + pub fn new(url: Url, name: String, exec_params: ExecutionParams) -> Self { + Self::new_with_client(Client::new(url), name, exec_params) } pub fn new_with_client( client: wallet::Client, - network: Network, name: String, - avg_block_time: Duration, + exec_params: ExecutionParams, ) -> Self { Self { inner: Mutex::new(client), - network, + network: exec_params.monero_network, name, - avg_block_time, + avg_block_time: exec_params.monero_avg_block_time, } } diff --git a/swap/src/protocol/alice.rs b/swap/src/protocol/alice.rs index f49b208e..07044e4b 100644 --- a/swap/src/protocol/alice.rs +++ b/swap/src/protocol/alice.rs @@ -28,7 +28,7 @@ pub struct Swap { pub event_loop_handle: EventLoopHandle, pub bitcoin_wallet: Arc, pub monero_wallet: Arc, - pub execution_params: ExecutionParams, + pub exec_params: ExecutionParams, pub swap_id: Uuid, pub db: Arc, } diff --git a/swap/src/protocol/alice/behaviour.rs b/swap/src/protocol/alice/behaviour.rs index c3790392..d4ff73f7 100644 --- a/swap/src/protocol/alice/behaviour.rs +++ b/swap/src/protocol/alice/behaviour.rs @@ -206,11 +206,11 @@ impl Behaviour { peer: PeerId, btc: bitcoin::Amount, xmr: monero::Amount, - execution_params: ExecutionParams, + exec_params: ExecutionParams, bitcoin_wallet: &bitcoin::Wallet, rng: &mut (impl RngCore + CryptoRng), ) -> Result<()> { - let state0 = State0::new(btc, xmr, execution_params, bitcoin_wallet, rng).await?; + let state0 = State0::new(btc, xmr, exec_params, bitcoin_wallet, rng).await?; tracing::info!( %peer, diff --git a/swap/src/protocol/alice/event_loop.rs b/swap/src/protocol/alice/event_loop.rs index 84da64d9..a52173d7 100644 --- a/swap/src/protocol/alice/event_loop.rs +++ b/swap/src/protocol/alice/event_loop.rs @@ -23,7 +23,7 @@ use uuid::Uuid; pub struct EventLoop { swarm: libp2p::Swarm, peer_id: PeerId, - execution_params: ExecutionParams, + exec_params: ExecutionParams, bitcoin_wallet: Arc, monero_wallet: Arc, db: Arc, @@ -53,7 +53,7 @@ where pub fn new( listen_address: Multiaddr, seed: Seed, - execution_params: ExecutionParams, + exec_params: ExecutionParams, bitcoin_wallet: Arc, monero_wallet: Arc, db: Arc, @@ -81,7 +81,7 @@ where let event_loop = EventLoop { swarm, peer_id, - execution_params, + exec_params, bitcoin_wallet, monero_wallet, db, @@ -133,7 +133,7 @@ where } } - match self.swarm.start_execution_setup(peer, btc, xmr, self.execution_params, self.bitcoin_wallet.as_ref(), &mut OsRng).await { + match self.swarm.start_execution_setup(peer, btc, xmr, self.exec_params, self.bitcoin_wallet.as_ref(), &mut OsRng).await { Ok(_) => {}, Err(e) => { tracing::warn!(%peer, "failed to start execution setup: {:#}", e); @@ -241,7 +241,7 @@ where event_loop_handle: handle, bitcoin_wallet: self.bitcoin_wallet.clone(), monero_wallet: self.monero_wallet.clone(), - execution_params: self.execution_params, + exec_params: self.exec_params, db: self.db.clone(), state: initial_state, swap_id, diff --git a/swap/src/protocol/alice/state.rs b/swap/src/protocol/alice/state.rs index 263aee10..0934d7dd 100644 --- a/swap/src/protocol/alice/state.rs +++ b/swap/src/protocol/alice/state.rs @@ -96,7 +96,7 @@ impl State0 { pub async fn new( btc: bitcoin::Amount, xmr: monero::Amount, - execution_params: ExecutionParams, + exec_params: ExecutionParams, bitcoin_wallet: &bitcoin::Wallet, rng: &mut R, ) -> Result @@ -124,8 +124,8 @@ impl State0 { punish_address, btc, xmr, - cancel_timelock: execution_params.bitcoin_cancel_timelock, - punish_timelock: execution_params.bitcoin_punish_timelock, + cancel_timelock: exec_params.bitcoin_cancel_timelock, + punish_timelock: exec_params.bitcoin_punish_timelock, }) } diff --git a/swap/src/protocol/alice/swap.rs b/swap/src/protocol/alice/swap.rs index 2d652416..f63be180 100644 --- a/swap/src/protocol/alice/swap.rs +++ b/swap/src/protocol/alice/swap.rs @@ -51,7 +51,7 @@ pub async fn run_until( swap.event_loop_handle, swap.bitcoin_wallet, swap.monero_wallet, - swap.execution_params, + swap.exec_params, swap.swap_id, swap.db, ) @@ -67,7 +67,7 @@ async fn run_until_internal( mut event_loop_handle: EventLoopHandle, bitcoin_wallet: Arc, monero_wallet: Arc, - execution_params: ExecutionParams, + exec_params: ExecutionParams, swap_id: Uuid, db: Arc, ) -> Result { @@ -81,7 +81,7 @@ async fn run_until_internal( bob_peer_id, } => { timeout( - execution_params.bob_time_to_act, + exec_params.bob_time_to_act, bitcoin_wallet .watch_until_status(&state3.tx_lock, |status| status.has_been_seen()), ) @@ -90,7 +90,7 @@ async fn run_until_internal( bitcoin_wallet .watch_until_status(&state3.tx_lock, |status| { - status.is_confirmed_with(execution_params.bitcoin_finality_confirmations) + status.is_confirmed_with(exec_params.bitcoin_finality_confirmations) }) .await?; @@ -108,7 +108,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -144,7 +144,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -192,7 +192,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -258,7 +258,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -291,7 +291,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -326,7 +326,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -355,7 +355,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -432,7 +432,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - execution_params, + exec_params, swap_id, db, ) @@ -452,7 +452,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - execution_params, + exec_params, swap_id, db, ) diff --git a/swap/src/protocol/bob.rs b/swap/src/protocol/bob.rs index f70eaf63..455eb5e0 100644 --- a/swap/src/protocol/bob.rs +++ b/swap/src/protocol/bob.rs @@ -37,7 +37,7 @@ pub struct Swap { pub db: Database, pub bitcoin_wallet: Arc, pub monero_wallet: Arc, - pub execution_params: ExecutionParams, + pub exec_params: ExecutionParams, pub swap_id: Uuid, pub receive_monero_address: ::monero::Address, } @@ -50,7 +50,7 @@ pub struct Builder { monero_wallet: Arc, init_params: InitParams, - execution_params: ExecutionParams, + exec_params: ExecutionParams, event_loop_handle: EventLoopHandle, @@ -69,7 +69,7 @@ impl Builder { swap_id: Uuid, bitcoin_wallet: Arc, monero_wallet: Arc, - execution_params: ExecutionParams, + exec_params: ExecutionParams, event_loop_handle: EventLoopHandle, receive_monero_address: ::monero::Address, ) -> Self { @@ -79,7 +79,7 @@ impl Builder { bitcoin_wallet, monero_wallet, init_params: InitParams::None, - execution_params, + exec_params, event_loop_handle, receive_monero_address, } @@ -105,7 +105,7 @@ impl Builder { bitcoin_wallet: self.bitcoin_wallet.clone(), monero_wallet: self.monero_wallet.clone(), swap_id: self.swap_id, - execution_params: self.execution_params, + exec_params: self.exec_params, receive_monero_address: self.receive_monero_address, }) } diff --git a/swap/src/protocol/bob/swap.rs b/swap/src/protocol/bob/swap.rs index 197e5fd9..4696be18 100644 --- a/swap/src/protocol/bob/swap.rs +++ b/swap/src/protocol/bob/swap.rs @@ -41,7 +41,7 @@ pub async fn run_until( swap.bitcoin_wallet, swap.monero_wallet, swap.swap_id, - swap.execution_params, + swap.exec_params, swap.receive_monero_address, ) .await @@ -58,7 +58,7 @@ async fn run_until_internal( bitcoin_wallet: Arc, monero_wallet: Arc, swap_id: Uuid, - execution_params: ExecutionParams, + exec_params: ExecutionParams, receive_monero_address: monero::Address, ) -> Result { trace!("Current state: {}", state); @@ -74,7 +74,7 @@ async fn run_until_internal( let state2 = request_price_and_setup( btc_amount, &mut event_loop_handle, - execution_params, + exec_params, bitcoin_refund_address, ) .await?; @@ -90,7 +90,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -121,7 +121,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -177,7 +177,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -232,7 +232,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -275,7 +275,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -311,7 +311,7 @@ async fn run_until_internal( bitcoin_wallet.clone(), monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -342,7 +342,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -368,7 +368,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -398,7 +398,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - execution_params, + exec_params, receive_monero_address, ) .await @@ -414,7 +414,7 @@ async fn run_until_internal( pub async fn request_price_and_setup( btc: bitcoin::Amount, event_loop_handle: &mut EventLoopHandle, - execution_params: ExecutionParams, + exec_params: ExecutionParams, bitcoin_refund_address: bitcoin::Address, ) -> Result { let xmr = event_loop_handle.request_spot_price(btc).await?; @@ -425,10 +425,10 @@ pub async fn request_price_and_setup( &mut OsRng, btc, xmr, - execution_params.bitcoin_cancel_timelock, - execution_params.bitcoin_punish_timelock, + exec_params.bitcoin_cancel_timelock, + exec_params.bitcoin_punish_timelock, bitcoin_refund_address, - execution_params.monero_finality_confirmations, + exec_params.monero_finality_confirmations, ); let state2 = event_loop_handle.execution_setup(state0).await?; diff --git a/swap/tests/testutils/mod.rs b/swap/tests/testutils/mod.rs index 174c46d7..4958d251 100644 --- a/swap/tests/testutils/mod.rs +++ b/swap/tests/testutils/mod.rs @@ -52,7 +52,7 @@ struct BobParams { monero_wallet: Arc, alice_address: Multiaddr, alice_peer_id: PeerId, - execution_params: ExecutionParams, + exec_params: ExecutionParams, } impl BobParams { @@ -64,7 +64,7 @@ impl BobParams { self.swap_id, self.bitcoin_wallet.clone(), self.monero_wallet.clone(), - self.execution_params, + self.exec_params, event_loop_handle, receive_address, )) @@ -317,7 +317,7 @@ where let _guard = init_tracing(); - let execution_params = C::get_execution_params(); + let exec_params = C::get_execution_params(); let (monero, containers) = testutils::init_containers(&cli).await; @@ -351,7 +351,7 @@ where tempdir().unwrap().path(), electrs_rpc_port, alice_seed, - execution_params, + exec_params, ) .await; @@ -373,14 +373,14 @@ where tempdir().unwrap().path(), electrs_rpc_port, bob_seed, - execution_params, + exec_params, ) .await; let (alice_event_loop, alice_swap_handle) = alice::EventLoop::new( alice_listen_address.clone(), alice_seed, - execution_params, + exec_params, alice_bitcoin_wallet.clone(), alice_monero_wallet.clone(), alice_db, @@ -401,7 +401,7 @@ where monero_wallet: bob_monero_wallet.clone(), alice_address: alice_listen_address, alice_peer_id, - execution_params, + exec_params, }; let test = TestContext { @@ -580,7 +580,7 @@ async fn init_test_wallets( datadir: &Path, electrum_rpc_port: u16, seed: Seed, - execution_params: ExecutionParams, + exec_params: ExecutionParams, ) -> (Arc, Arc) { monero .init(vec![(name, starting_balances.xmr.as_piconero())]) @@ -589,9 +589,8 @@ async fn init_test_wallets( let xmr_wallet = swap::monero::Wallet::new_with_client( monero.wallet(name).unwrap().client(), - monero::Network::default(), name.to_string(), - execution_params.monero_avg_block_time, + exec_params, ); let electrum_rpc_url = { @@ -601,11 +600,10 @@ async fn init_test_wallets( let btc_wallet = swap::bitcoin::Wallet::new( electrum_rpc_url, - bitcoin::Network::Regtest, - execution_params.bitcoin_finality_confirmations, datadir, - seed.derive_extended_private_key(bitcoin::Network::Regtest) + seed.derive_extended_private_key(exec_params.bitcoin_network) .expect("Could not create extended private key from seed"), + exec_params, ) .await .expect("could not init btc wallet"); From 09c41f89c42b2484b9c831831af11039ad8270f0 Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Wed, 17 Mar 2021 14:55:42 +1100 Subject: [PATCH 3/4] Rename ExecutionParams to EnvironmentConfig --- swap/src/bin/asb.rs | 18 ++++---- swap/src/bin/swap.rs | 42 +++++++++---------- swap/src/bitcoin/wallet.rs | 8 ++-- swap/src/{execution_params.rs => env.rs} | 26 ++++++------ swap/src/lib.rs | 2 +- swap/src/monero/wallet.rs | 16 +++----- swap/src/protocol/alice.rs | 4 +- swap/src/protocol/alice/behaviour.rs | 6 +-- swap/src/protocol/alice/event_loop.rs | 12 +++--- swap/src/protocol/alice/state.rs | 8 ++-- swap/src/protocol/alice/swap.rs | 28 ++++++------- swap/src/protocol/bob.rs | 12 +++--- swap/src/protocol/bob/swap.rs | 34 ++++++++-------- swap/tests/testutils/mod.rs | 52 ++++++++++++------------ 14 files changed, 132 insertions(+), 136 deletions(-) rename swap/src/{execution_params.rs => env.rs} (80%) diff --git a/swap/src/bin/asb.rs b/swap/src/bin/asb.rs index a3f2b9c1..76a4d5b5 100644 --- a/swap/src/bin/asb.rs +++ b/swap/src/bin/asb.rs @@ -24,13 +24,13 @@ use swap::asb::config::{ initial_setup, query_user_for_initial_testnet_config, read_config, Config, ConfigNotInitialized, }; use swap::database::Database; -use swap::execution_params::{ExecutionParams, GetExecutionParams}; +use swap::env::GetConfig; use swap::fs::default_config_path; use swap::monero::Amount; use swap::protocol::alice::{run, EventLoop}; use swap::seed::Seed; use swap::trace::init_tracing; -use swap::{bitcoin, execution_params, kraken, monero}; +use swap::{bitcoin, env, kraken, monero}; use tracing::{info, warn}; use tracing_subscriber::filter::LevelFilter; @@ -76,13 +76,13 @@ async fn main() -> Result<()> { let seed = Seed::from_file_or_generate(&config.data.dir) .expect("Could not retrieve/initialize seed"); - let exec_params = execution_params::Testnet::get_execution_params(); + let env_config = env::Testnet::get_config(); let (bitcoin_wallet, monero_wallet) = init_wallets( config.clone(), &wallet_data_dir, - seed.derive_extended_private_key(exec_params.bitcoin_network)?, - exec_params, + seed.derive_extended_private_key(env_config.bitcoin_network)?, + env_config, ) .await?; @@ -96,7 +96,7 @@ async fn main() -> Result<()> { let (event_loop, mut swap_receiver) = EventLoop::new( config.network.listen, seed, - exec_params, + env_config, Arc::new(bitcoin_wallet), Arc::new(monero_wallet), Arc::new(db), @@ -146,13 +146,13 @@ async fn init_wallets( config: Config, bitcoin_wallet_data_dir: &Path, key: impl DerivableKey + Clone, - exec_params: ExecutionParams, + env_config: env::Config, ) -> Result<(bitcoin::Wallet, monero::Wallet)> { let bitcoin_wallet = bitcoin::Wallet::new( config.bitcoin.electrum_rpc_url, bitcoin_wallet_data_dir, key, - exec_params, + env_config, ) .await?; @@ -167,7 +167,7 @@ async fn init_wallets( let monero_wallet = monero::Wallet::new( config.monero.wallet_rpc_url.clone(), DEFAULT_WALLET_NAME.to_string(), - exec_params, + env_config, ); // Setup the Monero wallet diff --git a/swap/src/bin/swap.rs b/swap/src/bin/swap.rs index 2d58b7d2..e4c9f102 100644 --- a/swap/src/bin/swap.rs +++ b/swap/src/bin/swap.rs @@ -23,12 +23,12 @@ use structopt::StructOpt; use swap::bitcoin::{Amount, TxLock}; use swap::cli::command::{AliceConnectParams, Arguments, Command, Data, MoneroParams}; use swap::database::Database; -use swap::execution_params::{ExecutionParams, GetExecutionParams}; +use swap::env::{Config, GetConfig}; use swap::network::quote::BidQuote; use swap::protocol::bob; use swap::protocol::bob::{Builder, EventLoop}; use swap::seed::Seed; -use swap::{bitcoin, execution_params, monero}; +use swap::{bitcoin, env, monero}; use tracing::{debug, error, info, warn, Level}; use tracing_subscriber::FmtSubscriber; use url::Url; @@ -76,7 +76,7 @@ async fn main() -> Result<()> { let seed = Seed::from_file_or_generate(data_dir.as_path()).context("Failed to read in seed file")?; - let exec_params = execution_params::Testnet::get_execution_params(); + let env_config = env::Testnet::get_config(); match args.cmd { Command::BuyXmr { @@ -92,18 +92,18 @@ async fn main() -> Result<()> { }, electrum_rpc_url, } => { - if receive_monero_address.network != exec_params.monero_network { + if receive_monero_address.network != env_config.monero_network { bail!( "Given monero address is on network {:?}, expected address on network {:?}", receive_monero_address.network, - exec_params.monero_network + env_config.monero_network ) } let bitcoin_wallet = - init_bitcoin_wallet(electrum_rpc_url, seed, data_dir.clone(), exec_params).await?; + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir.clone(), env_config).await?; let (monero_wallet, _process) = - init_monero_wallet(data_dir, monero_daemon_host, exec_params).await?; + init_monero_wallet(data_dir, monero_daemon_host, env_config).await?; let bitcoin_wallet = Arc::new(bitcoin_wallet); let (event_loop, mut event_loop_handle) = EventLoop::new( &seed.derive_libp2p_identity(), @@ -135,7 +135,7 @@ async fn main() -> Result<()> { Uuid::new_v4(), bitcoin_wallet.clone(), Arc::new(monero_wallet), - exec_params, + env_config, event_loop_handle, receive_monero_address, ) @@ -178,14 +178,14 @@ async fn main() -> Result<()> { }, electrum_rpc_url, } => { - if receive_monero_address.network != exec_params.monero_network { - bail!("The given monero address is on network {:?}, expected address of network {:?}.", receive_monero_address.network, exec_params.monero_network) + if receive_monero_address.network != env_config.monero_network { + bail!("The given monero address is on network {:?}, expected address of network {:?}.", receive_monero_address.network, env_config.monero_network) } let bitcoin_wallet = - init_bitcoin_wallet(electrum_rpc_url, seed, data_dir.clone(), exec_params).await?; + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir.clone(), env_config).await?; let (monero_wallet, _process) = - init_monero_wallet(data_dir, monero_daemon_host, exec_params).await?; + init_monero_wallet(data_dir, monero_daemon_host, env_config).await?; let bitcoin_wallet = Arc::new(bitcoin_wallet); let (event_loop, event_loop_handle) = EventLoop::new( @@ -201,7 +201,7 @@ async fn main() -> Result<()> { swap_id, bitcoin_wallet.clone(), Arc::new(monero_wallet), - exec_params, + env_config, event_loop_handle, receive_monero_address, ) @@ -223,7 +223,7 @@ async fn main() -> Result<()> { electrum_rpc_url, } => { let bitcoin_wallet = - init_bitcoin_wallet(electrum_rpc_url, seed, data_dir, exec_params).await?; + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir, env_config).await?; let resume_state = db.get_state(swap_id)?.try_into_bob()?.into(); let cancel = @@ -248,7 +248,7 @@ async fn main() -> Result<()> { electrum_rpc_url, } => { let bitcoin_wallet = - init_bitcoin_wallet(electrum_rpc_url, seed, data_dir, exec_params).await?; + init_bitcoin_wallet(electrum_rpc_url, seed, data_dir, env_config).await?; let resume_state = db.get_state(swap_id)?.try_into_bob()?.into(); @@ -262,15 +262,15 @@ async fn init_bitcoin_wallet( electrum_rpc_url: Url, seed: Seed, data_dir: PathBuf, - exec_params: ExecutionParams, + env_config: Config, ) -> Result { let wallet_dir = data_dir.join("wallet"); let wallet = bitcoin::Wallet::new( electrum_rpc_url.clone(), &wallet_dir, - seed.derive_extended_private_key(exec_params.bitcoin_network)?, - exec_params, + seed.derive_extended_private_key(env_config.bitcoin_network)?, + env_config, ) .await .context("Failed to initialize Bitcoin wallet")?; @@ -283,9 +283,9 @@ async fn init_bitcoin_wallet( async fn init_monero_wallet( data_dir: PathBuf, monero_daemon_host: String, - exec_params: ExecutionParams, + env_config: Config, ) -> Result<(monero::Wallet, monero::WalletRpcProcess)> { - let network = exec_params.monero_network; + let network = env_config.monero_network; const MONERO_BLOCKCHAIN_MONITORING_WALLET_NAME: &str = "swap-tool-blockchain-monitoring-wallet"; @@ -298,7 +298,7 @@ async fn init_monero_wallet( let monero_wallet = monero::Wallet::new( monero_wallet_rpc_process.endpoint(), MONERO_BLOCKCHAIN_MONITORING_WALLET_NAME.to_string(), - exec_params, + env_config, ); monero_wallet.open_or_create().await?; diff --git a/swap/src/bitcoin/wallet.rs b/swap/src/bitcoin/wallet.rs index 7b58c555..b5483fd6 100644 --- a/swap/src/bitcoin/wallet.rs +++ b/swap/src/bitcoin/wallet.rs @@ -1,6 +1,6 @@ use crate::bitcoin::timelocks::BlockHeight; use crate::bitcoin::{Address, Amount, Transaction}; -use crate::execution_params::ExecutionParams; +use crate::env::Config; use ::bitcoin::util::psbt::PartiallySignedTransaction; use ::bitcoin::Txid; use anyhow::{anyhow, bail, Context, Result}; @@ -33,7 +33,7 @@ impl Wallet { electrum_rpc_url: Url, wallet_dir: &Path, key: impl DerivableKey + Clone, - exec_params: ExecutionParams, + env_config: Config, ) -> Result { // Workaround for https://github.com/bitcoindevkit/rust-electrum-client/issues/47. let config = electrum_client::ConfigBuilder::default().retry(2).build(); @@ -47,7 +47,7 @@ impl Wallet { let bdk_wallet = bdk::Wallet::new( bdk::template::BIP84(key.clone(), KeychainKind::External), Some(bdk::template::BIP84(key, KeychainKind::Internal)), - exec_params.bitcoin_network, + env_config.bitcoin_network, db, ElectrumBlockchain::from(client), )?; @@ -60,7 +60,7 @@ impl Wallet { Ok(Self { wallet: Arc::new(Mutex::new(bdk_wallet)), client: Arc::new(Mutex::new(Client::new(electrum, interval)?)), - finality_confirmations: exec_params.bitcoin_finality_confirmations, + finality_confirmations: env_config.bitcoin_finality_confirmations, }) } diff --git a/swap/src/execution_params.rs b/swap/src/env.rs similarity index 80% rename from swap/src/execution_params.rs rename to swap/src/env.rs index 3479357c..cae01dea 100644 --- a/swap/src/execution_params.rs +++ b/swap/src/env.rs @@ -3,7 +3,7 @@ use std::time::Duration; use time::NumericalStdDurationShort; #[derive(Debug, Copy, Clone)] -pub struct ExecutionParams { +pub struct Config { pub bob_time_to_act: Duration, pub bitcoin_finality_confirmations: u32, pub bitcoin_avg_block_time: Duration, @@ -15,8 +15,8 @@ pub struct ExecutionParams { pub monero_network: monero::Network, } -pub trait GetExecutionParams { - fn get_execution_params() -> ExecutionParams; +pub trait GetConfig { + fn get_config() -> Config; } #[derive(Clone, Copy)] @@ -28,9 +28,9 @@ pub struct Testnet; #[derive(Clone, Copy)] pub struct Regtest; -impl GetExecutionParams for Mainnet { - fn get_execution_params() -> ExecutionParams { - ExecutionParams { +impl GetConfig for Mainnet { + fn get_config() -> Config { + Config { bob_time_to_act: 10.minutes(), bitcoin_finality_confirmations: 3, bitcoin_avg_block_time: 10.minutes(), @@ -44,9 +44,9 @@ impl GetExecutionParams for Mainnet { } } -impl GetExecutionParams for Testnet { - fn get_execution_params() -> ExecutionParams { - ExecutionParams { +impl GetConfig for Testnet { + fn get_config() -> Config { + Config { bob_time_to_act: 60.minutes(), bitcoin_finality_confirmations: 1, bitcoin_avg_block_time: 5.minutes(), @@ -60,9 +60,9 @@ impl GetExecutionParams for Testnet { } } -impl GetExecutionParams for Regtest { - fn get_execution_params() -> ExecutionParams { - ExecutionParams { +impl GetConfig for Regtest { + fn get_config() -> Config { + Config { bob_time_to_act: 30.seconds(), bitcoin_finality_confirmations: 1, bitcoin_avg_block_time: 5.seconds(), @@ -71,7 +71,7 @@ impl GetExecutionParams for Regtest { bitcoin_network: bitcoin::Network::Regtest, monero_avg_block_time: 1.seconds(), monero_finality_confirmations: 10, - monero_network: monero::Network::Testnet, + monero_network: monero::Network::Mainnet, // yes this is strange } } } diff --git a/swap/src/lib.rs b/swap/src/lib.rs index b769dc96..5694f087 100644 --- a/swap/src/lib.rs +++ b/swap/src/lib.rs @@ -20,7 +20,7 @@ pub mod asb; pub mod bitcoin; pub mod cli; pub mod database; -pub mod execution_params; +pub mod env; pub mod fs; pub mod kraken; pub mod monero; diff --git a/swap/src/monero/wallet.rs b/swap/src/monero/wallet.rs index 59408177..bd7afcda 100644 --- a/swap/src/monero/wallet.rs +++ b/swap/src/monero/wallet.rs @@ -1,4 +1,4 @@ -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::monero::{ Amount, InsufficientFunds, PrivateViewKey, PublicViewKey, TransferProof, TxHash, }; @@ -24,20 +24,16 @@ pub struct Wallet { } impl Wallet { - pub fn new(url: Url, name: String, exec_params: ExecutionParams) -> Self { - Self::new_with_client(Client::new(url), name, exec_params) + pub fn new(url: Url, name: String, env_config: Config) -> Self { + Self::new_with_client(Client::new(url), name, env_config) } - pub fn new_with_client( - client: wallet::Client, - name: String, - exec_params: ExecutionParams, - ) -> Self { + pub fn new_with_client(client: wallet::Client, name: String, env_config: Config) -> Self { Self { inner: Mutex::new(client), - network: exec_params.monero_network, + network: env_config.monero_network, name, - avg_block_time: exec_params.monero_avg_block_time, + avg_block_time: env_config.monero_avg_block_time, } } diff --git a/swap/src/protocol/alice.rs b/swap/src/protocol/alice.rs index 07044e4b..351cef71 100644 --- a/swap/src/protocol/alice.rs +++ b/swap/src/protocol/alice.rs @@ -1,7 +1,7 @@ //! Run an XMR/BTC swap in the role of Alice. //! Alice holds XMR and wishes receive BTC. use crate::database::Database; -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::{bitcoin, monero}; use std::sync::Arc; use uuid::Uuid; @@ -28,7 +28,7 @@ pub struct Swap { pub event_loop_handle: EventLoopHandle, pub bitcoin_wallet: Arc, pub monero_wallet: Arc, - pub exec_params: ExecutionParams, + pub env_config: Config, pub swap_id: Uuid, pub db: Arc, } diff --git a/swap/src/protocol/alice/behaviour.rs b/swap/src/protocol/alice/behaviour.rs index d4ff73f7..f5fc7b2e 100644 --- a/swap/src/protocol/alice/behaviour.rs +++ b/swap/src/protocol/alice/behaviour.rs @@ -1,4 +1,4 @@ -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::network::quote::BidQuote; use crate::network::{peer_tracker, quote, spot_price}; use crate::protocol::alice::{ @@ -206,11 +206,11 @@ impl Behaviour { peer: PeerId, btc: bitcoin::Amount, xmr: monero::Amount, - exec_params: ExecutionParams, + env_config: Config, bitcoin_wallet: &bitcoin::Wallet, rng: &mut (impl RngCore + CryptoRng), ) -> Result<()> { - let state0 = State0::new(btc, xmr, exec_params, bitcoin_wallet, rng).await?; + let state0 = State0::new(btc, xmr, env_config, bitcoin_wallet, rng).await?; tracing::info!( %peer, diff --git a/swap/src/protocol/alice/event_loop.rs b/swap/src/protocol/alice/event_loop.rs index a52173d7..179c9532 100644 --- a/swap/src/protocol/alice/event_loop.rs +++ b/swap/src/protocol/alice/event_loop.rs @@ -1,6 +1,6 @@ use crate::asb::{FixedRate, Rate}; use crate::database::Database; -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::monero::BalanceTooLow; use crate::network::quote::BidQuote; use crate::network::{spot_price, transport, TokioExecutor}; @@ -23,7 +23,7 @@ use uuid::Uuid; pub struct EventLoop { swarm: libp2p::Swarm, peer_id: PeerId, - exec_params: ExecutionParams, + env_config: Config, bitcoin_wallet: Arc, monero_wallet: Arc, db: Arc, @@ -53,7 +53,7 @@ where pub fn new( listen_address: Multiaddr, seed: Seed, - exec_params: ExecutionParams, + env_config: Config, bitcoin_wallet: Arc, monero_wallet: Arc, db: Arc, @@ -81,7 +81,7 @@ where let event_loop = EventLoop { swarm, peer_id, - exec_params, + env_config, bitcoin_wallet, monero_wallet, db, @@ -133,7 +133,7 @@ where } } - match self.swarm.start_execution_setup(peer, btc, xmr, self.exec_params, self.bitcoin_wallet.as_ref(), &mut OsRng).await { + match self.swarm.start_execution_setup(peer, btc, xmr, self.env_config, self.bitcoin_wallet.as_ref(), &mut OsRng).await { Ok(_) => {}, Err(e) => { tracing::warn!(%peer, "failed to start execution setup: {:#}", e); @@ -241,7 +241,7 @@ where event_loop_handle: handle, bitcoin_wallet: self.bitcoin_wallet.clone(), monero_wallet: self.monero_wallet.clone(), - exec_params: self.exec_params, + env_config: self.env_config, db: self.db.clone(), state: initial_state, swap_id, diff --git a/swap/src/protocol/alice/state.rs b/swap/src/protocol/alice/state.rs index 0934d7dd..6eb2e7e1 100644 --- a/swap/src/protocol/alice/state.rs +++ b/swap/src/protocol/alice/state.rs @@ -1,7 +1,7 @@ use crate::bitcoin::{ current_epoch, CancelTimelock, ExpiredTimelocks, PunishTimelock, TxCancel, TxPunish, TxRefund, }; -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::protocol::alice::{Message1, Message3}; use crate::protocol::bob::{Message0, Message2, Message4}; use crate::protocol::CROSS_CURVE_PROOF_SYSTEM; @@ -96,7 +96,7 @@ impl State0 { pub async fn new( btc: bitcoin::Amount, xmr: monero::Amount, - exec_params: ExecutionParams, + env_config: Config, bitcoin_wallet: &bitcoin::Wallet, rng: &mut R, ) -> Result @@ -124,8 +124,8 @@ impl State0 { punish_address, btc, xmr, - cancel_timelock: exec_params.bitcoin_cancel_timelock, - punish_timelock: exec_params.bitcoin_punish_timelock, + cancel_timelock: env_config.bitcoin_cancel_timelock, + punish_timelock: env_config.bitcoin_punish_timelock, }) } diff --git a/swap/src/protocol/alice/swap.rs b/swap/src/protocol/alice/swap.rs index f63be180..942ae5a4 100644 --- a/swap/src/protocol/alice/swap.rs +++ b/swap/src/protocol/alice/swap.rs @@ -2,7 +2,7 @@ //! Alice holds XMR and wishes receive BTC. use crate::bitcoin::{ExpiredTimelocks, TxRedeem}; use crate::database::Database; -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::monero_ext::ScalarExt; use crate::protocol::alice; use crate::protocol::alice::event_loop::EventLoopHandle; @@ -51,7 +51,7 @@ pub async fn run_until( swap.event_loop_handle, swap.bitcoin_wallet, swap.monero_wallet, - swap.exec_params, + swap.env_config, swap.swap_id, swap.db, ) @@ -67,7 +67,7 @@ async fn run_until_internal( mut event_loop_handle: EventLoopHandle, bitcoin_wallet: Arc, monero_wallet: Arc, - exec_params: ExecutionParams, + env_config: Config, swap_id: Uuid, db: Arc, ) -> Result { @@ -81,7 +81,7 @@ async fn run_until_internal( bob_peer_id, } => { timeout( - exec_params.bob_time_to_act, + env_config.bob_time_to_act, bitcoin_wallet .watch_until_status(&state3.tx_lock, |status| status.has_been_seen()), ) @@ -90,7 +90,7 @@ async fn run_until_internal( bitcoin_wallet .watch_until_status(&state3.tx_lock, |status| { - status.is_confirmed_with(exec_params.bitcoin_finality_confirmations) + status.is_confirmed_with(env_config.bitcoin_finality_confirmations) }) .await?; @@ -108,7 +108,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -144,7 +144,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -192,7 +192,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -258,7 +258,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -291,7 +291,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet, monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -326,7 +326,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -355,7 +355,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -432,7 +432,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - exec_params, + env_config, swap_id, db, ) @@ -452,7 +452,7 @@ async fn run_until_internal( event_loop_handle, bitcoin_wallet.clone(), monero_wallet, - exec_params, + env_config, swap_id, db, ) diff --git a/swap/src/protocol/bob.rs b/swap/src/protocol/bob.rs index 455eb5e0..62103aea 100644 --- a/swap/src/protocol/bob.rs +++ b/swap/src/protocol/bob.rs @@ -1,5 +1,5 @@ use crate::database::Database; -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::network::{peer_tracker, spot_price}; use crate::protocol::alice::TransferProof; use crate::protocol::bob; @@ -37,7 +37,7 @@ pub struct Swap { pub db: Database, pub bitcoin_wallet: Arc, pub monero_wallet: Arc, - pub exec_params: ExecutionParams, + pub env_config: Config, pub swap_id: Uuid, pub receive_monero_address: ::monero::Address, } @@ -50,7 +50,7 @@ pub struct Builder { monero_wallet: Arc, init_params: InitParams, - exec_params: ExecutionParams, + env_config: Config, event_loop_handle: EventLoopHandle, @@ -69,7 +69,7 @@ impl Builder { swap_id: Uuid, bitcoin_wallet: Arc, monero_wallet: Arc, - exec_params: ExecutionParams, + env_config: Config, event_loop_handle: EventLoopHandle, receive_monero_address: ::monero::Address, ) -> Self { @@ -79,7 +79,7 @@ impl Builder { bitcoin_wallet, monero_wallet, init_params: InitParams::None, - exec_params, + env_config, event_loop_handle, receive_monero_address, } @@ -105,7 +105,7 @@ impl Builder { bitcoin_wallet: self.bitcoin_wallet.clone(), monero_wallet: self.monero_wallet.clone(), swap_id: self.swap_id, - exec_params: self.exec_params, + env_config: self.env_config, receive_monero_address: self.receive_monero_address, }) } diff --git a/swap/src/protocol/bob/swap.rs b/swap/src/protocol/bob/swap.rs index 4696be18..bada7f5d 100644 --- a/swap/src/protocol/bob/swap.rs +++ b/swap/src/protocol/bob/swap.rs @@ -1,6 +1,6 @@ use crate::bitcoin::ExpiredTimelocks; use crate::database::{Database, Swap}; -use crate::execution_params::ExecutionParams; +use crate::env::Config; use crate::monero::InsufficientFunds; use crate::protocol::bob; use crate::protocol::bob::event_loop::EventLoopHandle; @@ -41,7 +41,7 @@ pub async fn run_until( swap.bitcoin_wallet, swap.monero_wallet, swap.swap_id, - swap.exec_params, + swap.env_config, swap.receive_monero_address, ) .await @@ -58,7 +58,7 @@ async fn run_until_internal( bitcoin_wallet: Arc, monero_wallet: Arc, swap_id: Uuid, - exec_params: ExecutionParams, + env_config: Config, receive_monero_address: monero::Address, ) -> Result { trace!("Current state: {}", state); @@ -74,7 +74,7 @@ async fn run_until_internal( let state2 = request_price_and_setup( btc_amount, &mut event_loop_handle, - exec_params, + env_config, bitcoin_refund_address, ) .await?; @@ -90,7 +90,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -121,7 +121,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -177,7 +177,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -232,7 +232,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -275,7 +275,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -311,7 +311,7 @@ async fn run_until_internal( bitcoin_wallet.clone(), monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -342,7 +342,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -368,7 +368,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -398,7 +398,7 @@ async fn run_until_internal( bitcoin_wallet, monero_wallet, swap_id, - exec_params, + env_config, receive_monero_address, ) .await @@ -414,7 +414,7 @@ async fn run_until_internal( pub async fn request_price_and_setup( btc: bitcoin::Amount, event_loop_handle: &mut EventLoopHandle, - exec_params: ExecutionParams, + env_config: Config, bitcoin_refund_address: bitcoin::Address, ) -> Result { let xmr = event_loop_handle.request_spot_price(btc).await?; @@ -425,10 +425,10 @@ pub async fn request_price_and_setup( &mut OsRng, btc, xmr, - exec_params.bitcoin_cancel_timelock, - exec_params.bitcoin_punish_timelock, + env_config.bitcoin_cancel_timelock, + env_config.bitcoin_punish_timelock, bitcoin_refund_address, - exec_params.monero_finality_confirmations, + env_config.monero_finality_confirmations, ); let state2 = event_loop_handle.execution_setup(state0).await?; diff --git a/swap/tests/testutils/mod.rs b/swap/tests/testutils/mod.rs index 4958d251..7f4c21f6 100644 --- a/swap/tests/testutils/mod.rs +++ b/swap/tests/testutils/mod.rs @@ -16,12 +16,12 @@ use std::time::Duration; use swap::asb::FixedRate; use swap::bitcoin::{CancelTimelock, PunishTimelock}; use swap::database::Database; -use swap::execution_params::{ExecutionParams, GetExecutionParams}; +use swap::env::{Config, GetConfig}; use swap::protocol::alice::{AliceState, Swap}; use swap::protocol::bob::BobState; use swap::protocol::{alice, bob}; use swap::seed::Seed; -use swap::{bitcoin, execution_params, monero}; +use swap::{bitcoin, env, monero}; use tempfile::tempdir; use testcontainers::clients::Cli; use testcontainers::{Container, Docker, RunArgs}; @@ -52,7 +52,7 @@ struct BobParams { monero_wallet: Arc, alice_address: Multiaddr, alice_peer_id: PeerId, - exec_params: ExecutionParams, + env_config: Config, } impl BobParams { @@ -64,7 +64,7 @@ impl BobParams { self.swap_id, self.bitcoin_wallet.clone(), self.monero_wallet.clone(), - self.exec_params, + self.env_config, event_loop_handle, receive_address, )) @@ -311,13 +311,13 @@ pub async fn setup_test(_config: C, testfn: T) where T: Fn(TestContext) -> F, F: Future>, - C: GetExecutionParams, + C: GetConfig, { let cli = Cli::default(); let _guard = init_tracing(); - let exec_params = C::get_execution_params(); + let env_config = C::get_config(); let (monero, containers) = testutils::init_containers(&cli).await; @@ -351,7 +351,7 @@ where tempdir().unwrap().path(), electrs_rpc_port, alice_seed, - exec_params, + env_config, ) .await; @@ -373,14 +373,14 @@ where tempdir().unwrap().path(), electrs_rpc_port, bob_seed, - exec_params, + env_config, ) .await; let (alice_event_loop, alice_swap_handle) = alice::EventLoop::new( alice_listen_address.clone(), alice_seed, - exec_params, + env_config, alice_bitcoin_wallet.clone(), alice_monero_wallet.clone(), alice_db, @@ -401,7 +401,7 @@ where monero_wallet: bob_monero_wallet.clone(), alice_address: alice_listen_address, alice_peer_id, - exec_params, + env_config, }; let test = TestContext { @@ -580,7 +580,7 @@ async fn init_test_wallets( datadir: &Path, electrum_rpc_port: u16, seed: Seed, - exec_params: ExecutionParams, + env_config: Config, ) -> (Arc, Arc) { monero .init(vec![(name, starting_balances.xmr.as_piconero())]) @@ -590,7 +590,7 @@ async fn init_test_wallets( let xmr_wallet = swap::monero::Wallet::new_with_client( monero.wallet(name).unwrap().client(), name.to_string(), - exec_params, + env_config, ); let electrum_rpc_url = { @@ -601,9 +601,9 @@ async fn init_test_wallets( let btc_wallet = swap::bitcoin::Wallet::new( electrum_rpc_url, datadir, - seed.derive_extended_private_key(exec_params.bitcoin_network) + seed.derive_extended_private_key(env_config.bitcoin_network) .expect("Could not create extended private key from seed"), - exec_params, + env_config, ) .await .expect("could not init btc wallet"); @@ -702,34 +702,34 @@ pub mod bob_run_until { pub struct SlowCancelConfig; -impl GetExecutionParams for SlowCancelConfig { - fn get_execution_params() -> ExecutionParams { - ExecutionParams { +impl GetConfig for SlowCancelConfig { + fn get_config() -> Config { + Config { bitcoin_cancel_timelock: CancelTimelock::new(180), - ..execution_params::Regtest::get_execution_params() + ..env::Regtest::get_config() } } } pub struct FastCancelConfig; -impl GetExecutionParams for FastCancelConfig { - fn get_execution_params() -> ExecutionParams { - ExecutionParams { +impl GetConfig for FastCancelConfig { + fn get_config() -> Config { + Config { bitcoin_cancel_timelock: CancelTimelock::new(1), - ..execution_params::Regtest::get_execution_params() + ..env::Regtest::get_config() } } } pub struct FastPunishConfig; -impl GetExecutionParams for FastPunishConfig { - fn get_execution_params() -> ExecutionParams { - ExecutionParams { +impl GetConfig for FastPunishConfig { + fn get_config() -> Config { + Config { bitcoin_cancel_timelock: CancelTimelock::new(1), bitcoin_punish_timelock: PunishTimelock::new(1), - ..execution_params::Regtest::get_execution_params() + ..env::Regtest::get_config() } } } From ce780759327a5277e9ad7b3d6c774f392ed5e4bb Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Wed, 17 Mar 2021 15:01:08 +1100 Subject: [PATCH 4/4] Make Monero and Bitcoin wallet use a generalized sync interval We define the sync interval as 1/10th of the blocktime. For the special case of our tests, we however check at max once per second. The tests have a super fast blocktime. As such we shouldn't hammer the nodes with a request every 100ms. --- swap/src/bitcoin/wallet.rs | 11 ++++++----- swap/src/env.rs | 34 ++++++++++++++++++++++++++++++++++ swap/src/monero/wallet.rs | 25 +++---------------------- 3 files changed, 43 insertions(+), 27 deletions(-) diff --git a/swap/src/bitcoin/wallet.rs b/swap/src/bitcoin/wallet.rs index b5483fd6..dbd38a3f 100644 --- a/swap/src/bitcoin/wallet.rs +++ b/swap/src/bitcoin/wallet.rs @@ -1,6 +1,6 @@ use crate::bitcoin::timelocks::BlockHeight; use crate::bitcoin::{Address, Amount, Transaction}; -use crate::env::Config; +use crate::env; use ::bitcoin::util::psbt::PartiallySignedTransaction; use ::bitcoin::Txid; use anyhow::{anyhow, bail, Context, Result}; @@ -33,7 +33,7 @@ impl Wallet { electrum_rpc_url: Url, wallet_dir: &Path, key: impl DerivableKey + Clone, - env_config: Config, + env_config: env::Config, ) -> Result { // Workaround for https://github.com/bitcoindevkit/rust-electrum-client/issues/47. let config = electrum_client::ConfigBuilder::default().retry(2).build(); @@ -55,11 +55,12 @@ impl Wallet { let electrum = bdk::electrum_client::Client::from_config(electrum_rpc_url.as_str(), config) .map_err(|e| anyhow!("Failed to init electrum rpc client {:?}", e))?; - let interval = Duration::from_secs(5); - Ok(Self { wallet: Arc::new(Mutex::new(bdk_wallet)), - client: Arc::new(Mutex::new(Client::new(electrum, interval)?)), + client: Arc::new(Mutex::new(Client::new( + electrum, + env_config.bitcoin_sync_interval(), + )?)), finality_confirmations: env_config.bitcoin_finality_confirmations, }) } diff --git a/swap/src/env.rs b/swap/src/env.rs index cae01dea..d60ae858 100644 --- a/swap/src/env.rs +++ b/swap/src/env.rs @@ -1,4 +1,5 @@ use crate::bitcoin::{CancelTimelock, PunishTimelock}; +use std::cmp::max; use std::time::Duration; use time::NumericalStdDurationShort; @@ -15,6 +16,16 @@ pub struct Config { pub monero_network: monero::Network, } +impl Config { + pub fn bitcoin_sync_interval(&self) -> Duration { + sync_interval(self.bitcoin_avg_block_time) + } + + pub fn monero_sync_interval(&self) -> Duration { + sync_interval(self.monero_avg_block_time) + } +} + pub trait GetConfig { fn get_config() -> Config; } @@ -75,3 +86,26 @@ impl GetConfig for Regtest { } } } + +fn sync_interval(avg_block_time: Duration) -> Duration { + max(avg_block_time / 10, Duration::from_secs(1)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn check_interval_is_one_second_if_avg_blocktime_is_one_second() { + let interval = sync_interval(Duration::from_secs(1)); + + assert_eq!(interval, Duration::from_secs(1)) + } + + #[test] + fn check_interval_is_tenth_of_avg_blocktime() { + let interval = sync_interval(Duration::from_secs(100)); + + assert_eq!(interval, Duration::from_secs(10)) + } +} diff --git a/swap/src/monero/wallet.rs b/swap/src/monero/wallet.rs index bd7afcda..764235c9 100644 --- a/swap/src/monero/wallet.rs +++ b/swap/src/monero/wallet.rs @@ -6,7 +6,6 @@ use ::monero::{Address, Network, PrivateKey, PublicKey}; use anyhow::{Context, Result}; use monero_rpc::wallet; use monero_rpc::wallet::{BlockHeight, CheckTxKey, Client, Refreshed}; -use std::cmp::max; use std::future::Future; use std::str::FromStr; use std::time::Duration; @@ -20,7 +19,7 @@ pub struct Wallet { inner: Mutex, network: Network, name: String, - avg_block_time: Duration, + sync_interval: Duration, } impl Wallet { @@ -33,7 +32,7 @@ impl Wallet { inner: Mutex::new(client), network: env_config.monero_network, name, - avg_block_time: env_config.monero_avg_block_time, + sync_interval: env_config.monero_sync_interval(), } } @@ -164,7 +163,7 @@ impl Wallet { let address = Address::standard(self.network, public_spend_key, public_view_key.into()); - let check_interval = tokio::time::interval(new_check_interval(self.avg_block_time)); + let check_interval = tokio::time::interval(self.sync_interval); let key = &transfer_proof.tx_key().to_string(); wait_for_confirmations( @@ -223,10 +222,6 @@ impl Wallet { } } -fn new_check_interval(avg_block_time: Duration) -> Duration { - max(avg_block_time / 10, Duration::from_secs(1)) -} - async fn wait_for_confirmations( txid: String, fetch_tx: impl Fn(String) -> Fut, @@ -346,18 +341,4 @@ mod tests { assert!(result.is_ok()) } - - #[test] - fn check_interval_is_one_second_if_avg_blocktime_is_one_second() { - let interval = new_check_interval(Duration::from_secs(1)); - - assert_eq!(interval, Duration::from_secs(1)) - } - - #[test] - fn check_interval_is_tenth_of_avg_blocktime() { - let interval = new_check_interval(Duration::from_secs(100)); - - assert_eq!(interval, Duration::from_secs(10)) - } }