breez_sdk_liquid/
receive_swap.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use std::{str::FromStr, sync::Arc};

use anyhow::{anyhow, Result};
use boltz_client::swaps::boltz::RevSwapStates;
use boltz_client::swaps::boltz::{self, SwapUpdateTxDetails};
use boltz_client::{Serialize, ToHex};
use log::{debug, error, info, warn};
use lwk_wollet::hashes::hex::DisplayHex;
use tokio::sync::{broadcast, Mutex};

use crate::chain::liquid::LiquidChainService;
use crate::model::PaymentState::{
    Complete, Created, Failed, Pending, RefundPending, Refundable, TimedOut,
};
use crate::model::{Config, PaymentTxData, PaymentType, ReceiveSwap};
use crate::prelude::{Swap, Transaction};
use crate::{ensure_sdk, utils};
use crate::{
    error::PaymentError, model::PaymentState, persist::Persister, swapper::Swapper,
    wallet::OnchainWallet,
};

/// The minimum acceptable fee rate when claiming using zero-conf
pub const DEFAULT_ZERO_CONF_MIN_FEE_RATE_TESTNET: u32 = 100;
pub const DEFAULT_ZERO_CONF_MIN_FEE_RATE_MAINNET: u32 = 10;
/// The maximum acceptable amount in satoshi when claiming using zero-conf
pub const DEFAULT_ZERO_CONF_MAX_SAT: u64 = 100_000;

pub(crate) struct ReceiveSwapHandler {
    config: Config,
    onchain_wallet: Arc<dyn OnchainWallet>,
    persister: Arc<Persister>,
    swapper: Arc<dyn Swapper>,
    subscription_notifier: broadcast::Sender<String>,
    liquid_chain_service: Arc<Mutex<dyn LiquidChainService>>,
}

impl ReceiveSwapHandler {
    pub(crate) fn new(
        config: Config,
        onchain_wallet: Arc<dyn OnchainWallet>,
        persister: Arc<Persister>,
        swapper: Arc<dyn Swapper>,
        liquid_chain_service: Arc<Mutex<dyn LiquidChainService>>,
    ) -> Self {
        let (subscription_notifier, _) = broadcast::channel::<String>(30);
        Self {
            config,
            onchain_wallet,
            persister,
            swapper,
            subscription_notifier,
            liquid_chain_service,
        }
    }

    pub(crate) fn subscribe_payment_updates(&self) -> broadcast::Receiver<String> {
        self.subscription_notifier.subscribe()
    }

