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

[r2r] Lightning Refunds #1592

Merged
merged 30 commits into from
Jan 13, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
3e907ac
lightning refunds wip: add is_auto_refundable, wait_for_htlc_refund S…
shamardy Dec 12, 2022
3a6c61d
lightning refunds wip: move fail_htlc_backwards to the right place
shamardy Dec 14, 2022
daf5da2
lightning refunds wip: add update_payment_status_in_db to LightningDB…
shamardy Dec 15, 2022
66e6f80
add update_payment_to_received_in_db method to LightningDB
shamardy Dec 19, 2022
2a5aa63
add update_payment_to_sent_in_db method to LightningDB
shamardy Dec 19, 2022
420e763
change add_or_update_payment_in_db to add_payment_to_db, remove payme…
shamardy Dec 19, 2022
e384af3
edit docs/notes related to fail_htlc_backwards
shamardy Dec 20, 2022
6067f03
Merge remote-tracking branch 'origin/dev' into ln-refunds
shamardy Dec 20, 2022
0353a81
fix typo: rename if_my_payment_spent_args to if_my_payment_sent_args
shamardy Dec 20, 2022
84d19b1
impl check_if_my_payment_sent for LightningCoin
shamardy Dec 20, 2022
e61e76b
add TakerPaymentInstructionsReceived to TAKER_SUCCESS_EVENTS, MakerPa…
shamardy Dec 22, 2022
ab68e26
implemented recover_funds for lightning, revised lightning swap resta…
shamardy Dec 26, 2022
fbc2da1
Remove unneeded todos
shamardy Dec 28, 2022
8df164c
Merge remote-tracking branch 'origin/dev' into ln-refunds
shamardy Dec 28, 2022
f133368
review fixes wip: add MakerSwapOps and TakerSwapOps
shamardy Jan 9, 2023
445a6ee
review fixes wip: update deny.toml
shamardy Jan 9, 2023
1f370bb
review fixes wip: revert deny.toml changes
shamardy Jan 10, 2023
72b3467
Merge remote-tracking branch 'origin/dev' into ln-refunds
shamardy Jan 10, 2023
ae5daf7
review fixes wip: add on_start/success trait methods to MakerSwapOps/…
shamardy Jan 10, 2023
d555e09
review fixes wip: fix wait_for_htlc_refund to not return TransactionFut
shamardy Jan 10, 2023
98b5798
review fixes wip: add with_preimage, with_status methods to PaymentIn…
shamardy Jan 10, 2023
ee12d6b
review fixes wip: use owned_named_params for insert_payment_sql
shamardy Jan 10, 2023
a35db06
first review fixes complete: use owned_named_params for insert_channe…
shamardy Jan 10, 2023
733aca1
second review fixes wip: use repeatable in wait_for_htlc_refund imple…
shamardy Jan 11, 2023
3279aa6
second review fixes wip: remove white spaces in recover_funds, fix is…
shamardy Jan 11, 2023
87f5fce
Merge remote-tracking branch 'origin/dev' into ln-refunds
shamardy Jan 12, 2023
cbe3d48
second review fixes wip: rename MakerSwapOps/TakerSwapOps to TakerSwa…
shamardy Jan 12, 2023
b329de3
second review fixes wip: Add TakerSwapCommand::PrepareForTakerPayment…
shamardy Jan 12, 2023
76632df
second review fixes: Add MakerSwapCommand::PrepareForMakerPaymentRefu…
shamardy Jan 12, 2023
0d2b7da
more review fixes
shamardy Jan 13, 2023
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
19 changes: 10 additions & 9 deletions mm2src/coins/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,19 +65,20 @@ use web3_transport::{http_transport::HttpTransportNode, EthFeeHistoryNamespace,

use super::{coin_conf, AsyncMutex, BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner,
CoinProtocol, CoinTransportMetrics, CoinsContext, FeeApproxStage, FoundSwapTxSpend, HistorySyncState,
IguanaPrivKey, MakerSwapOps, MarketCoinOps, MmCoin, MyAddressError, NegotiateSwapContractAddrErr,
IguanaPrivKey, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MyAddressError, NegotiateSwapContractAddrErr,
NumConversError, NumConversResult, PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy,
PrivKeyPolicyNotAllowed, RawTransactionError, RawTransactionFut, RawTransactionRequest, RawTransactionRes,
RawTransactionResult, RefundError, RefundResult, RpcClientType, RpcTransportEventHandler,
RpcTransportEventHandlerShared, SearchForSwapTxSpendInput, SendMakerPaymentArgs,
SendMakerRefundsPaymentArgs, SendMakerSpendsTakerPaymentArgs, SendTakerPaymentArgs,
SendTakerRefundsPaymentArgs, SendTakerSpendsMakerPaymentArgs, SignatureError, SignatureResult, SwapOps,
TakerSwapOps, TradeFee, TradePreimageError, TradePreimageFut, TradePreimageResult, TradePreimageValue,
Transaction, TransactionDetails, TransactionEnum, TransactionErr, TransactionFut, TxMarshalingErr,
UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr,
ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError,
VerificationResult, WatcherOps, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput,
WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut, WithdrawRequest, WithdrawResult};
TakerSwapMakerCoin, TradeFee, TradePreimageError, TradePreimageFut, TradePreimageResult,
TradePreimageValue, Transaction, TransactionDetails, TransactionEnum, TransactionErr, TransactionFut,
TxMarshalingErr, UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs,
ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut,
ValidatePaymentInput, VerificationError, VerificationResult, WatcherOps, WatcherSearchForSwapTxSpendInput,
WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut,
WithdrawRequest, WithdrawResult};
pub use rlp;

