1use std::collections::HashSet;
2use std::str::FromStr;
3
4use anyhow::{anyhow, bail, Context, Result};
5use boltz_client::swaps::boltz::RevSwapStates;
6use boltz_client::{boltz, Serialize, ToHex};
7use log::{debug, error, info, warn};
8use lwk_wollet::elements::secp256k1_zkp::Secp256k1;
9use lwk_wollet::elements::{Transaction, Txid};
10use lwk_wollet::hashes::hex::DisplayHex;
11use lwk_wollet::secp256k1::SecretKey;
12use sdk_common::utils::Arc;
13use tokio::sync::{broadcast, Mutex};
14
15use crate::chain::liquid::LiquidChainService;
16use crate::error::is_txn_mempool_conflict_error;
17use crate::model::{BlockListener, PaymentState::*};
18use crate::model::{Config, PaymentTxData, PaymentType, ReceiveSwap};
19use crate::persist::model::PaymentTxBalance;
20use crate::prelude::Swap;
21use crate::{ensure_sdk, utils};
22use crate::{
23 error::PaymentError, model::PaymentState, persist::Persister, swapper::Swapper,
24 wallet::OnchainWallet,
25};
26
27pub const DEFAULT_ZERO_CONF_MAX_SAT: u64 = 1_000_000;
29
30pub(crate) struct ReceiveSwapHandler {
31 config: Config,
32 onchain_wallet: Arc<dyn OnchainWallet>,
33 persister: std::sync::Arc<Persister>,
34 swapper: Arc<dyn Swapper>,
35 subscription_notifier: broadcast::Sender<String>,
36 liquid_chain_service: Arc<dyn LiquidChainService>,
37 claiming_swaps: Arc<Mutex<HashSet<String>>>,
38}
39
40#[sdk_macros::async_trait]
41impl BlockListener for ReceiveSwapHandler {
42 async fn on_bitcoin_block(&self, _height: u32) {}
43
44 async fn on_liquid_block(&self, height: u32) {
45 if let Err(e) = self.claim_confirmed_lockups(height).await {
46 error!("Error claiming confirmed lockups: {e:?}");
47 }
48 }
49}
50
51impl ReceiveSwapHandler {
52 pub(crate) fn new(
53 config: Config,
54 onchain_wallet: Arc<dyn OnchainWallet>,
55 persister: std::sync::Arc<Persister>,
56 swapper: Arc<dyn Swapper>,
57 liquid_chain_service: Arc<dyn LiquidChainService>,
58 ) -> Self {
59 let (subscription_notifier, _) = broadcast::channel::<String>(30);
60 Self {
61 config,
62 onchain_wallet,
63 persister,
64 swapper,
65 subscription_notifier,
66 liquid_chain_service,
67 claiming_swaps: Arc::new(Mutex::new(HashSet::new())),
68 }
69 }
70
71 pub(crate) fn subscribe_payment_updates(&self) -> broadcast::Receiver<String> {
72 self.subscription_notifier.subscribe()
73 }
74
75 pub(crate) async fn on_new_status(&self, update: &boltz::SwapStatus) -> Result<()> {
77 let id = &update.id;
78 let status = &update.status;
79 let swap_state = RevSwapStates::from_str(status)
80 .map_err(|_| anyhow!("Invalid RevSwapState for Receive Swap {id}: {status}"))?;
81 let receive_swap = self.fetch_receive_swap_by_id(id)?;
82
83 info!("Handling Receive Swap transition to {swap_state:?} for swap {id}");
84
85 match swap_state {
86 RevSwapStates::SwapExpired
87 | RevSwapStates::InvoiceExpired
88 | RevSwapStates::TransactionFailed
89 | RevSwapStates::TransactionRefunded => {
90 match receive_swap.mrh_tx_id {
91 Some(mrh_tx_id) => {
92 warn!("Swap {id} is expired but MRH payment was received: txid {mrh_tx_id}")
93 }
94 None => {
95 error!("Swap {id} entered into an unrecoverable state: {swap_state:?}");
96 self.update_swap_info(id, Failed, None, None, None, None)?;
97 }
98 }
99 Ok(())
100 }
101 RevSwapStates::TransactionMempool => {
104 let Some(transaction) = update.transaction.clone() else {
105 return Err(anyhow!("Unexpected payload from Boltz status stream"));
106 };
107
108 if let Some(claim_tx_id) = receive_swap.claim_tx_id {
109 return Err(anyhow!(
110 "Claim tx for Receive Swap {id} was already broadcast: txid {claim_tx_id}"
111 ));
112 }
113
114 if let Some(mrh_tx_id) = receive_swap.mrh_tx_id {
116 return Err(anyhow!(
117 "MRH tx for Receive Swap {id} was already broadcast, ignoring swap: txid {mrh_tx_id}"
118 ));
119 }
120
121 let tx_hex = transaction.hex.ok_or(anyhow!(
123 "Missing lockup transaction hex in swap status update"
124 ))?;
125 let lockup_tx = utils::deserialize_tx_hex(&tx_hex)
126 .context("Failed to deserialize tx hex in swap status update")?;
127 debug!(
128 "Broadcasting lockup tx received in swap status update for receive swap {id}"
129 );
130 if let Err(e) = self.liquid_chain_service.broadcast(&lockup_tx).await {
131 warn!(
132 "Failed to broadcast lockup tx in swap status update: {e:?} - maybe the \
133 tx depends on inputs that haven't been seen yet, falling back to waiting for \
134 it to appear in the mempool"
135 );
136 if let Err(e) = self
137 .verify_lockup_tx_status(&receive_swap, &transaction.id, &tx_hex, false)
138 .await
139 {
140 return Err(anyhow!(
141 "Swapper mempool reported lockup could not be verified. txid: {}, err: {}",
142 transaction.id,
143 e
144 ));
145 }
146 }
147
148 if let Err(e) = self
149 .verify_lockup_tx_amount(&receive_swap, &lockup_tx)
150 .await
151 {
152 self.update_swap_info(id, Failed, None, None, None, None)?;
154 return Err(anyhow!(
155 "Swapper underpaid lockup amount. txid: {}, err: {}",
156 transaction.id,
157 e
158 ));
159 }
160 info!("Swapper lockup was verified");
161
162 let lockup_tx_id = &transaction.id;
163 self.update_swap_info(id, Pending, None, Some(lockup_tx_id), None, None)?;
164
165 let max_amount_sat = self.config.zero_conf_max_amount_sat();
167 let receiver_amount_sat = receive_swap.receiver_amount_sat;
168 if receiver_amount_sat > max_amount_sat {
169 warn!("[Receive Swap {id}] Amount is too high to claim with zero-conf ({receiver_amount_sat} sat > {max_amount_sat} sat). Waiting for confirmation...");
170 return Ok(());
171 }
172
173 debug!("[Receive Swap {id}] Amount is within valid range for zero-conf ({receiver_amount_sat} < {max_amount_sat} sat)");
174
175 let rbf_explicit = lockup_tx.input.iter().any(|input| input.sequence.is_rbf());
178 if rbf_explicit {
181 warn!("[Receive Swap {id}] Lockup transaction signals RBF. Waiting for confirmation...");
182 return Ok(());
183 }
184 debug!("[Receive Swap {id}] Lockup tx does not signal RBF. Proceeding...");
185
186 if let Err(err) = self.claim(id).await {
187 match err {
188 PaymentError::AlreadyClaimed => {
189 warn!("Funds already claimed for Receive Swap {id}")
190 }
191 _ => error!("Claim for Receive Swap {id} failed: {err}"),
192 }
193 }
194
195 Ok(())
196 }
197 RevSwapStates::TransactionConfirmed => {
198 let Some(transaction) = update.transaction.clone() else {
199 return Err(anyhow!("Unexpected payload from Boltz status stream"));
200 };
201
202 if let Some(mrh_tx_id) = receive_swap.mrh_tx_id {
204 return Err(anyhow!(
205 "MRH tx for Receive Swap {id} was already broadcast, ignoring swap: txid {mrh_tx_id}"
206 ));
207 }
208
209 let tx_hex = transaction.hex.ok_or(anyhow!(
211 "Missing lockup transaction hex in swap status update"
212 ))?;
213 let lockup_tx = match self
214 .verify_lockup_tx_status(&receive_swap, &transaction.id, &tx_hex, true)
215 .await
216 {
217 Ok(lockup_tx) => lockup_tx,
218 Err(e) => {
219 return Err(anyhow!(
220 "Swapper reported lockup could not be verified. txid: {}, err: {}",
221 transaction.id,
222 e
223 ));
224 }
225 };
226
227 if let Err(e) = self
228 .verify_lockup_tx_amount(&receive_swap, &lockup_tx)
229 .await
230 {
231 self.update_swap_info(id, Failed, None, None, None, None)?;
233 return Err(anyhow!(
234 "Swapper underpaid lockup amount. txid: {}, err: {}",
235 transaction.id,
236 e
237 ));
238 }
239 info!("Swapper lockup was verified, moving to claim");
240
241 match receive_swap.claim_tx_id {
242 Some(claim_tx_id) => {
243 warn!("Claim tx for Receive Swap {id} was already broadcast: txid {claim_tx_id}")
244 }
245 None => {
246 self.update_swap_info(&receive_swap.id, Pending, None, None, None, None)?;
247
248 if let Err(err) = self.claim(id).await {
249 match err {
250 PaymentError::AlreadyClaimed => {
251 warn!("Funds already claimed for Receive Swap {id}")
252 }
253 _ => error!("Claim for Receive Swap {id} failed: {err}"),
254 }
255 }
256 }
257 }
258 Ok(())
259 }
260
261 _ => {
262 debug!("Unhandled state for Receive Swap {id}: {swap_state:?}");
263 Ok(())
264 }
265 }
266 }
267
268 fn fetch_receive_swap_by_id(&self, swap_id: &str) -> Result<ReceiveSwap, PaymentError> {
269 self.persister
270 .fetch_receive_swap_by_id(swap_id)
271 .map_err(|_| PaymentError::PersistError)?
272 .ok_or(PaymentError::Generic {
273 err: format!("Receive Swap not found {swap_id}"),
274 })
275 }
276
277 pub(crate) fn update_swap(&self, updated_swap: ReceiveSwap) -> Result<(), PaymentError> {
279 let swap = self.fetch_receive_swap_by_id(&updated_swap.id)?;
280 if updated_swap != swap {
281 info!(
282 "Updating Receive swap {} to {:?} (claim_tx_id = {:?}, lockup_tx_id = {:?}, mrh_tx_id = {:?})",
283 updated_swap.id, updated_swap.state, updated_swap.claim_tx_id, updated_swap.lockup_tx_id, updated_swap.mrh_tx_id
284 );
285 self.persister
286 .insert_or_update_receive_swap(&updated_swap)?;
287 let _ = self.subscription_notifier.send(updated_swap.id);
288 }
289 Ok(())
290 }
291
292 pub(crate) fn update_swap_info(
294 &self,
295 swap_id: &str,
296 to_state: PaymentState,
297 claim_tx_id: Option<&str>,
298 lockup_tx_id: Option<&str>,
299 mrh_tx_id: Option<&str>,
300 mrh_amount_sat: Option<u64>,
301 ) -> Result<(), PaymentError> {
302 info!(
303 "Transitioning Receive swap {swap_id} to {to_state:?} (claim_tx_id = {claim_tx_id:?}, lockup_tx_id = {lockup_tx_id:?}, mrh_tx_id = {mrh_tx_id:?})"
304 );
305 let swap = self.fetch_receive_swap_by_id(swap_id)?;
306 Self::validate_state_transition(swap.state, to_state)?;
307 self.persister.try_handle_receive_swap_update(
308 swap_id,
309 to_state,
310 claim_tx_id,
311 lockup_tx_id,
312 mrh_tx_id,
313 mrh_amount_sat,
314 )?;
315 let updated_swap = self.fetch_receive_swap_by_id(swap_id)?;
316
317 if mrh_tx_id.is_some() {
318 self.persister.delete_reserved_address(&swap.mrh_address)?;
319 }
320
321 if updated_swap != swap {
322 let _ = self.subscription_notifier.send(updated_swap.id);
323 }
324 Ok(())
325 }
326
327 async fn claim(&self, swap_id: &str) -> Result<(), PaymentError> {
328 {
329 let mut claiming_guard = self.claiming_swaps.lock().await;
330 if claiming_guard.contains(swap_id) {
331 debug!("Claim for swap {swap_id} already in progress, skipping.");
332 return Ok(());
333 }
334 claiming_guard.insert(swap_id.to_string());
335 }
336
337 let result = self.claim_inner(swap_id).await;
338
339 {
340 let mut claiming_guard = self.claiming_swaps.lock().await;
341 claiming_guard.remove(swap_id);
342 }
343
344 result
345 }
346
347 async fn claim_inner(&self, swap_id: &str) -> Result<(), PaymentError> {
348 let swap = self.fetch_receive_swap_by_id(swap_id)?;
349 ensure_sdk!(swap.claim_tx_id.is_none(), PaymentError::AlreadyClaimed);
350
351 info!("Initiating claim for Receive Swap {swap_id}");
352 let claim_address = match swap.claim_address {
353 Some(ref claim_address) => claim_address.clone(),
354 None => {
355 let address = self.onchain_wallet.next_unused_address().await?.to_string();
357 self.persister
358 .set_receive_swap_claim_address(&swap.id, &address)?;
359 address
360 }
361 };
362
363 let crate::prelude::Transaction::Liquid(claim_tx) = self
364 .swapper
365 .create_claim_tx(Swap::Receive(swap.clone()), Some(claim_address.clone()))
366 .await?
367 else {
368 return Err(PaymentError::Generic {
369 err: format!("Constructed invalid transaction for Receive swap {swap_id}"),
370 });
371 };
372
373 let tx_id = claim_tx.txid().to_hex();
376 match self.persister.set_receive_swap_claim_tx_id(swap_id, &tx_id) {
377 Ok(_) => {
378 let broadcast_res = match self.liquid_chain_service.broadcast(&claim_tx).await {
380 Ok(tx_id) => Ok(tx_id.to_hex()),
381 Err(e) if is_txn_mempool_conflict_error(&e) => {
382 Err(PaymentError::AlreadyClaimed)
383 }
384 Err(err) => {
385 debug!(
386 "Could not broadcast claim tx via chain service for Receive swap {swap_id}: {err:?}"
387 );
388 let claim_tx_hex = claim_tx.serialize().to_lower_hex_string();
389 self.swapper
390 .broadcast_tx(self.config.network.into(), &claim_tx_hex)
391 .await
392 }
393 };
394 match broadcast_res {
395 Ok(claim_tx_id) => {
396 self.persister.insert_or_update_payment(
399 PaymentTxData {
400 tx_id: claim_tx_id.clone(),
401 timestamp: Some(utils::now()),
402 fees_sat: 0,
403 is_confirmed: false,
404 unblinding_data: None,
405 },
406 &[PaymentTxBalance {
407 amount: swap.receiver_amount_sat,
408 payment_type: PaymentType::Receive,
409 asset_id: self.config.lbtc_asset_id(),
410 }],
411 None,
412 false,
413 )?;
414
415 info!("Successfully broadcast claim tx {claim_tx_id} for Receive Swap {swap_id}");
416 _ = self.subscription_notifier.send(claim_tx_id);
419 Ok(())
420 }
421 Err(err) => {
422 debug!(
424 "Could not broadcast claim tx via swapper for Receive swap {swap_id}: {err:?}"
425 );
426 self.persister
427 .unset_receive_swap_claim_tx_id(swap_id, &tx_id)?;
428 Err(err)
429 }
430 }
431 }
432 Err(err) => {
433 debug!(
434 "Failed to set claim_tx_id after creating tx for Receive swap {swap_id}: txid {tx_id}"
435 );
436 Err(err)
437 }
438 }
439 }
440
441 async fn claim_confirmed_lockups(&self, height: u32) -> Result<()> {
442 let receive_swaps: Vec<ReceiveSwap> = self
443 .persister
444 .list_ongoing_receive_swaps()?
445 .into_iter()
446 .filter(|s| s.lockup_tx_id.is_some() && s.claim_tx_id.is_none())
447 .collect();
448 info!(
449 "Rescanning {} Receive Swap(s) lockup txs at height {}",
450 receive_swaps.len(),
451 height
452 );
453 for swap in receive_swaps {
454 if let Err(e) = self.claim_confirmed_lockup(&swap).await {
455 error!("Error rescanning Receive Swap {}: {e:?}", swap.id,);
456 }
457 }
458 Ok(())
459 }
460
461 async fn claim_confirmed_lockup(&self, receive_swap: &ReceiveSwap) -> Result<()> {
462 let Some(tx_id) = receive_swap.lockup_tx_id.clone() else {
463 return Ok(());
465 };
466 let swap_id = &receive_swap.id;
467 let tx_hex = self
468 .liquid_chain_service
469 .get_transaction_hex(&Txid::from_str(&tx_id)?)
470 .await?
471 .ok_or(anyhow!("Lockup tx not found for Receive swap {swap_id}"))?
472 .serialize()
473 .to_lower_hex_string();
474 let lockup_tx = self
475 .verify_lockup_tx_status(receive_swap, &tx_id, &tx_hex, true)
476 .await?;
477 if let Err(e) = self.verify_lockup_tx_amount(receive_swap, &lockup_tx).await {
478 self.update_swap_info(swap_id, Failed, None, None, None, None)?;
479 return Err(e);
480 }
481 info!("Receive Swap {swap_id} lockup tx is confirmed");
482 self.claim(swap_id)
483 .await
484 .map_err(|e| anyhow!("Could not claim Receive Swap {swap_id}: {e:?}"))
485 }
486
487 fn validate_state_transition(
488 from_state: PaymentState,
489 to_state: PaymentState,
490 ) -> Result<(), PaymentError> {
491 match (from_state, to_state) {
492 (_, Created) => Err(PaymentError::Generic {
493 err: "Cannot transition to Created state".to_string(),
494 }),
495
496 (Created | Pending, Pending) => Ok(()),
497 (_, Pending) => Err(PaymentError::Generic {
498 err: format!("Cannot transition from {from_state:?} to Pending state"),
499 }),
500
501 (Created | Pending, Complete) => Ok(()),
502 (_, Complete) => Err(PaymentError::Generic {
503 err: format!("Cannot transition from {from_state:?} to Complete state"),
504 }),
505
506 (Created | TimedOut, TimedOut) => Ok(()),
507 (_, TimedOut) => Err(PaymentError::Generic {
508 err: format!("Cannot transition from {from_state:?} to TimedOut state"),
509 }),
510
511 (_, Refundable) => Err(PaymentError::Generic {
512 err: format!("Cannot transition from {from_state:?} to Refundable state"),
513 }),
514
515 (_, RefundPending) => Err(PaymentError::Generic {
516 err: format!("Cannot transition from {from_state:?} to RefundPending state"),
517 }),
518
519 (Complete, Failed) => Err(PaymentError::Generic {
520 err: format!("Cannot transition from {from_state:?} to Failed state"),
521 }),
522 (_, Failed) => Ok(()),
523
524 (_, WaitingFeeAcceptance) => Err(PaymentError::Generic {
525 err: format!("Cannot transition from {from_state:?} to WaitingFeeAcceptance state"),
526 }),
527 }
528 }
529
530 async fn verify_lockup_tx_status(
531 &self,
532 receive_swap: &ReceiveSwap,
533 tx_id: &str,
534 tx_hex: &str,
535 verify_confirmation: bool,
536 ) -> Result<Transaction> {
537 let script = receive_swap.get_swap_script()?;
539 let address = script
540 .to_address(self.config.network.into())
541 .map_err(|e| anyhow!("Failed to get swap script address {e:?}"))?;
542 self.liquid_chain_service
543 .verify_tx(&address, tx_id, tx_hex, verify_confirmation)
544 .await
545 }
546
547 async fn verify_lockup_tx_amount(
548 &self,
549 receive_swap: &ReceiveSwap,
550 lockup_tx: &Transaction,
551 ) -> Result<()> {
552 let secp = Secp256k1::new();
553 let script = receive_swap.get_swap_script()?;
554 let address = script
555 .to_address(self.config.network.into())
556 .map_err(|e| anyhow!("Failed to get swap script address {e:?}"))?;
557 let blinding_key = receive_swap
558 .get_boltz_create_response()?
559 .blinding_key
560 .ok_or(anyhow!("Missing blinding key"))?;
561 let tx_out = lockup_tx
562 .output
563 .iter()
564 .find(|tx_out| tx_out.script_pubkey == address.script_pubkey())
565 .ok_or(anyhow!("Failed to get tx output"))?;
566 let lockup_amount_sat = tx_out
567 .unblind(&secp, SecretKey::from_str(&blinding_key)?)
568 .map(|o| o.value)?;
569 let expected_lockup_amount_sat =
570 receive_swap.receiver_amount_sat + receive_swap.claim_fees_sat;
571 if lockup_amount_sat < expected_lockup_amount_sat {
572 bail!(
573 "Failed to verify lockup amount for Receive Swap {}: {} sat vs {} sat",
574 receive_swap.id,
575 expected_lockup_amount_sat,
576 lockup_amount_sat
577 );
578 }
579 Ok(())
580 }
581}
582
583#[cfg(test)]
584mod tests {
585 use std::collections::{HashMap, HashSet};
586
587 use anyhow::Result;
588
589 use crate::{
590 model::PaymentState::{self, *},
591 test_utils::{
592 persist::{create_persister, new_receive_swap},
593 receive_swap::new_receive_swap_handler,
594 },
595 };
596
597 #[cfg(feature = "browser-tests")]
598 wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
599
600 #[sdk_macros::async_test_all]
601 async fn test_receive_swap_state_transitions() -> Result<()> {
602 create_persister!(persister);
603
604 let receive_swap_state_handler = new_receive_swap_handler(persister.clone())?;
605
606 let valid_combinations = HashMap::from([
608 (
609 Created,
610 HashSet::from([Pending, Complete, TimedOut, Failed]),
611 ),
612 (Pending, HashSet::from([Pending, Complete, Failed])),
613 (TimedOut, HashSet::from([TimedOut, Failed])),
614 (Complete, HashSet::from([])),
615 (Refundable, HashSet::from([Failed])),
616 (RefundPending, HashSet::from([Failed])),
617 (Failed, HashSet::from([Failed])),
618 ]);
619
620 for (first_state, allowed_states) in valid_combinations.iter() {
621 for allowed_state in allowed_states {
622 let receive_swap = new_receive_swap(Some(*first_state), None);
623 persister.insert_or_update_receive_swap(&receive_swap)?;
624
625 assert!(receive_swap_state_handler
626 .update_swap_info(&receive_swap.id, *allowed_state, None, None, None, None)
627 .is_ok());
628 }
629 }
630
631 let all_states = HashSet::from([Created, Pending, Complete, TimedOut, Failed]);
633 let invalid_combinations: HashMap<PaymentState, HashSet<PaymentState>> = valid_combinations
634 .iter()
635 .map(|(first_state, allowed_states)| {
636 (
637 *first_state,
638 all_states.difference(allowed_states).cloned().collect(),
639 )
640 })
641 .collect();
642
643 for (first_state, disallowed_states) in invalid_combinations.iter() {
644 for disallowed_state in disallowed_states {
645 let receive_swap = new_receive_swap(Some(*first_state), None);
646 persister.insert_or_update_receive_swap(&receive_swap)?;
647
648 assert!(receive_swap_state_handler
649 .update_swap_info(&receive_swap.id, *disallowed_state, None, None, None, None)
650 .is_err());
651 }
652 }
653
654 Ok(())
655 }
656}