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

Add transaction sync crate #1870

Merged

Conversation

tnull
Copy link
Contributor

@tnull tnull commented Nov 24, 2022

This crate provides utilities for syncing LDK via the transaction-based Confirm interface. The initial implementation facilitates synchronization with an Esplora backend server.

Upstreamed from lightningdevkit/ldk-node#9.

@tnull tnull marked this pull request as draft November 24, 2022 12:37
@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch from 7b952c8 to c0e0a9e Compare November 24, 2022 12:40
c.transaction_unconfirmed(&txid);
}

locked_watched_transactions.insert(txid);
Copy link
Contributor Author

@tnull tnull Nov 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I now included this essentially as a hotfix for the latest feedback from lightningdevkit/ldk-node#9. However, I'm still not sure if we shouldn't rather go either with the "simply always confirm everything" or the "re-register outputs via load_outputs_to_watch upon start of the sync round" approach.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

putting this here causes it so confirmed txs are never added to watched_transactions and thus never confirmed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, I'm not sure why they never would be confirmed?

Generally all transactions will be added to locked_watched_transactions when the Filter queues are processed via process_queues(). Any transaction returned by get_relevant_txids() only needs to be monitored for re- and unconfirmations, in which case we call transaction_confirmed and re-add them to the list to monitor for confirmation, i.e., watched_transactions. Am I missing something?

Copy link
Contributor

@benthecarman benthecarman Dec 12, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haven't debugged it yet but we're using a copy-paste of this in mutiny and transactions would never get confirmed unless we added txs that were confirmed here

https://github.com/BitcoinDevShop/mutiny-web-poc/blob/master/node-manager/src/chain.rs

This was our bug fix

MutinyWallet/mutiny-node@9104a7d

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mh, I'm still not clear why that would happen when only re-adding the unconfirmed transactions.

I now cleaned up the approach a bit with 5d94cb6. Could you check whether this mitigates what you saw before?

Btw. I now also migrated to future::lock::Mutex. Does this allow you to re-use the create instead of copy-pasting?

@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch 6 times, most recently from 5ca85f9 to d696d42 Compare November 24, 2022 13:43
@tnull tnull marked this pull request as ready for review November 24, 2022 14:37
@tnull
Copy link
Contributor Author

tnull commented Nov 24, 2022

Seems due to the dependencies of rust-esplora-client this will only pass CI for stable and above. Are we fine with this for a new crate? We'd need to upgrade the linting job to have it pass also it seems...

@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch 2 times, most recently from b9d8e26 to 5e27d3c Compare November 24, 2022 14:45
@TheBlueMatt
Copy link
Collaborator

Cool! A few assorted notes:

  • I think ideally we wouldn't take on a dependency with a big HTTP client for this, but I assume we kinda need TLS, so we can't really avoid it. It may be worth looking into contributing an HTTP client upstream so that we can avoid the HTTP library and just take on a RustTLS (or openssl-sys or whatever) dependency, but it doesn't have to happen immediately. In the mean time, we can have a different MSRV for different crates, though ideally BDK starts supporting versions of rustc people have, rather than just latest.
  • I believe this cannot land until we have some way to be much more confident in a server-side reorg not being possible without detection. I believe we need upstream changes for that, but that should be relatively easy, I think? Is there something I'm missing here?

@jkczyz jkczyz self-requested a review November 29, 2022 04:24
@tnull
Copy link
Contributor Author

tnull commented Nov 30, 2022

  • I believe this cannot land until we have some way to be much more confident in a server-side reorg not being possible without detection. I believe we need upstream changes for that, but that should be relatively easy, I think? Is there something I'm missing here?

No, I think while I covered a lot of cases, some edge cases still remain.

I'm currently considering whether adding a confirmed_since/in_best_chain_since timestamp field to Esplora's /block/:hash/status endpoint might be enough and a very unobtrusive way to get what we need. I.e., we could remember that timestamp when we check the tip initially and compare it to the one in the last check to figure out if there had been reorgs in-between. I imagine this is much more likely to be accepted than breaking the API by adding a as_of_tip_hash field to every call.

@TheBlueMatt
Copy link
Collaborator

TheBlueMatt commented Nov 30, 2022

I don't think adding a new field to calls "breaks the API" - isn't the point of JSON that we can add new fields and old clients will ignore them? Have you chatted with upstream yet?

@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch from 43a3bb9 to d5f43c7 Compare December 5, 2022 10:23
@tnull
Copy link
Contributor Author

tnull commented Dec 5, 2022

