Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Receive Chain Swap: support refund even when lockup address is re-used #471

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cli/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ frb = ["dep:flutter_rust_bridge"]
[dependencies]
anyhow = { workspace = true }
bip39 = "2.0.0"
boltz-client = { git = "https://github.com/hydra-yse/boltz-rust", branch = "yse-fee-calculation" }
boltz-client = { git = "https://github.com/ok300/boltz-rust", branch = "ok300-chain-swap-refund-check-all-utoxs" }
ok300 marked this conversation as resolved.
Show resolved Hide resolved
chrono = "0.4"
env_logger = "0.11"
flutter_rust_bridge = { version = "=2.4.0", features = [
Expand Down
27 changes: 21 additions & 6 deletions lib/core/src/chain_swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ impl ChainSwapHandler {
loop {
tokio::select! {
_ = rescan_interval.tick() => {
if let Err(e) = cloned.rescan_incoming_chain_swaps().await {
if let Err(e) = cloned.rescan_incoming_chain_swaps(false).await {
error!("Error checking incoming chain swaps: {e:?}");
}
if let Err(e) = cloned.rescan_outgoing_chain_swaps().await {
Expand Down Expand Up @@ -110,7 +110,10 @@ impl ChainSwapHandler {
}
}

pub(crate) async fn rescan_incoming_chain_swaps(&self) -> Result<()> {
pub(crate) async fn rescan_incoming_chain_swaps(
&self,
ignore_monitoring_block_height: bool,
) -> Result<()> {
let current_height = self.bitcoin_chain_service.lock().await.tip()?.height as u32;
let chain_swaps: Vec<ChainSwap> = self
.persister
Expand All @@ -124,22 +127,34 @@ impl ChainSwapHandler {
current_height
);
for swap in chain_swaps {
if let Err(e) = self.rescan_incoming_chain_swap(&swap, current_height).await {
if let Err(e) = self
.rescan_incoming_chain_swap(&swap, current_height, ignore_monitoring_block_height)
.await
{
error!("Error rescanning incoming Chain Swap {}: {e:?}", swap.id);
}
}
Ok(())
}

/// ### Arguments
/// - `swap`: the swap being rescanned
/// - `current_height`: the tip
/// - `ignore_monitoring_block_height`: if true, it rescans an expired swap even after the
/// cutoff monitoring block height
async fn rescan_incoming_chain_swap(
&self,
swap: &ChainSwap,
current_height: u32,
ignore_monitoring_block_height: bool,
) -> Result<()> {
let monitoring_block_height =
swap.timeout_block_height + CHAIN_SWAP_MONITORING_PERIOD_BITCOIN_BLOCKS;
let is_swap_expired = current_height > swap.timeout_block_height;
let is_monitoring_expired = current_height > monitoring_block_height;
let is_monitoring_expired = match ignore_monitoring_block_height {
true => false,
false => current_height > monitoring_block_height,
};

if (is_swap_expired && !is_monitoring_expired) || swap.state == RefundPending {
let script_pubkey = swap.get_receive_lockup_swap_script_pubkey(self.config.network)?;
Expand Down Expand Up @@ -730,7 +745,7 @@ impl ChainSwapHandler {
Ok(())
}

pub async fn prepare_refund(
pub(crate) async fn prepare_refund(
&self,
lockup_address: &str,
refund_address: &str,
Expand Down Expand Up @@ -771,7 +786,7 @@ impl ChainSwapHandler {
.persister
.fetch_chain_swap_by_lockup_address(lockup_address)?
.ok_or(PaymentError::Generic {
err: format!("Swap {} not found", lockup_address),
err: format!("Swap for lockup address {} not found", lockup_address),
})?;

ensure_sdk!(
Expand Down
33 changes: 30 additions & 3 deletions lib/core/src/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1822,14 +1822,41 @@ impl LiquidSdk {
)
})
.await?;

let swap = self
.persister
.fetch_chain_swap_by_lockup_address(&req.swap_address)?
.ok_or(PaymentError::Generic {
err: format!("Swap for lockup address {} not found", &req.swap_address),
})?;

// Set the payment state to `RefundPending`. This ensures:
// - the swap is not shown in `list-refundables` anymore
// - the background thread will move it to Failed once the refund tx confirms
self.chain_swap_handler
.update_swap_info(
&swap.id,
RefundPending,
None,
None,
None,
Some(&refund_tx_id),
)
.await?;

ok300 marked this conversation as resolved.
Show resolved Hide resolved
Ok(RefundResponse { refund_tx_id })
}

/// Rescans all expired chain swaps created from calling [LiquidSdk::receive_onchain] within
/// the monitoring period to check if there are any confirmed funds available to refund.
/// Rescans all expired chain swaps created from calling [LiquidSdk::receive_onchain] to check
/// if there are any confirmed funds available to refund.
///
/// Since it bypasses the monitoring period, this should be called rarely or when the caller
/// expects there is a very old refundable chain swap. Otherwise, for relatively recent swaps
/// (within last [CHAIN_SWAP_MONITORING_PERIOD_BITCOIN_BLOCKS] blocks = ~30 days), calling this
/// is not necessary as it happens automatically in the background.
pub async fn rescan_onchain_swaps(&self) -> SdkResult<()> {
self.chain_swap_handler
.rescan_incoming_chain_swaps()
.rescan_incoming_chain_swaps(true)
.await?;
Ok(())
}
Expand Down
10 changes: 5 additions & 5 deletions lib/core/src/swapper/boltz/bitcoin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,17 @@ impl BoltzSwapper {
SdkError::generic("Address network validation failed")
);

let utxo = utxos
.first()
.and_then(|utxo| utxo.as_bitcoin().cloned())
.ok_or(SdkError::generic("No UTXO found"))?;
let utxos = utxos
.iter()
.filter_map(|utxo| utxo.as_bitcoin().cloned())
.collect();

let swap_script = swap.get_lockup_swap_script()?.as_bitcoin_script()?;
let refund_tx = BtcSwapTx {
kind: SwapTxKind::Refund,
swap_script,
output_address: address.assume_checked(),
utxo,
utxos,
};

let refund_keypair = swap.get_refund_keypair()?;
Expand Down
Loading