    /// Handles status updates from Boltz for Receive swaps
    pub(crate) async fn on_new_status(&self, update: &boltz::Update) -> Result<()> {
        let id = &update.id;
        let swap_state = &update.status;
        let receive_swap = self
            .persister
            .fetch_receive_swap_by_id(id)?
            .ok_or(anyhow!("No ongoing Receive Swap found for ID {id}"))?;

        info!("Handling Receive Swap transition to {swap_state:?} for swap {id}");

        match RevSwapStates::from_str(swap_state) {
            Ok(
                RevSwapStates::SwapExpired
                | RevSwapStates::InvoiceExpired
                | RevSwapStates::TransactionFailed
                | RevSwapStates::TransactionRefunded,
            ) => {
                match receive_swap.mrh_tx_id {
                    Some(mrh_tx_id) => {
                        warn!("Swap {id} is expired but MRH payment was received: txid {mrh_tx_id}")
                    }
                    None => {
                        error!("Swap {id} entered into an unrecoverable state: {swap_state:?}");
                        self.update_swap_info(id, Failed, None, None, None, None)
                            .await?;
                    }
                }
                Ok(())
            }
            // The lockup tx is in the mempool and we accept 0-conf => try to claim
            // Execute 0-conf preconditions check
            Ok(RevSwapStates::TransactionMempool) => {
                let Some(transaction) = update.transaction.clone() else {
                    return Err(anyhow!("Unexpected payload from Boltz status stream"));
                };

                if let Some(claim_tx_id) = receive_swap.claim_tx_id {
                    return Err(anyhow!(
                        "Claim tx for Receive Swap {id} was already broadcast: txid {claim_tx_id}"
                    ));
                }

                // Do not continue or claim the swap if it was already paid via MRH
                if let Some(mrh_tx_id) = receive_swap.mrh_tx_id {
                    return Err(anyhow!(
                        "MRH tx for Receive Swap {id} was already broadcast, ignoring swap: txid {mrh_tx_id}"
                    ));
                }

                // looking for lockup script history to verify lockup was broadcasted
                if let Err(e) = self
                    .verify_lockup_tx(&receive_swap, &transaction, false)
                    .await
                {
                    return Err(anyhow!(
                        "swapper mempool reported lockup could not be verified. txid: {}, err: {}",
                        transaction.id,
                        e
                    ));
                }
                info!("swapper lockup was verified");

                let lockup_tx_id = &transaction.id;
                self.update_swap_info(id, Pending, None, Some(lockup_tx_id), None, None)
                    .await?;

                let lockup_tx = utils::deserialize_tx_hex(&transaction.hex)?;

                // If the amount is greater than the zero-conf limit
                let max_amount_sat = self.config.zero_conf_max_amount_sat();
                let receiver_amount_sat = receive_swap.receiver_amount_sat;
                if receiver_amount_sat > max_amount_sat {
                    warn!("[Receive Swap {id}] Amount is too high to claim with zero-conf ({receiver_amount_sat} sat > {max_amount_sat} sat). Waiting for confirmation...");
                    return Ok(());
                }

                debug!("[Receive Swap {id}] Amount is within valid range for zero-conf ({receiver_amount_sat} < {max_amount_sat} sat)");

                // If the transaction has RBF, see https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki
                // TODO: Check for inherent RBF by ensuring all tx ancestors are confirmed
                let rbf_explicit = lockup_tx.input.iter().any(|input| input.sequence.is_rbf());
                // let rbf_inherent = lockup_tx_history.height < 0;

                if rbf_explicit {
                    warn!("[Receive Swap {id}] Lockup transaction signals RBF. Waiting for confirmation...");
                    return Ok(());
                }

                debug!("[Receive Swap {id}] Lockup tx does not signal RBF. Proceeding...");

                // If the fees are higher than our estimated value
                let tx_fees: u64 = lockup_tx.all_fees().values().sum();
                let min_fee_rate = self.config.zero_conf_min_fee_rate_msat as f32 / 1000.0;
                let lower_bound_estimated_fees = lockup_tx.vsize() as f32 * min_fee_rate * 0.8;

                if lower_bound_estimated_fees > tx_fees as f32 {
                    warn!("[Receive Swap {id}] Lockup tx fees are too low: Expected at least {lower_bound_estimated_fees} sat, got {tx_fees} sat. Waiting for confirmation...");
                    return Ok(());
                }

                debug!("[Receive Swap {id}] Lockup tx fees are within acceptable range ({tx_fees} > {lower_bound_estimated_fees} sat). Proceeding with claim.");

                match self.claim(id).await {
                    Ok(_) => {}
                    Err(err) => match err {
                        PaymentError::AlreadyClaimed => {
                            warn!("Funds already claimed for Receive Swap {id}")
                        }
                        _ => error!("Claim for Receive Swap {id} failed: {err}"),
                    },
                }

                Ok(())
            }
            Ok(RevSwapStates::TransactionConfirmed) => {
                let Some(transaction) = update.transaction.clone() else {
                    return Err(anyhow!("Unexpected payload from Boltz status stream"));
                };

                // Do not continue or claim the swap if it was already paid via MRH
                if let Some(mrh_tx_id) = receive_swap.mrh_tx_id {
                    return Err(anyhow!(
                        "MRH tx for Receive Swap {id} was already broadcast, ignoring swap: txid {mrh_tx_id}"
                    ));
                }

                // looking for lockup script history to verify lockup was broadcasted and confirmed
                if let Err(e) = self
                    .verify_lockup_tx(&receive_swap, &transaction, true)
                    .await
                {
                    return Err(anyhow!(
                        "swapper reported lockup could not be verified. txid: {}, err: {}",
                        transaction.id,
                        e
                    ));
                }
                info!("swapper lockup was verified, moving to claim");

                match receive_swap.claim_tx_id {
                    Some(claim_tx_id) => {
                        warn!("Claim tx for Receive Swap {id} was already broadcast: txid {claim_tx_id}")
                    }
                    None => {
                        self.update_swap_info(&receive_swap.id, Pending, None, None, None, None)
                            .await?;
                        match self.claim(id).await {
                            Ok(_) => {}
                            Err(err) => match err {
                                PaymentError::AlreadyClaimed => {
                                    warn!("Funds already claimed for Receive Swap {id}")
                                }
                                _ => error!("Claim for Receive Swap {id} failed: {err}"),
                            },
                        }
                    }
                }
                Ok(())
            }

            Ok(_) => {
                debug!("Unhandled state for Receive Swap {id}: {swap_state}");
                Ok(())
            }

            _ => Err(anyhow!(
                "Invalid RevSwapState for Receive Swap {id}: {swap_state}"
            )),
        }
    }