I don't think adding a new field to calls "breaks the API" - isn't the point of JSON that we can add new fields and old clients will ignore them? Have you chatted with upstream yet?

Fair enough. Will look into opening corresponding issue/PR upstream. If there's much push-back, we might have above mentioned variant as a fallback option.

@tnull
Copy link
Contributor Author

tnull commented Dec 6, 2022

Now opened Blockstream/electrs#52, which adds the best_tip_hash to the /block/:hash/status endpoint. I think this should be sufficient to assert consistency.

Unfortunately it's not as straight forward to add a similar field to the merkleblock-proof endpoint as this returns just the raw hex-encoded data in Core's format. This means we'll still need to collect the corresponding block hashes during a sync round and check their status and the tip invariance at the end once. But I think that should be no big deal.

@TheBlueMatt
Copy link
Collaborator

I'm confused how that's sufficient here - can't the server do a reorg while we're making other queries and then reorg back to the original chain before we get to check it?

@tnull
Copy link
Contributor Author

tnull commented Dec 6, 2022

I'm confused how that's sufficient here - can't the server do a reorg while we're making other queries and then reorg back to the original chain before we get to check it?

All other calls (only get_merkle_block and get_output_status are relevant really, I think) give us block hashes in which the confirmations happened. We currently already call get_block_status for essentially all of them to retrieve the block height. With the upstream change we can now also assert that the tip hasn't changed since we started syncing, which ensures that there is no inconsistency, i.e., block status is confirmed and under best_tip_hash == cur_tip_hash.

We may be able to save some of these calls if upstream also added a best_tip_hash field to the transaction status returned from get_output_status()'s spending transaction. I may add this as follow-up PR upstream, but would like to keep it separate as it is less trivial than the one for the block status.

@tnull
Copy link
Contributor Author

tnull commented Jan 3, 2023

@TheBlueMatt Rebased on main and now uses the recent release of esplora-client, which includes all calls we need.

Also, I think the observation @andrei-21 recently made is correct: even in a reorg-then-reorg-back scenario the tip would change (as it only would reorg-back if there is a longer chain featuring a new tip). As we check tip consistency just before handing over any changes to LDK, we would detect any reorg that happened in the meantime. I therefore think the currently taken fail-restart approach should be safe as is.

Note that we'd currently also restart if we're still on the same chain but a new tip has been appended. If upstream added the tip hash field to the block and tx statuses, we may even be able to recover and continue the sync in this case, but this would mostly be a performance improvement I think.

@TheBlueMatt
Copy link
Collaborator

Also, I think the observation @andrei-21 recently made is correct: even in a reorg-then-reorg-back scenario the tip would change (as it only would reorg-back if there is a longer chain featuring a new tip).

No, this is not correct. Bitcoin Core will expose the intermediary state. So while, yes, eventually we'll get to a new tip, the tip may jump back to the previous tip, the Bitcoin Core will drop the cs_main lock, allowing it to expose that tip to clients (in this case esplora), which can be exposed ultimately to us.

@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch 3 times, most recently from 63e59fb to 0c677d4 Compare February 2, 2023 23:26
Copy link
Contributor

@jkczyz jkczyz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like CI is unhappy for 1.57. Otherwise, looks good. Feel free to rebase and leave any comments needing large changes to a follow-up.

lightning-transaction-sync/src/esplora.rs Outdated Show resolved Hide resolved
lightning-transaction-sync/src/esplora.rs Outdated Show resolved Hide resolved
lightning-transaction-sync/src/lib.rs Show resolved Hide resolved
lightning-transaction-sync/src/lib.rs Outdated Show resolved Hide resolved
lightning-transaction-sync/src/esplora.rs Show resolved Hide resolved
lightning-transaction-sync/src/tests.rs Outdated Show resolved Hide resolved
lightning-transaction-sync/src/tests.rs Outdated Show resolved Hide resolved
lightning-transaction-sync/src/tests.rs Outdated Show resolved Hide resolved
@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch 3 times, most recently from f600374 to 58639e1 Compare February 3, 2023 23:54
@tnull tnull mentioned this pull request Feb 4, 2023
3 tasks
@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch from 58639e1 to dfb9a58 Compare February 4, 2023 00:20
@tnull
Copy link
Contributor Author

tnull commented Feb 4, 2023

Looks like CI is unhappy for 1.57. Otherwise, looks good. Feel free to rebase and leave any comments needing large changes to a follow-up.

Squashed the fixups.