#[cfg(test)] mod eth_tests;
Expand Down Expand Up @@ -1256,14 +1257,14 @@ impl SwapOps for EthCoin {
}

#[async_trait]
impl MakerSwapOps for EthCoin {
impl TakerSwapMakerCoin for EthCoin {
async fn on_taker_payment_refund_start(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }

async fn on_taker_payment_refund_success(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
}

#[async_trait]
impl TakerSwapOps for EthCoin {
impl MakerSwapTakerCoin for EthCoin {
async fn on_maker_payment_refund_start(&self, _taker_payment: &[u8]) -> RefundResult<()> { Ok(()) }

async fn on_maker_payment_refund_success(&self, _taker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
Expand Down
77 changes: 33 additions & 44 deletions mm2src/coins/lightning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,24 @@ use crate::utxo::rpc_clients::UtxoRpcClientEnum;
use crate::utxo::utxo_common::{big_decimal_from_sat, big_decimal_from_sat_unsigned};
use crate::utxo::{sat_from_big_decimal, utxo_common, BlockchainNetwork};
use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, FeeApproxStage, FoundSwapTxSpend,
HistorySyncState, MakerSwapOps, MarketCoinOps, MmCoin, NegotiateSwapContractAddrErr, PaymentInstructions,
PaymentInstructionsErr, RawTransactionError, RawTransactionFut, RawTransactionRequest, RefundError,
RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentArgs, SendMakerRefundsPaymentArgs,
SendMakerSpendsTakerPaymentArgs, SendSpendPaymentArgs, SendTakerPaymentArgs, SendTakerRefundsPaymentArgs,
SendTakerSpendsMakerPaymentArgs, SignatureError, SignatureResult, SwapOps, TakerSwapOps, TradeFee,
TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction, TransactionEnum, TransactionErr,
TransactionFut, TxMarshalingErr, UnexpectedDerivationMethod, UtxoStandardCoin, ValidateAddressResult,
ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError,
ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, WatcherOps,
WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput,
HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, NegotiateSwapContractAddrErr,
PaymentInstructions, PaymentInstructionsErr, RawTransactionError, RawTransactionFut,
RawTransactionRequest, RefundError, RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentArgs,
SendMakerRefundsPaymentArgs, SendMakerSpendsTakerPaymentArgs, SendSpendPaymentArgs, SendTakerPaymentArgs,
SendTakerRefundsPaymentArgs, SendTakerSpendsMakerPaymentArgs, SignatureError, SignatureResult, SwapOps,
TakerSwapMakerCoin, TradeFee, TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction,
TransactionEnum, TransactionErr, TransactionFut, TxMarshalingErr, UnexpectedDerivationMethod,
UtxoStandardCoin, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr,
ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult,
WatcherOps, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput,
WithdrawError, WithdrawFut, WithdrawRequest};
use async_trait::async_trait;
use bitcoin::bech32::ToBase32;
use bitcoin::hashes::Hash;
use bitcoin_hashes::sha256::Hash as Sha256;
use bitcrypto::ChecksumType;
use bitcrypto::{dhash256, ripemd160};
use common::custom_futures::repeatable::{Ready, Retry};
use common::executor::{AbortableSystem, AbortedError, Timer};
use common::log::{info, LogOnError, LogState};
use common::{async_blocking, get_local_duration_since_epoch, log, now_ms, PagingOptionsEnum};
Expand Down Expand Up @@ -803,44 +804,32 @@ impl SwapOps for LightningCoin {
async fn wait_for_htlc_refund(&self, tx: &[u8], locktime: u64) -> RefundResult<()> {
let payment_hash = payment_hash_from_slice(tx).map_err(|e| RefundError::DecodeErr(e.to_string()))?;
let payment_hex = hex::encode(payment_hash.0);
loop {
repeatable!(async {
match self.db.get_payment_from_db(payment_hash).await {
Ok(Some(payment)) => match payment.status {
HTLCStatus::Failed => return Ok(()),
HTLCStatus::Pending => (),
_ => {
return MmError::err(RefundError::Internal(ERRL!(
"Payment {} has an invalid status of {} in the db",
payment_hex,
payment.status
)))
},
},
Ok(None) => {
return MmError::err(RefundError::Internal(ERRL!(
"Payment {} is not in the database when it should be!",
payment_hex
)))
},
Err(e) => {
return MmError::err(RefundError::DbError(ERRL!(
"Error getting payment {} from db: {}",
HTLCStatus::Failed => Ready(Ok(())),
HTLCStatus::Pending => Retry(()),
_ => Ready(MmError::err(RefundError::Internal(ERRL!(
"Payment {} has an invalid status of {} in the db",
payment_hex,
e
)))
payment.status
)))),
},
}

let now = now_ms() / 1000;
if now > locktime {
sergeyboyko0791 marked this conversation as resolved.
Show resolved Hide resolved
return MmError::err(RefundError::Timeout(ERRL!(
"Waited too long until {} for payment {} to be refunded!",
locktime,
Ok(None) => Ready(MmError::err(RefundError::Internal(ERRL!(
"Payment {} is not in the database when it should be!",
payment_hex
)));
)))),
Err(e) => Ready(MmError::err(RefundError::DbError(ERRL!(
"Error getting payment {} from db: {}",
payment_hex,
e
)))),
}
Timer::sleep(WAIT_FOR_REFUND_INTERVAL).await;
}
})
.repeat_every_secs(WAIT_FOR_REFUND_INTERVAL)
.until_ms(locktime)
.await
.map_err(|e| RefundError::Timeout(format!("{:?}", e)))?
}

fn negotiate_swap_contract_addr(
Expand Down Expand Up @@ -916,7 +905,7 @@ impl SwapOps for LightningCoin {
}

#[async_trait]
impl MakerSwapOps for LightningCoin {
impl TakerSwapMakerCoin for LightningCoin {
async fn on_taker_payment_refund_start(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }

async fn on_taker_payment_refund_success(&self, maker_payment: &[u8]) -> RefundResult<()> {
Expand All @@ -925,7 +914,7 @@ impl MakerSwapOps for LightningCoin {
}

#[async_trait]
impl TakerSwapOps for LightningCoin {
impl MakerSwapTakerCoin for LightningCoin {
async fn on_maker_payment_refund_start(&self, taker_payment: &[u8]) -> RefundResult<()> {
self.on_swap_refund(taker_payment).await
}
Expand Down
20 changes: 11 additions & 9 deletions mm2src/coins/lp_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -761,21 +761,21 @@ pub trait SwapOps {
fn maker_locktime_multiplier(&self) -> f64 { 2.0 }
}

/// Maker specific swap operations
/// Operations on maker coin from taker swap side
#[async_trait]
pub trait MakerSwapOps {
/// Performs an action on maker payment on taker payment refund start if applicable
pub trait TakerSwapMakerCoin {
/// Performs an action on maker coin payment on taker swap payment refund start if applicable
sergeyboyko0791 marked this conversation as resolved.
Show resolved Hide resolved
async fn on_taker_payment_refund_start(&self, maker_payment: &[u8]) -> RefundResult<()>;
/// Perform an action on maker payment on taker payment refund success if applicable
/// Perform an action on maker coin payment on taker swap payment refund success if applicable
async fn on_taker_payment_refund_success(&self, maker_payment: &[u8]) -> RefundResult<()>;
}

/// Taker specific swap operations
/// Operations on taker coin from maker swap side
#[async_trait]
pub trait TakerSwapOps {
/// Performs an action on taker payment on starting maker payment refund process if applicable
pub trait MakerSwapTakerCoin {
/// Performs an action on taker coin payment on starting maker swap payment refund process if applicable
async fn on_maker_payment_refund_start(&self, taker_payment: &[u8]) -> RefundResult<()>;
/// Perform an action on taker payment on maker payment refund success if applicable
/// Perform an action on taker coin payment on maker swap payment refund success if applicable
async fn on_maker_payment_refund_success(&self, taker_payment: &[u8]) -> RefundResult<()>;
}

Expand Down Expand Up @@ -1927,7 +1927,9 @@ impl From<CoinFindError> for VerificationError {

/// NB: Implementations are expected to follow the pImpl idiom, providing cheap reference-counted cloning and garbage collection.
#[async_trait]
pub trait MmCoin: SwapOps + MakerSwapOps + TakerSwapOps + WatcherOps + MarketCoinOps + Send + Sync + 'static {
pub trait MmCoin:
SwapOps + TakerSwapMakerCoin + MakerSwapTakerCoin + WatcherOps + MarketCoinOps + Send + Sync + 'static
{
// `MmCoin` is an extension fulcrum for something that doesn't fit the `MarketCoinOps`. Practical examples:
// name (might be required for some APIs, CoinMarketCap for instance);
// coin statistics that we might want to share with UI;
Expand Down
16 changes: 8 additions & 8 deletions mm2src/coins/qrc20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@ use crate::utxo::{qtum, ActualTxFee, AdditionalTxData, AddrFromStrError, Broadca
UtxoActivationParams, UtxoAddressFormat, UtxoCoinFields, UtxoCommonOps, UtxoFromLegacyReqErr,
UtxoTx, UtxoTxBroadcastOps, UtxoTxGenerationOps, VerboseTransactionFrom, UTXO_LOCK};
use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, FeeApproxStage,
FoundSwapTxSpend, HistorySyncState, IguanaPrivKey, MakerSwapOps, MarketCoinOps, MmCoin,
FoundSwapTxSpend, HistorySyncState, IguanaPrivKey, MakerSwapTakerCoin, MarketCoinOps, MmCoin,
NegotiateSwapContractAddrErr, PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy,
PrivKeyPolicyNotAllowed, RawTransactionFut, RawTransactionRequest, RefundError, RefundResult,
SearchForSwapTxSpendInput, SendMakerPaymentArgs, SendMakerRefundsPaymentArgs,
SendMakerSpendsTakerPaymentArgs, SendTakerPaymentArgs, SendTakerRefundsPaymentArgs,
SendTakerSpendsMakerPaymentArgs, SignatureResult, SwapOps, TakerSwapOps, TradeFee, TradePreimageError,
TradePreimageFut, TradePreimageResult, TradePreimageValue, TransactionDetails, TransactionEnum,
TransactionErr, TransactionFut, TransactionType, TxMarshalingErr, UnexpectedDerivationMethod,
ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr,
ValidatePaymentFut, ValidatePaymentInput, VerificationResult, WatcherOps,
SendTakerSpendsMakerPaymentArgs, SignatureResult, SwapOps, TakerSwapMakerCoin, TradeFee,
TradePreimageError, TradePreimageFut, TradePreimageResult, TradePreimageValue, TransactionDetails,
TransactionEnum, TransactionErr, TransactionFut, TransactionType, TxMarshalingErr,
UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr,
ValidateOtherPubKeyErr, ValidatePaymentFut, ValidatePaymentInput, VerificationResult, WatcherOps,
WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput,
WithdrawError, WithdrawFee, WithdrawFut, WithdrawRequest, WithdrawResult};
use async_trait::async_trait;
Expand Down Expand Up @@ -1084,14 +1084,14 @@ impl SwapOps for Qrc20Coin {
}

#[async_trait]
impl MakerSwapOps for Qrc20Coin {
impl TakerSwapMakerCoin for Qrc20Coin {
async fn on_taker_payment_refund_start(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }

async fn on_taker_payment_refund_success(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
}

#[async_trait]
impl TakerSwapOps for Qrc20Coin {
impl MakerSwapTakerCoin for Qrc20Coin {
async fn on_maker_payment_refund_start(&self, _taker_payment: &[u8]) -> RefundResult<()> { Ok(()) }

async fn on_maker_payment_refund_success(&self, _taker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
Expand Down
16 changes: 8 additions & 8 deletions mm2src/coins/solana.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ use crate::coin_errors::MyAddressError;
use crate::solana::solana_common::{lamports_to_sol, PrepareTransferData, SufficientBalanceError};
use crate::solana::spl::SplTokenInfo;
use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinFutSpawner, FeeApproxStage, FoundSwapTxSpend,
MakerSwapOps, NegotiateSwapContractAddrErr, PaymentInstructions, PaymentInstructionsErr,
MakerSwapTakerCoin, NegotiateSwapContractAddrErr, PaymentInstructions, PaymentInstructionsErr,
PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed, RawTransactionFut, RawTransactionRequest, RefundError,
RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentArgs, SendMakerRefundsPaymentArgs,
SendMakerSpendsTakerPaymentArgs, SendTakerPaymentArgs, SendTakerRefundsPaymentArgs,
SendTakerSpendsMakerPaymentArgs, SignatureResult, TakerSwapOps, TradePreimageFut, TradePreimageResult,
TradePreimageValue, TransactionDetails, TransactionFut, TransactionType, TxMarshalingErr,
UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr,
ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput,
VerificationResult, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput,
SendTakerSpendsMakerPaymentArgs, SignatureResult, TakerSwapMakerCoin, TradePreimageFut,
TradePreimageResult, TradePreimageValue, TransactionDetails, TransactionFut, TransactionType,
TxMarshalingErr, UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs,
ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut,
ValidatePaymentInput, VerificationResult, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput,
WatcherValidateTakerFeeInput, WithdrawError, WithdrawFut, WithdrawRequest, WithdrawResult};
use async_trait::async_trait;
use base58::ToBase58;
Expand Down Expand Up @@ -606,14 +606,14 @@ impl SwapOps for SolanaCoin {
}

#[async_trait]
impl MakerSwapOps for SolanaCoin {
impl TakerSwapMakerCoin for SolanaCoin {
async fn on_taker_payment_refund_start(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }

async fn on_taker_payment_refund_success(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
}

#[async_trait]
impl TakerSwapOps for SolanaCoin {
impl MakerSwapTakerCoin for SolanaCoin {
async fn on_maker_payment_refund_start(&self, _taker_payment: &[u8]) -> RefundResult<()> { Ok(()) }

async fn on_maker_payment_refund_success(&self, _taker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
Expand Down
Loading