    /// Transitions a Receive swap to a new state
    pub(crate) async fn update_swap_info(
        &self,
        swap_id: &str,
        to_state: PaymentState,
        claim_tx_id: Option<&str>,
        lockup_tx_id: Option<&str>,
        mrh_tx_id: Option<&str>,
        mrh_amount_sat: Option<u64>,
    ) -> Result<(), PaymentError> {
        info!(
            "Transitioning Receive swap {} to {:?} (claim_tx_id = {:?}, lockup_tx_id = {:?}, mrh_tx_id = {:?})",
            swap_id, to_state, claim_tx_id, lockup_tx_id, mrh_tx_id
        );

        let swap = self
            .persister
            .fetch_receive_swap_by_id(swap_id)
            .map_err(|_| PaymentError::PersistError)?
            .ok_or(PaymentError::Generic {
                err: format!("Receive Swap not found {swap_id}"),
            })?;
        let payment_id = claim_tx_id
            .or(lockup_tx_id)
            .or(mrh_tx_id)
            .map(|id| id.to_string())
            .or(swap.claim_tx_id);

        Self::validate_state_transition(swap.state, to_state)?;
        self.persister.try_handle_receive_swap_update(
            swap_id,
            to_state,
            claim_tx_id,
            lockup_tx_id,
            mrh_tx_id,
            mrh_amount_sat,
        )?;

        if let Some(payment_id) = payment_id {
            let _ = self.subscription_notifier.send(payment_id);
        }
        Ok(())
    }

    async fn claim(&self, swap_id: &str) -> Result<(), PaymentError> {
        let swap = self
            .persister
            .fetch_receive_swap_by_id(swap_id)?
            .ok_or(anyhow!("No Receive Swap found for ID {swap_id}"))?;
        ensure_sdk!(swap.claim_tx_id.is_none(), PaymentError::AlreadyClaimed);

        info!("Initiating claim for Receive Swap {swap_id}");
        let claim_address = self.onchain_wallet.next_unused_address().await?.to_string();
        let Transaction::Liquid(claim_tx) = self
            .swapper
            .create_claim_tx(Swap::Receive(swap.clone()), Some(claim_address))?
        else {
            return Err(PaymentError::Generic {
                err: format!("Constructed invalid transaction for Receive swap {swap_id}"),
            });
        };

        // Set the swap claim_tx_id before broadcasting.
        // If another claim_tx_id has been set in the meantime, don't broadcast the claim tx
        let tx_id = claim_tx.txid().to_hex();
        match self.persister.set_receive_swap_claim_tx_id(swap_id, &tx_id) {
            Ok(_) => {
                // We attempt broadcasting via chain service, then fallback to Boltz
                let liquid_chain_service = self.liquid_chain_service.lock().await;
                let broadcast_res = liquid_chain_service
                    .broadcast(&claim_tx, Some(&swap.id))
                    .await
                    .map(|tx_id| tx_id.to_hex())
                    .or_else(|err| {
                        debug!(
                            "Could not broadcast claim tx via chain service for Receive swap {swap_id}: {err:?}"
                        );
                        let claim_tx_hex = claim_tx.serialize().to_lower_hex_string();
                        self.swapper.broadcast_tx(self.config.network.into(), &claim_tx_hex)
                    });

                match broadcast_res {
                    Ok(claim_tx_id) => {
                        // We insert a pseudo-claim-tx in case LWK fails to pick up the new mempool tx for a while
                        // This makes the tx known to the SDK (get_info, list_payments) instantly
                        self.persister.insert_or_update_payment(
                            PaymentTxData {
                                tx_id: claim_tx_id.clone(),
                                timestamp: Some(utils::now()),
                                amount_sat: swap.receiver_amount_sat,
                                fees_sat: 0,
                                payment_type: PaymentType::Receive,
                                is_confirmed: false,
                            },
                            None,
                            None,
                        )?;

                        info!("Successfully broadcast claim tx {claim_tx_id} for Receive Swap {swap_id}");
                        self.update_swap_info(
                            swap_id,
                            Pending,
                            Some(&claim_tx_id),
                            None,
                            None,
                            None,
                        )
                        .await
                    }
                    Err(err) => {
                        // Multiple attempts to broadcast have failed. Unset the swap claim_tx_id
                        debug!(
                            "Could not broadcast claim tx via swapper for Receive swap {swap_id}: {err:?}"
                        );
                        self.persister
                            .unset_receive_swap_claim_tx_id(swap_id, &tx_id)?;
                        Err(err)
                    }
                }
            }
            Err(err) => {
                debug!(
                    "Failed to set claim_tx_id after creating tx for Receive swap {swap_id}: txid {tx_id}"
                );
                Err(err)
            }
        }
    }