@TheBlueMatt TheBlueMatt added this to the 0.0.114 milestone Feb 4, 2023
@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch from dfb9a58 to d9b2fc2 Compare February 7, 2023 20:58
@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch 3 times, most recently from d79d2e2 to 45d4146 Compare February 9, 2023 19:00
@tnull
Copy link
Contributor Author

tnull commented Feb 9, 2023

Squashed fixups without further changes.

@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch from 45d4146 to d458011 Compare February 9, 2023 19:31
@tnull
Copy link
Contributor Author

tnull commented Feb 9, 2023

Squashed again removing superfluous whitespace:

git diff-tree -U2 45d41467 d4580117
diff --git a/lightning-transaction-sync/src/esplora.rs b/lightning-transaction-sync/src/esplora.rs
index 9f109cb1..807ef807 100644
--- a/lightning-transaction-sync/src/esplora.rs
+++ b/lightning-transaction-sync/src/esplora.rs
@@ -213,5 +213,5 @@ where

                        sync_state.watched_transactions.remove(&ctx.tx.txid());
-
+
                        for input in &ctx.tx.input {
                                sync_state.watched_outputs.remove(&input.previous_output);

This crate provides utilities for syncing LDK via the transaction-based
`Confirm` interface. The initial implementation facilitates
synchronization with an Esplora backend server.
@tnull tnull force-pushed the 2022-11-add-transaction-sync-crate branch from d458011 to ce8b5ba Compare February 9, 2023 21:29
@tnull tnull requested a review from jkczyz February 9, 2023 21:53
Copy link
Contributor

@jkczyz jkczyz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed offline last week. I wasn't able to get the integration test to run on my corp machine. Not sure why but seems like the connection to bitcoind gets disconnected when waiting for blocks. Shouldn't be a blocker, though.

@TheBlueMatt TheBlueMatt merged commit 41a6c67 into lightningdevkit:main Feb 10, 2023
k0k0ne pushed a commit to bitlightlabs/rust-lightning that referenced this pull request Sep 30, 2024
0.0.114 - Mar 3, 2023 - "Faster Async BOLT12 Retries"

API Updates
===========

 * `InvoicePayer` has been removed and its features moved directly into
   `ChannelManager`. As such it now requires a simplified `Router` and supports
   `send_payment_with_retry` (and friends). `ChannelManager::retry_payment` was
   removed in favor of the automated retries. Invoice payment utilities in
   `lightning-invoice` now call the new code (lightningdevkit#1812, lightningdevkit#1916, lightningdevkit#1929, lightningdevkit#2007, etc).
 * `Sign`/`BaseSign` has been renamed `ChannelSigner`, with `EcdsaChannelSigner`
   split out in anticipation of future schnorr/taproot support (lightningdevkit#1967).
 * The catch-all `KeysInterface` was split into `EntropySource`, `NodeSigner`,
   and `SignerProvider`. `KeysManager` implements all three (lightningdevkit#1910, lightningdevkit#1930).
 * `KeysInterface::get_node_secret` is now `KeysManager::get_node_secret_key`
   and is no longer required for external signers (lightningdevkit#1951, lightningdevkit#2070).
 * A `lightning-transaction-sync` crate has been added which implements keeping
   LDK in sync with the chain via an esplora server (lightningdevkit#1870). Note that it can
   only be used on nodes that *never* ran a previous version of LDK.
 * `Score` is updated in `BackgroundProcessor` instead of via `Router` (lightningdevkit#1996).
 * `ChainAccess::get_utxo` (now `UtxoAccess`) can now be resolved async (lightningdevkit#1980).
 * BOLT12 `Offer`, `InvoiceRequest`, `Invoice` and `Refund` structs as well as
   associated builders have been added. Such invoices cannot yet be paid due to
   missing support for blinded path payments (lightningdevkit#1927, lightningdevkit#1908, lightningdevkit#1926).
 * A `lightning-custom-message` crate has been added to make combining multiple
   custom messages into one enum/handler easier (lightningdevkit#1832).
 * `Event::PaymentPathFailure` is now generated for failure to send an HTLC
   over the first hop on our local channel (lightningdevkit#2014, lightningdevkit#2043).
 * `lightning-net-tokio` no longer requires an `Arc` on `PeerManager` (lightningdevkit#1968).
 * `ChannelManager::list_recent_payments` was added (lightningdevkit#1873).
 * `lightning-background-processor` `std` is now optional in async mode (lightningdevkit#1962).
 * `create_phantom_invoice` can now be used in `no-std` (lightningdevkit#1985).
 * The required final CLTV delta on inbound payments is now configurable (lightningdevkit#1878)
 * bitcoind RPC error code and message are now surfaced in `block-sync` (lightningdevkit#2057).
 * Get `historical_estimated_channel_liquidity_probabilities` was added (lightningdevkit#1961).
 * `ChannelManager::fail_htlc_backwards_with_reason` was added (lightningdevkit#1948).
 * Macros which implement serialization using TLVs or straight writing of struct
   fields are now public (lightningdevkit#1823, lightningdevkit#1976, lightningdevkit#1977).

Backwards Compatibility
=======================

 * Any inbound payments with a custom final CLTV delta will be rejected by LDK
   if you downgrade prior to receipt (lightningdevkit#1878).
 * `Event::PaymentPathFailed::network_update` will always be `None` if an
   0.0.114-generated event is read by a prior version of LDK (lightningdevkit#2043).
 * `Event::PaymentPathFailed::all_paths_removed` will always be false if an
   0.0.114-generated event is read by a prior version of LDK. Users who rely on
   it to determine payment retries should migrate to `Event::PaymentFailed`, in
   a separate release prior to upgrading to LDK 0.0.114 if downgrading is
   supported (lightningdevkit#2043).

Performance Improvements
========================

 * Channel data is now stored per-peer and channel updates across multiple
   peers can be operated on simultaneously (lightningdevkit#1507).
 * Routefinding is roughly 1.5x faster (lightningdevkit#1799).
 * Deserializing a `NetworkGraph` is roughly 6x faster (lightningdevkit#2016).
 * Memory usage for a `NetworkGraph` has been reduced substantially (lightningdevkit#2040).
 * `KeysInterface::get_secure_random_bytes` is roughly 200x faster (lightningdevkit#1974).

Bug Fixes
=========

 * Fixed a bug where a delay in processing a `PaymentSent` event longer than the
   time taken to persist a `ChannelMonitor` update, when occurring immediately
   prior to a crash, may result in the `PaymentSent` event being lost (lightningdevkit#2048).
 * Fixed spurious rejections of rapid gossip sync data when the graph has been
   updated by other means between gossip syncs (lightningdevkit#2046).
 * Fixed a panic in `KeysManager` when the high bit of `starting_time_nanos`
   is set (lightningdevkit#1935).
 * Resolved an issue where the `ChannelManager::get_persistable_update_future`
   future would fail to wake until a second notification occurs (lightningdevkit#2064).
 * Resolved a memory leak when using `ChannelManager::send_probe` (lightningdevkit#2037).
 * Fixed a deadlock on some platforms at least when using async `ChannelMonitor`
   updating (lightningdevkit#2006).
 * Removed debug-only assertions which were reachable in threaded code (lightningdevkit#1964).
 * In some cases when payment sending fails on our local channel retries no
   longer take the same path and thus never succeed (lightningdevkit#2014).
 * Retries for spontaneous payments have been fixed (lightningdevkit#2002).
 * Return an `Err` if `lightning-persister` fails to read the directory listing
   rather than panicing (lightningdevkit#1943).
 * `peer_disconnected` will now never be called without `peer_connected` (lightningdevkit#2035)

Security
========

0.0.114 fixes several denial-of-service vulnerabilities which are reachable from
untrusted input from channel counterparties or in deployments accepting inbound
connections or channels. It also fixes a denial-of-service vulnerability in rare
cases in the route finding logic.
 * The number of pending un-funded channels as well as peers without funded
   channels is now limited to avoid denial of service (lightningdevkit#1988).
 * A second `channel_ready` message received immediately after the first could
   lead to a spurious panic (lightningdevkit#2071). This issue was introduced with 0conf
   support in LDK 0.0.107.
 * A division-by-zero issue was fixed in the `ProbabilisticScorer` if the amount
   being sent (including previous-hop fees) is equal to a channel's capacity
   while walking the graph (lightningdevkit#2072). The division-by-zero was introduced with
   historical data tracking in LDK 0.0.112.

In total, this release features 130 files changed, 21457 insertions, 10113
deletions in 343 commits from 18 authors, in alphabetical order:
 * Alec Chen
 * Allan Douglas R. de Oliveira
 * Andrei
 * Arik Sosman
 * Daniel Granhão
 * Duncan Dean
 * Elias Rohrer
 * Jeffrey Czyz
 * John Cantrell
 * Kurtsley
 * Matt Corallo
 * Max Fang
 * Omer Yacine
 * Valentine Wallace
 * Viktor Tigerström
 * Wilmer Paulino
 * benthecarman
 * jurvis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants