Disallow concurrent swaps

This commit is contained in:
binarybaron 2023-08-11 11:53:07 +02:00
parent 7d2b7bee92
commit 849e6e7a14

View file

@ -22,6 +22,11 @@ use structopt::lazy_static::lazy_static;
use tokio::sync::broadcast::Receiver;
use tracing::{debug_span, Instrument};
use uuid::Uuid;
use tokio::sync::Mutex;
lazy_static! {
static ref SWAP_MUTEX: Mutex<Option<Uuid>> = Mutex::new(None);
}
#[derive(PartialEq, Debug)]
pub struct Request {
@ -558,10 +563,26 @@ impl Request {
pub async fn call(self, context: Arc<Context>) -> Result<serde_json::Value> {
// If the swap ID is set, we add it to the span
let call_span = debug_span!(
"call",
"cmd",
method = ?self.cmd,
);
if let Some(swap_id) = self.has_lockable_swap_id() {
println!("taking lock for swap_id: {}", swap_id);
let mut guard = SWAP_MUTEX.try_lock().context("Another swap is already running")?;
if guard.is_some() {
bail!("Another swap is already running");
}
let _ = guard.insert(swap_id.clone());
let result = self.handle_cmd(context).instrument(call_span).await;
guard.take();
println!("releasing lock for swap_id: {}", swap_id);
return result;
}
self.handle_cmd(context).instrument(call_span).await
}
}
@ -584,7 +605,7 @@ pub async fn determine_btc_to_swap<FB, TB, FMG, TMG, FS, TS, FFE, TFE>(
sync: FS,
estimate_fee: FFE,
) -> Result<(bitcoin::Amount, bitcoin::Amount)>
where
where
TB: Future<Output = Result<bitcoin::Amount>>,
FB: Fn() -> TB,
TMG: Future<Output = Result<bitcoin::Amount>>,
@ -667,3 +688,4 @@ where
Ok((btc_swap_amount, fees))
}