    fn validate_state_transition(
        from_state: PaymentState,
        to_state: PaymentState,
    ) -> Result<(), PaymentError> {
        match (from_state, to_state) {
            (_, Created) => Err(PaymentError::Generic {
                err: "Cannot transition to Created state".to_string(),
            }),

            (Created | Pending, Pending) => Ok(()),
            (_, Pending) => Err(PaymentError::Generic {
                err: format!("Cannot transition from {from_state:?} to Pending state"),
            }),

            (Created | Pending, Complete) => Ok(()),
            (_, Complete) => Err(PaymentError::Generic {
                err: format!("Cannot transition from {from_state:?} to Complete state"),
            }),

            (Created | TimedOut, TimedOut) => Ok(()),
            (_, TimedOut) => Err(PaymentError::Generic {
                err: format!("Cannot transition from {from_state:?} to TimedOut state"),
            }),

            (_, Refundable) => Err(PaymentError::Generic {
                err: format!("Cannot transition from {from_state:?} to Refundable state"),
            }),

            (_, RefundPending) => Err(PaymentError::Generic {
                err: format!("Cannot transition from {from_state:?} to RefundPending state"),
            }),

            (Complete, Failed) => Err(PaymentError::Generic {
                err: format!("Cannot transition from {from_state:?} to Failed state"),
            }),
            (_, Failed) => Ok(()),
        }
    }

    async fn verify_lockup_tx(
        &self,
        receive_swap: &ReceiveSwap,
        swap_update_tx: &SwapUpdateTxDetails,
        verify_confirmation: bool,
    ) -> Result<()> {
        // Looking for lockup script history to verify lockup was broadcasted
        let script = receive_swap.get_swap_script()?;
        let address =
            script
                .to_address(self.config.network.into())
                .map_err(|e| PaymentError::Generic {
                    err: format!("Failed to get swap script address {e:?}"),
                })?;
        self.liquid_chain_service
            .lock()
            .await
            .verify_tx(
                &address,
                &swap_update_tx.id,
                &swap_update_tx.hex,
                verify_confirmation,
            )
            .await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::{
        collections::{HashMap, HashSet},
        sync::Arc,
    };

    use anyhow::Result;

    use crate::{
        model::PaymentState::{self, *},
        test_utils::{
            persist::{new_persister, new_receive_swap},
            receive_swap::new_receive_swap_handler,
        },
    };

    #[tokio::test]
    async fn test_receive_swap_state_transitions() -> Result<()> {
        let (_temp_dir, storage) = new_persister()?;
        let storage = Arc::new(storage);

        let receive_swap_state_handler = new_receive_swap_handler(storage.clone())?;

        // Test valid combinations of states
        let valid_combinations = HashMap::from([
            (
                Created,
                HashSet::from([Pending, Complete, TimedOut, Failed]),
            ),
            (Pending, HashSet::from([Pending, Complete, Failed])),
            (TimedOut, HashSet::from([TimedOut, Failed])),
            (Complete, HashSet::from([])),
            (Refundable, HashSet::from([Failed])),
            (RefundPending, HashSet::from([Failed])),
            (Failed, HashSet::from([Failed])),
        ]);

        for (first_state, allowed_states) in valid_combinations.iter() {
            for allowed_state in allowed_states {
                let receive_swap = new_receive_swap(Some(*first_state));
                storage.insert_receive_swap(&receive_swap)?;

                assert!(receive_swap_state_handler
                    .update_swap_info(&receive_swap.id, *allowed_state, None, None, None, None)
                    .await
                    .is_ok());
            }
        }

        // Test invalid combinations of states
        let all_states = HashSet::from([Created, Pending, Complete, TimedOut, Failed]);
        let invalid_combinations: HashMap<PaymentState, HashSet<PaymentState>> = valid_combinations
            .iter()
            .map(|(first_state, allowed_states)| {
                (
                    *first_state,
                    all_states.difference(allowed_states).cloned().collect(),
                )
            })
            .collect();

        for (first_state, disallowed_states) in invalid_combinations.iter() {
            for disallowed_state in disallowed_states {
                let receive_swap = new_receive_swap(Some(*first_state));
                storage.insert_receive_swap(&receive_swap)?;

                assert!(receive_swap_state_handler
                    .update_swap_info(&receive_swap.id, *disallowed_state, None, None, None, None)
                    .await
                    .is_err());
            }
        }

        Ok(())
    }
}