-
Notifications
You must be signed in to change notification settings - Fork 94
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
Lightning integration #1045
Comments
LDK/Rust-Lightning is the only good rust lightning network library/crate that exists, there are other libraries that implement LN in Rust but only partially. It also states in the about section that it's designed for integrating lightning with custom features such as our own chain sync/key management/data storage/backup logic. |
Update on whether HTLCs are possible on LN. |
A few Issues we should take into consideration when Integrating lightning to mm2.
|
@artemii235 The next step will be to implement an HTLC PoC on the testnet following this example https://github.com/KomodoPlatform/atomicDEX-API/blob/mm2.1/mm2src/coins/eth/eth_tests.rs#L196 as we discussed. |
The following is the best technical book on the lightning network (Maybe the only one) https://github.com/lnbook/lnbook it's equivalent to the "Programming Bitcoin" book but for LN. It's not officially released yet but should be in Jan of 2022. They released the work on progress and now the final production version on Github. |
* impl FeeEstimator, Logger, BroadcasterInterface * impl Filter for ElectrumClient * lightning conf + ChainMonitor for electrum * fix wasm build * impl keys_manager and channel_manager * NetGraphMsgHandler, PeerManager, spawn network * update best block for chainmon and channel manager * Mock LN events, Persist CM, Background Processing * 1st version of enable_lightning rpc for test * refactoring + Error handling * remove hardcoded lightning conf paramaters * move LN trait impls for Electrum to seperate file * enable_lightning test * move enable_lightning to dispacher_v2 * announce external ip address to LN * Add node color to configs and request
We should consider researching the Joule in regards to Lightning web wallet support: https://lightningjoule.com/ |
* WIP restarting node/read channel_manager from file * WIP: LN Registry for register_tx & register_output * update transactions confirmations on node restart * reconnect to channel peers on node restart * connect to LN node RPC + WIP lightning ctx * continued lightning ctx impl for multiple coins * open_channel RPC * withdraw to p2wsh addresses + funding tx WIP * fix zhtlc build * extract_destinations for p2wsh * generate/broadcast funding tx (channel opening tx) * update rust-lightning to v0.0.102 * update rust-lightning to v0.0.103 * fix reconnection to open channels nodes on restart * save nodes to file fix + order txs to confirm * add fee param to open_channel RPC + refactors * use scripthash_get_history to get tx block height * remove unneeded comments * WIP:Review fixes, ChannelOpenAmount, UtxoTxBuilder * WIP: Review fixes, use get_tx_fee for funding tx * remove WithdrawFee, fix unit test * WIP: review fixes, use find_output_spend fn * WIP: review fixes, separate dirs for tickers * WIP: Review fixes, request_id fix on restart * WIP: review fixes, LightningCoin * final fixes: move ln_registry, fix fee with max * second review fixes * WIP: review fixes, OpenChannelRequest fix, others * Review fixes: enable_l2, enable_lightning * remove lightning from lp_coininit * use virtual bytes to calculate tx fees * WIP: more review fixes * WIP: review fixes, remove block_on * WIP: review fixes, impl EventHandler trait * WIP: add validation methods to L2ActivationOps * Review fixes, add unsigned_funding_txs mutex * review fixes: NO_SUCH_TRANSACTION_ERROR * use 'code': -5 to check for tx unconfirmation * add get_merkle method, use tx index to confirm it
Just opened the lightning payments PR. After the review process and merging to dev, the next step should be persisting lightning payments and channels history (closed channels) to storage (SQLite) and implementing channels monitors external backup. Payments history is analogous to transactions history for other coins, as for monitors backup, this is required because lightning channels can't be reconstructed from the seed only unlike other coins so backup to external drive or cloud services is required. Once both of these functionalities are implemented minimal lightning wallet functionalities can be considered ready. I updated the above checklist with the upcoming steps. The ordering of these steps can be changed based on priorities. |
* ln-channels PR last comments fixes * generate_invoice RPC * update rust-lightning to latest version 0.0.104 * move events related code to ln_events * get_ln_node_id RPC, handle PaymentReceived event * WIP: send_payment RPC * PaymentSent/Failed events, list_payments RPC * persist network graph, scorer * move persisting functions to ln_storage * use async_blocking, PaMutex to fix thread blocking * list_channels RPC * PendingHTLCsForwardable Event, mutexes fixes * Handle SpendableOutputs Event * remove register funding tx/output as LDK does it * Fix rust-lightning logs to be same level as mm2 * close_channel RPC * fixes to spend channel closing outputs * send a payment by pubkey without invoice (keysend) * use InvoicePayer for keysend (handles some events) * Handle PaymentForwarded Event * my_balance, my_address for lightning coin * Impl MarketCoinOps related to wallet functionality * impl MmCoin traits related to wallet functionality * Reconnection to channels counterparties fixes * move connection related functions to seperate file * WIP: Custom channels configuration * wip custom channels configuration, l2 conf * Custom channels configuration * blocking in fee estimate fix, wip: lightning tests * moved lightning-persister to mm2 to allow for adding test functions * add get_claimable_balances RPC * use connect_to_lightning_node to update a channel's node addr if changed * get_channel_details RPC * get_payment_details RPC * payment retries param, use InvoicePayer as BackgroundProcessor event handler * Remove get_ln_node_id RPC since it's included in enable response * get confirmation targets for fee estimator from coin config * move network field from utxo coin to lightning coin * minor fixes * add force close option to close_channel RPC + init ln dir * Simple backup implementation for channels/nodes * import lightning-background-processor code * use cfg_native macro where it's possible * disable LightningCoin in WASM for now * minor fixes * review fixes, use more specific types for req/res * use invoice type for request/response * impl persist_nodes_addresses on LightningCoin * create Storage trait for LN and impl for FilesystemPersister * fix remove test dirs at the end of tests
* WIP: Channels history in SQL storage * review fixes: specific types, add serialization tests * WIP: refactor start_lightning fn * WIP: continue refactoring start_lightning fn * WIP: refactoring, add init_channel_manager fn * WIP: refactoring, ln_p2p * WIP: refactoring, ln_platform * Refactor completed * WIP: use user_channel_id as channel id in rpc calls to avoid using temp id * Channels in sql WIP: add pending outbound channel to sql * Channels sql WIP: get channel and add funding_tx * Channels sql WIP: add funding tx to sql after FundingGenerationReady event * Channels sql WIP: add closure_reason to sql table * Channels sql WIP: update channel to closed in sql * Channels sql WIP: get closed channels in list_channels response * Channels sql WIP: get closed channel by rpc_id in get_channel_details response * Channels sql WIP: add closing transaction to sql * outbound channels history in sql completed * Payments in sql WIP: add/get payment to/from sql * Payments in sql completed * update rust-lightning to v0.0.105 * set manually_accept_inbound_channels to true to be able to add them to sql in the future * correct calculation of claimed balances * add destination to payment info * add description to payment info * add created/updated at to payment info, wip: list payments by filter * list_payments_by_filter completed, pagination completed * list channels by filter for open and closed * fix wasm build * part of review fixes * part of review fixes: save_channel_closing_details function * review fixes wip: simplify find_watched_output_spend_with_header * review fixes * reviw fix for funding_generated_in_block * fix saving closing tx to db issues if electrums are down * review fixes: better grouping of SqlStorage trait functions + added descriptions * review fixes: add get_open_channels_by_filter fn * review fixes wip: some refactors * review fixes wip: default_fee_per_kb, refactors * review fixes: use try_loop_with_sleep macro wip * review fixes * remove wasm warnings * destination can't be None in OutboundPayment * empty string for description instead of an option * Review fixes: refactors * review fixes wip * wip: more review fixes * review fixes: inline, refactors * sql_text_conversion_err, h256_slice_from_row
#1339) * remove ok_or_retry_after_sleep_sync! macro * process_txs_confirmations independent from update_best_block * use get_tx_height in get_confirmed_registered_txs to prepare for batch requests * validate_spv_proof refactor wip, spv for lightning wip * fix test_spv_proof * remove find_watched_output_spend_with_header * impl some features of rust-lightning v0.0.106 wip, import code from lightning-persister v0.0.106 and lightning-background-processor v0.0.106 wip * add inbound channels details to sql db * remove lightning-persister and lightning-background-processor crates from our codebase and use v0.0.106 crates instead * remove ok_or_continue macro, use join_all to check for transactions confirmations in batches * small fixes after testing * fix fmt * get confirmed transaction info from spv proof fn * move get_tx_if_onchain, get_tx_height to rpc_clients * spv proof refactoring wip * fix fmt * spv proof refactor * break ln_storage.rs to multiple files, break up persister struct into db struct and filesystem struct * fixes for persisting monitors to back up dir * fix clippy for windows * fix some todos * btc difficulty calculations for spv validation wip * continued: btc difficulty calculations for spv validation wip, added more test cases * continued: btc difficulty calculations for spv validation wip, work.rs, storage.rs * fix wasm, tests * spv difficulty testnet * fix some todos * fixes after merge * add events abort handlers * Review fixes wip * Review fixes wip, log db error in open_channel, workTestVectors.json * Review fixes, save claiming tx to db after successful broadcasting * Review fixes wip, use bool without casting, use i64 instead of u64 casting for db operations * Review fixes wip, #[cfg(target_family = "windows")], refactors * Review fixes, get tx height by block hash
* fix some ignored tests * move connect_to_lightning_node to rpc_command * move open_channel to rpc_command * move update_channel to rpc_command * move list channels rpcs to rpc_command * move get_channel_details, get_claimable_balances, trusted nodes rpcs to rpc_command * move close_channel to rpc_command * move get_payment_details, list_payments_by_filter to rpc_command * move send_payment to rpc_command * move the rest of lightning RPCs to rpc_command, use lightning:: prefix for lightning methods * edit SwapMsg MakerPayment and TakerPayment to allow sending payment instructions to the other side * create_invoice_for_hash fn, impl other_side_instructions for LightningCoin, copy needed parts of SecretHashAlgo from iris-swap-poc branch * check connection to nodes before generating route hints, refactors * fix TakerFee msg to include PaymentDataMsg (lightning invoice to be paid by maker to taker) instead of TakerPayment msg * Validate invoice received from swap messages wip * Validate invoice on maker side if maker is lightning coin * add optional PaymentInstructions parameter to send_maker_payment, send_taker_payment functions * implement send_taker_payment and send_maker_payment for LightningCoin * change tx_enum_from_bytes to return none for lightning coin * Some refactors and rollbacks * impl more swap methods, do a unit test swap where taker is lightning * refactor some code by adding payment_hash_from_slice fn * minor fixes and added more todo for next PR/s * refactor lightning taker swap test * more refactors, broadcast_p2p_tx_msg shouldn't work with lightning payments, better todo comments * add preimage of swap payment to DB after the secret is revealed (claiming funds) * wip * Final refactors * Review fixes: better names for some functions/structs * Review fixes: some errors fixes, add channels::, nodes::, payments:: namespaces to the RPC methods * Review fixes: fix some error handling issues * more review fixes * review fixes wip: rename SwapTxDataMsg enum variants * review fixes wip: validate_instructions to return an error instead of None, some refactors * Review fixes: make TransactionIdentifier::tx_hex not an Option and add is_supported_by_watchers method to SwapOps * re-add Todo that was removed by merge
* use task manager to enable lightning * Move BackgroundProcessor back into LightningCoin now that it gets dropped when the coin is deactivated * move start_lightning to coins_activation to use LightningRpcTaskHandle to update the enabling progress * Edit coin deactivation todos * add one line break ¯\_(ツ)_/¯
After a swap P.O.C with lightning coin as taker was implemented, the next step would be to implement locktimes correctly for lightning. This will let us continue the implementation of maker swaps and swaps refunds for lightning coin. Here are some notes on my research about how swap locktimes can be implemented for lightning: Assumptions
Payments HTLCs
cltv_expiry_delta
Maker Swap Locktime if LightningCoin is Taker
Taker Swap Locktime if LightningCoin is Maker
|
@shamardy
Yes, this seems acceptable. Though,
is a bit too much 🙂
We can try it - with such a long lock duration, even 1,5x will give taker enough time to act even if his payment is spent right before locktime expiration. Also, a couple of questions:
|
First, Just adding a note about this to not forget :)
The 3 is related to the maximum shadow route hops. As shown by the below quote from the my original comment.
I believe it can be decreased, or even be
This is for demonstration purposes only.
Most nodes use |
final_cltv_expiry (last hop cltv) should be more than taker swap locktime (at least double like other swaps to give the taker enough time to claim the lightning payment), not less. I miscalculated this, will update this in both comments now. Taker swap locktime (for other non-lightning coins) when Maker is lightning can be just the current implemented swap locktimes in mm2, not 22 hours. |
This is a diagram to demonstrate swap locktimes if taker is |
@artemii235 In this comment, I would like to propose a solution to how lightning taker fees can be implemented in AtomicDEX so that we can discuss this solution before proceeding with implementing this part of the lightning network integration. Problems
Proposed Solution
Lightning offers
|
#1045 * lightning refunds wip: add is_auto_refundable, wait_for_htlc_refund SwapOps functions * lightning refunds wip: move fail_htlc_backwards to the right place * lightning refunds wip: add update_payment_status_in_db to LightningDB trait * add update_payment_to_received_in_db method to LightningDB * add update_payment_to_sent_in_db method to LightningDB * change add_or_update_payment_in_db to add_payment_to_db, remove payment secret from payment info and db * edit docs/notes related to fail_htlc_backwards * fix typo: rename if_my_payment_spent_args to if_my_payment_sent_args * impl check_if_my_payment_sent for LightningCoin * add TakerPaymentInstructionsReceived to TAKER_SUCCESS_EVENTS, MakerPaymentInstructionsReceived to MAKER_SUCCESS_EVENTS * implemented recover_funds for lightning, revised lightning swap restart, recreate_swap_data * Remove unneeded todos * review fixes wip: add MakerSwapOps and TakerSwapOps * review fixes wip: update deny.toml * review fixes wip: revert deny.toml changes * review fixes wip: add on_start/success trait methods to MakerSwapOps/TakerSwapOps * review fixes wip: fix wait_for_htlc_refund to not return TransactionFut * review fixes wip: add with_preimage, with_status methods to PaymentInfo impl * review fixes wip: use owned_named_params for insert_payment_sql * first review fixes complete: use owned_named_params for insert_channel_sql, used params macro where applicable * second review fixes wip: use repeatable in wait_for_htlc_refund implementation for LightningCoin * second review fixes wip: remove white spaces in recover_funds, fix is_auto_refundable in maker_swap's recover_funds * second review fixes wip: rename MakerSwapOps/TakerSwapOps to TakerSwapMakerCoin/MakerSwapTakerCoin * second review fixes wip: Add TakerSwapCommand::PrepareForTakerPaymentRefund, TakerSwapCommand::FinalizeTakerPaymentRefund * second review fixes: Add MakerSwapCommand::PrepareForMakerPaymentRefund, MakerSwapCommand::FinalizeMakerPaymentRefund * more review fixes
@smk762 after this PR #1592, new events that should be documented were added to
Full list of success and error events after this changeMaker success events"success_events": [
"Started",
"Negotiated",
"MakerPaymentInstructionsReceived",
"TakerFeeValidated",
"MakerPaymentSent",
"TakerPaymentReceived",
"TakerPaymentWaitConfirmStarted",
"TakerPaymentValidatedAndConfirmed",
"TakerPaymentSpent",
"TakerPaymentSpendConfirmStarted",
"TakerPaymentSpendConfirmed",
"Finished",
] Taker success events"success_events": [
"Started",
"Negotiated",
"TakerFeeSent",
"TakerPaymentInstructionsReceived",
"MakerPaymentReceived",
"MakerPaymentWaitConfirmStarted",
"MakerPaymentValidatedAndConfirmed",
"TakerPaymentSent",
"TakerPaymentSpent",
"MakerPaymentSpent",
"Finished",
] Maker error events"error_events": [
"StartFailed",
"NegotiateFailed",
"TakerFeeValidateFailed",
"MakerPaymentTransactionFailed",
"MakerPaymentDataSendFailed",
"MakerPaymentWaitConfirmFailed",
"TakerPaymentValidateFailed",
"TakerPaymentWaitConfirmFailed",
"TakerPaymentSpendFailed",
"TakerPaymentSpendConfirmFailed",
"MakerPaymentWaitRefundStarted",
"MakerPaymentRefundStarted",
"MakerPaymentRefunded",
"MakerPaymentRefundFailed",
"MakerPaymentRefundFinished",
] Taker error events"error_events": [
"StartFailed",
"NegotiateFailed",
"TakerFeeSendFailed",
"MakerPaymentValidateFailed",
"MakerPaymentWaitConfirmFailed",
"TakerPaymentTransactionFailed",
"TakerPaymentWaitConfirmFailed",
"TakerPaymentDataSendFailed",
"TakerPaymentWaitForSpendFailed",
"MakerPaymentSpendFailed",
"TakerPaymentWaitRefundStarted",
"TakerPaymentRefundStarted",
"TakerPaymentRefunded",
"TakerPaymentRefundFailed",
"TakerPaymentRefundFinished",
] |
test_deserialize_lightning_swap_status
similar to the iris one here [r2r] Fix IRIS/Lightning swap stats #1608@shamardy Please post the documentation links, notable libraries, and intermediate milestones reports to this issue comments.
The text was updated successfully, but these errors were encountered: