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

Send: Fix double-lockup when payment is TimedOut #541

Merged
merged 6 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
43 changes: 43 additions & 0 deletions lib/core/src/persist/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,49 @@ impl Persister {

Ok(())
}

pub(crate) fn set_send_swap_lockup_tx_id(
&self,
swap_id: &str,
lockup_tx_id: &str,
) -> Result<(), PaymentError> {
let con = self.get_connection()?;

let row_count = con
.execute(
"UPDATE send_swaps
SET lockup_tx_id = :lockup_tx_id
WHERE id = :id AND lockup_tx_id IS NULL",
named_params! {
":id": swap_id,
":lockup_tx_id": lockup_tx_id,
},
)
.map_err(|_| PaymentError::PersistError)?;
match row_count {
1 => Ok(()),
_ => Err(PaymentError::PaymentInProgress),
}
}

pub(crate) fn unset_send_swap_lockup_tx_id(
&self,
swap_id: &str,
lockup_tx_id: &str,
) -> Result<(), PaymentError> {
let con = self.get_connection()?;
con.execute(
"UPDATE send_swaps
SET lockup_tx_id = NULL
WHERE id = :id AND lockup_tx_id = :lockup_tx_id",
named_params! {
":id": swap_id,
":lockup_tx_id": lockup_tx_id,
},
)
.map_err(|_| PaymentError::PersistError)?;
Ok(())
}
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand Down
76 changes: 55 additions & 21 deletions lib/core/src/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1006,14 +1006,20 @@ impl LiquidSdk {

let swap = match self.persister.fetch_send_swap_by_invoice(invoice)? {
Some(swap) => match swap.state {
Created => swap,
hydra-yse marked this conversation as resolved.
Show resolved Hide resolved
TimedOut => {
self.send_swap_handler
.update_swap_info(&swap.id, PaymentState::Created, None, None, None)
.await?;
swap
}
Pending => return Err(PaymentError::PaymentInProgress),
Complete => return Err(PaymentError::AlreadyPaid),
RefundPending | Failed => {
RefundPending | Refundable | Failed => {
return Err(PaymentError::invalid_invoice(
"Payment has already failed. Please try with another invoice",
))
}
_ => swap,
},
None => {
let keypair = utils::generate_keypair();
Expand Down Expand Up @@ -1072,12 +1078,53 @@ impl LiquidSdk {
};
self.status_stream.track_swap_id(&swap.id)?;

let accept_zero_conf = swap.get_boltz_create_response()?.accept_zero_conf;
self.wait_for_payment(Swap::Send(swap), accept_zero_conf)
let create_response = swap.get_boltz_create_response()?;
self.try_lockup(&swap, &create_response).await?;
hydra-yse marked this conversation as resolved.
Show resolved Hide resolved

self.wait_for_payment(Swap::Send(swap), create_response.accept_zero_conf)
.await
.map(|payment| SendPaymentResponse { payment })
}

async fn try_lockup(
&self,
swap: &SendSwap,
create_response: &CreateSubmarineResponse,
) -> Result<(), PaymentError> {
if swap.lockup_tx_id.is_some() {
debug!("Lockup tx was already broadcast for Send Swap {}", swap.id);
return Ok(());
}

let lockup_tx = self
.send_swap_handler
.lockup_funds(&swap.id, create_response)
.await?;
let lockup_tx_id = lockup_tx.txid().to_string();
let lockup_tx_fees_sat: u64 = lockup_tx.all_fees().values().sum();

// We insert a pseudo-lockup-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: lockup_tx_id.clone(),
timestamp: Some(utils::now()),
amount_sat: swap.payer_amount_sat,
fees_sat: lockup_tx_fees_sat,
payment_type: PaymentType::Send,
is_confirmed: false,
},
None,
None,
)?;

self.send_swap_handler
.update_swap_info(&swap.id, Pending, None, Some(&lockup_tx_id), None)
.await?;

Ok(())
}

/// Fetch the current payment limits for [LiquidSdk::send_payment] and [LiquidSdk::receive_payment].
pub async fn fetch_lightning_limits(
&self,
Expand Down Expand Up @@ -1311,8 +1358,9 @@ impl LiquidSdk {
webhook,
})?;

let swap_id = &create_response.id;
let create_response_json = ChainSwap::from_boltz_struct_to_json(&create_response, swap_id)?;
let create_response_json =
ChainSwap::from_boltz_struct_to_json(&create_response, &create_response.id)?;
let swap_id = create_response.id;

let accept_zero_conf = server_lockup_amount_sat <= pair.limits.maximal_zero_conf;
let payer_amount_sat = req.prepare_response.total_fees_sat + receiver_amount_sat;
Expand Down Expand Up @@ -1341,7 +1389,7 @@ impl LiquidSdk {
state: PaymentState::Created,
};
self.persister.insert_chain_swap(&swap)?;
self.status_stream.track_swap_id(&swap.id)?;
self.status_stream.track_swap_id(&swap_id)?;

self.wait_for_payment(Swap::Chain(swap), accept_zero_conf)
.await
Expand Down Expand Up @@ -2665,20 +2713,6 @@ mod tests {
assert_eq!(persisted_swap.state, PaymentState::Failed);
}

// Verify that `InvoiceSet` correctly sets the state to `Pending` and
// assigns the `lockup_tx_id` to the payment
let persisted_swap = trigger_swap_update!(
"send",
NewSwapArgs::default(),
persister,
status_stream,
SubSwapStates::InvoiceSet,
None,
None
);
assert_eq!(persisted_swap.state, PaymentState::Pending);
assert!(persisted_swap.lockup_tx_id.is_some());

// Verify that `TransactionClaimPending` correctly sets the state to `Complete`
// and stores the preimage
let persisted_swap = trigger_swap_update!(
Expand Down
64 changes: 23 additions & 41 deletions lib/core/src/send_swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::wallet::OnchainWallet;
use crate::{ensure_sdk, utils};
use crate::{
error::PaymentError,
model::{PaymentState, PaymentTxData, PaymentType, Transaction as SdkTransaction},
model::{PaymentState, Transaction as SdkTransaction},
persist::Persister,
};

Expand Down Expand Up @@ -71,40 +71,9 @@ impl SendSwapHandler {

// See https://docs.boltz.exchange/v/api/lifecycle#normal-submarine-swaps
match SubSwapStates::from_str(swap_state) {
// Boltz has locked the HTLC, we proceed with locking up the funds
// Boltz has locked the HTLC
Ok(SubSwapStates::InvoiceSet) => {
match (swap.state, swap.lockup_tx_id.clone()) {
(PaymentState::Created, None) | (PaymentState::TimedOut, None) => {
let create_response = swap.get_boltz_create_response()?;
let lockup_tx = self.lockup_funds(id, &create_response).await?;
let lockup_tx_id = lockup_tx.txid().to_string();
let lockup_tx_fees_sat: u64 = lockup_tx.all_fees().values().sum();

// We insert a pseudo-lockup-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: lockup_tx_id.clone(),
timestamp: Some(utils::now()),
amount_sat: swap.payer_amount_sat,
fees_sat: lockup_tx_fees_sat,
payment_type: PaymentType::Send,
is_confirmed: false,
},
None,
None,
)?;

self.update_swap_info(id, Pending, None, Some(&lockup_tx_id), None)
.await?;
}
(_, Some(lockup_tx_id)) => {
warn!("Lockup tx for Send Swap {id} was already broadcast: txid {lockup_tx_id}")
}
(state, _) => {
debug!("Send Swap {id} is in an invalid state for {swap_state}: {state:?}")
}
}
warn!("Received `invoice.set` state for Send Swap {id}");
Ok(())
}

Expand Down Expand Up @@ -203,7 +172,7 @@ impl SendSwapHandler {
}
}

async fn lockup_funds(
pub(crate) async fn lockup_funds(
&self,
swap_id: &str,
create_response: &CreateSubmarineResponse,
Expand All @@ -223,18 +192,31 @@ impl SendSwapHandler {
create_response.expected_amount,
)
.await?;
let lockup_tx_id = lockup_tx.txid().to_string();

self.persister
ok300 marked this conversation as resolved.
Show resolved Hide resolved
.set_send_swap_lockup_tx_id(swap_id, &lockup_tx_id)?;

info!("broadcasting lockup tx {}", lockup_tx.txid());
let lockup_tx_id = self
info!("Broadcasting lockup tx {lockup_tx_id} for Send swap {swap_id}",);
let broadcast_result = self
.chain_service
.lock()
.await
.broadcast(&lockup_tx, Some(swap_id))
.await?
.to_string();
.await;

info!("Successfully broadcast lockup tx for Send Swap {swap_id}. Lockup tx id: {lockup_tx_id}");
Ok(lockup_tx)
match broadcast_result {
Ok(_) => {
info!("Successfully broadcast lockup tx for Send Swap {swap_id}. Lockup tx id: {lockup_tx_id}");
Ok(lockup_tx)
}
Err(err) => {
debug!("Could not broadcast lockup tx for Send Swap {swap_id}: {err:?}");
self.persister
.unset_send_swap_lockup_tx_id(swap_id, &lockup_tx_id)?;
Err(err.into())
}
}
}

/// Transitions a Send swap to a new state
Expand Down
Loading