rust-lightning
2 years agoMerge pull request #1153 from TheBlueMatt/2021-11-0.0.103 v0.0.103
Matt Corallo [Wed, 3 Nov 2021 03:30:39 +0000 (03:30 +0000)]
Merge pull request #1153 from TheBlueMatt/2021-11-0.0.103

One final fix + cut 0.0.103

2 years agoBump crate versions to 0.0.103/invoice 0.11 2021-11-0.0.103
Matt Corallo [Wed, 3 Nov 2021 01:14:53 +0000 (01:14 +0000)]
Bump crate versions to 0.0.103/invoice 0.11

2 years agoUpdate CHANGELOG for 0.0.103
Matt Corallo [Wed, 3 Nov 2021 01:05:05 +0000 (01:05 +0000)]
Update CHANGELOG for 0.0.103

2 years agoTweak serialization of ScorerUsingTime for better forward compat
Matt Corallo [Wed, 3 Nov 2021 01:11:25 +0000 (01:11 +0000)]
Tweak serialization of ScorerUsingTime for better forward compat

2 years agoMerge pull request #1150 from TheBlueMatt/2021-11-103-bindings
Matt Corallo [Tue, 2 Nov 2021 21:56:00 +0000 (21:56 +0000)]
Merge pull request #1150 from TheBlueMatt/2021-11-103-bindings

Pre-0.0.103 Bindings Tweaks

2 years agoAdd `(C-not exported)` tags as required in tuple types 2021-11-103-bindings
Matt Corallo [Mon, 1 Nov 2021 22:01:57 +0000 (22:01 +0000)]
Add `(C-not exported)` tags as required in tuple types

This prepares us for C bindings auto-exporting tuple type fields.

2 years agoAdd `(C-not exported)` tag to a `Payee` modifier with move semantics
Matt Corallo [Mon, 1 Nov 2021 04:23:30 +0000 (04:23 +0000)]
Add `(C-not exported)` tag to a `Payee` modifier with move semantics

This matches the other `Payee` move-modifier functions.

2 years agoRemove now-unused import in routing/mod.rs
Matt Corallo [Sun, 31 Oct 2021 00:26:54 +0000 (00:26 +0000)]
Remove now-unused import in routing/mod.rs

2 years agoMake payment_path_failed path type bindings-mappable
Matt Corallo [Sun, 31 Oct 2021 18:21:46 +0000 (18:21 +0000)]
Make payment_path_failed path type bindings-mappable

The bindings don't currently support passing `Vec`s of objects
which it mappes as "opaque types". This is because it will require
clones to convert its own list of references to Rust's list of
objects.

In the near future we should resolve this limitation, allowing us
to revert this (and make `find_route`'s method signature similarly
cleaner), but for now we must avoid `Vec<OpaqueType>`.

2 years agoRename Payee::new to Payee::from_node_id to clarify it somewhat
Matt Corallo [Sun, 31 Oct 2021 18:20:27 +0000 (18:20 +0000)]
Rename Payee::new to Payee::from_node_id to clarify it somewhat

This also differentiates it from the bindings default-constructed
`new` method which is constructed when all fields are exposed and
of mappable types.

2 years agoRemove trailing ;s from macro calls to silence new rustc warnings
Matt Corallo [Sun, 31 Oct 2021 18:19:39 +0000 (18:19 +0000)]
Remove trailing ;s from macro calls to silence new rustc warnings

2 years agoMerge pull request #1146 from jkczyz/2021-10-score-serialization
Matt Corallo [Tue, 2 Nov 2021 20:36:22 +0000 (20:36 +0000)]
Merge pull request #1146 from jkczyz/2021-10-score-serialization

Scorer serialization

2 years agoImplement (de)serialization for Scorer
Jeffrey Czyz [Fri, 29 Oct 2021 04:44:26 +0000 (23:44 -0500)]
Implement (de)serialization for Scorer

Scorer should be serialized to retain penalty data between restarts.
Implement (de)serialization for Scorer by serializing last failure times
as duration since the UNIX epoch. For no-std, the zero-Duration is used.

2 years agoParameterize Scorer by a Time trait
Jeffrey Czyz [Fri, 29 Oct 2021 13:52:27 +0000 (08:52 -0500)]
Parameterize Scorer by a Time trait

Scorer uses time to determine how much to penalize a channel after a
failure occurs. Parameterizing it by time cleans up the code such that
no-std support is in a single AlwaysPresent struct, which implements the
Time trait. Time is implemented for std::time::Instant when std is
available.

This parameterization also allows for deterministic testing since a
clock could be devised to advance forward as needed.

2 years agoRefactor channel failure penalty logic
Jeffrey Czyz [Fri, 29 Oct 2021 04:23:45 +0000 (23:23 -0500)]
Refactor channel failure penalty logic

Move channel failure penalty logic into a ChannelFailure abstraction.
This encapsulates the logic for accumulating penalties and decaying them
over time. It also is responsible for the no-std behavior. This cleans
up Scorer and will make it easier to serialize it.

2 years agoClarify Scorer docs around penalizing channels
Jeffrey Czyz [Mon, 1 Nov 2021 21:35:39 +0000 (16:35 -0500)]
Clarify Scorer docs around penalizing channels

2 years agoMerge pull request #1149 from jkczyz/2021-11-network-graph
Matt Corallo [Mon, 1 Nov 2021 22:19:08 +0000 (22:19 +0000)]
Merge pull request #1149 from jkczyz/2021-11-network-graph

Shared ownership of NetworkGraph

2 years agoMake NetGraphMsgHandler::network_graph private
Jeffrey Czyz [Mon, 1 Nov 2021 20:01:39 +0000 (15:01 -0500)]
Make NetGraphMsgHandler::network_graph private

Since NetworkGraph has shared ownership, NetGraphMsgHandler does not
need to expose its field.

2 years agoParameterize NetGraphMsgHandler with NetworkGraph
Jeffrey Czyz [Mon, 1 Nov 2021 18:14:14 +0000 (13:14 -0500)]
Parameterize NetGraphMsgHandler with NetworkGraph

NetworkGraph is owned by NetGraphMsgHandler, but DefaultRouter requires
a reference to it. Introduce shared ownership to NetGraphMsgHandler so
that both can use the same NetworkGraph.

2 years agoMerge pull request #1141 from TheBlueMatt/2021-10-payment-id-on-partial-failure
Matt Corallo [Sun, 31 Oct 2021 18:33:16 +0000 (18:33 +0000)]
Merge pull request #1141 from TheBlueMatt/2021-10-payment-id-on-partial-failure

Rewrite InvoicePayer retry to correctly handle MPP partial failures

2 years agoCheck for invoice expiry in InvoicePayer before we send any HTLCs 2021-10-payment-id-on-partial-failure
Matt Corallo [Thu, 28 Oct 2021 18:46:02 +0000 (18:46 +0000)]
Check for invoice expiry in InvoicePayer before we send any HTLCs

2 years agoAdd integration test for InvoicePayerretry on an immediate failure
Matt Corallo [Wed, 27 Oct 2021 22:22:48 +0000 (22:22 +0000)]
Add integration test for InvoicePayerretry on an immediate failure

2 years agoAdd an integration test for InvoicePayer paying when one part fails
Matt Corallo [Wed, 27 Oct 2021 22:15:11 +0000 (22:15 +0000)]
Add an integration test for InvoicePayer paying when one part fails

This tests the multi-part-single-failure-immediately fixes in the
previous commit.

2 years agoRewrite InvoicePayer retry to correctly handle MPP partial failures
Matt Corallo [Tue, 26 Oct 2021 22:52:06 +0000 (22:52 +0000)]
Rewrite InvoicePayer retry to correctly handle MPP partial failures

This rewrites a good chunk of the retry logic in `InvoicePayer` to
address two issues:
 * it was not considering the return value of `send_payment` (and
   `retry_payment`) may indicate a failure on some paths but not
   others,
 * it was not considering that more failures may still come later
   when removing elements from the retry count map. This could
   result in us seeing an MPP-partial-failure, failing to retry,
   removing the retries count entry, and then retrying other parts,
   potentially forever.

2 years agoDont unwrap `RouteParameter::expiry_time` as users can set it
Matt Corallo [Wed, 27 Oct 2021 22:12:07 +0000 (22:12 +0000)]
Dont unwrap `RouteParameter::expiry_time` as users can set it

Users can provide anything they want as `RouteParameters` so we
shouldn't assume any fields are set any particular way, including
`expiry_time` set at all.

2 years agoExpand `InvoicePayer` documentation somewhat to clarify edge-cases
Matt Corallo [Sat, 30 Oct 2021 01:52:43 +0000 (01:52 +0000)]
Expand `InvoicePayer` documentation somewhat to clarify edge-cases

2 years agoProvide payment retry data when an MPP payment failed partially
Matt Corallo [Tue, 26 Oct 2021 21:39:31 +0000 (21:39 +0000)]
Provide payment retry data when an MPP payment failed partially

This will allow `InvoicePayer` to properly retry payments that only
partially failed to send.

2 years agoMove PaymentId to a [u8; 32] in bindings as for other hash objects
Matt Corallo [Tue, 26 Oct 2021 21:38:46 +0000 (21:38 +0000)]
Move PaymentId to a [u8; 32] in bindings as for other hash objects

This should allow us to fix
https://github.com/lightningdevkit/ldk-garbagecollected/issues/52

2 years agoMerge pull request #1144 from jkczyz/2021-10-invoice-payer-scoring
Matt Corallo [Fri, 29 Oct 2021 20:16:36 +0000 (20:16 +0000)]
Merge pull request #1144 from jkczyz/2021-10-invoice-payer-scoring

Penalize failed channels

2 years agoTest InvoicePayer in BackgroundProcessor
Jeffrey Czyz [Tue, 24 Aug 2021 04:56:59 +0000 (23:56 -0500)]
Test InvoicePayer in BackgroundProcessor

Proof of concept showing InvoicePayer can be used with an
Arc<ChannelManager> passed to BackgroundProcessor. Likely do not need to
merge this commit.

2 years agoPenalize failed channels in Scorer
Jeffrey Czyz [Wed, 27 Oct 2021 15:39:22 +0000 (10:39 -0500)]
Penalize failed channels in Scorer

As payments fail, the channel responsible for the failure may be
penalized. Implement Scorer::payment_path_failed to penalize the failed
channel using a configured penalty. As time passes, the penalty is
reduced using exponential decay, though penalties will accumulate if the
channel continues to fail. The decay interval is also configurable.

2 years agoNotify scorer of failing payment path and channel
Jeffrey Czyz [Thu, 14 Oct 2021 18:04:39 +0000 (13:04 -0500)]
Notify scorer of failing payment path and channel

Upon receiving a PaymentPathFailed event, the failing payment may be
retried on a different path. To avoid using the channel responsible for
the failure, a scorer should be notified of the failure before being
used to find a new route.

Add a payment_path_failed method to routing::Score and call it in
InvoicePayer's event handler. Introduce a LockableScore parameterization
to InvoicePayer so the scorer is locked only once before calling
find_route.

2 years agoMerge pull request #1137 from TheBlueMatt/2021-10-ping-fixes
Matt Corallo [Thu, 28 Oct 2021 20:57:21 +0000 (20:57 +0000)]
Merge pull request #1137 from TheBlueMatt/2021-10-ping-fixes

Give peers which are sending us messages/receiving messages from us longer to respond to ping

2 years agoLog peer public key more thoroughly when logging in peer_handler 2021-10-ping-fixes
Matt Corallo [Wed, 27 Oct 2021 20:06:13 +0000 (20:06 +0000)]
Log peer public key more thoroughly when logging in peer_handler

2 years agoGive peers one timer tick to finish handshake before disconnecting
Matt Corallo [Thu, 21 Oct 2021 22:33:42 +0000 (22:33 +0000)]
Give peers one timer tick to finish handshake before disconnecting

This ensures we don't let a hung connection stick around forever if
the peer never completes the initial handshake.

This also resolves a race where, on receiving a second connection
from a peer, we may reset their_node_id to None to prevent sending
messages even though the `channel_encryptor`
`is_ready_for_encryption()`. Sending pings only checks the
`channel_encryptor` status, not `their_node_id` resulting in an
`unwrap` on `None` in `enqueue_message`.

2 years agoGive peers which are sending us messages longer to respond to ping
Matt Corallo [Mon, 11 Oct 2021 04:24:08 +0000 (04:24 +0000)]
Give peers which are sending us messages longer to respond to ping

See comment for rationale.

2 years agoUtil-ify enqueueing an encoded message in peer_handler
Matt Corallo [Thu, 28 Oct 2021 17:43:58 +0000 (17:43 +0000)]
Util-ify enqueueing an encoded message in peer_handler

This marginally simplifies coming commits.

2 years agoConstify the ratio in buf limits between forward and init sync msgs
Matt Corallo [Mon, 25 Oct 2021 17:31:34 +0000 (17:31 +0000)]
Constify the ratio in buf limits between forward and init sync msgs

2 years agoMerge pull request #1142 from TheBlueMatt/2021-10-on-sent-fees
Matt Corallo [Wed, 27 Oct 2021 22:13:36 +0000 (22:13 +0000)]
Merge pull request #1142 from TheBlueMatt/2021-10-on-sent-fees

Track the amount spent on fees as payments are retried

2 years agoTrack the amount spent on fees as payments are retried 2021-10-on-sent-fees
Matt Corallo [Wed, 27 Oct 2021 19:04:22 +0000 (19:04 +0000)]
Track the amount spent on fees as payments are retried

Especially once we merge the `InvoicePayer` logic soon, we'll want
to expose the total fee paid in the `PaymentSent` event.

2 years agoPass the failing/succeeding `Path` to PendingOutboundPayment meths
Matt Corallo [Wed, 27 Oct 2021 18:57:16 +0000 (18:57 +0000)]
Pass the failing/succeeding `Path` to PendingOutboundPayment meths

This will make the next commit much simpler

2 years agoAdd a utility trait in `router` to get the fees along a given path
Matt Corallo [Wed, 27 Oct 2021 18:24:44 +0000 (18:24 +0000)]
Add a utility trait in `router` to get the fees along a given path

2 years agoMerge pull request #1059 from jkczyz/2021-08-payment-retry
Matt Corallo [Wed, 27 Oct 2021 16:58:19 +0000 (16:58 +0000)]
Merge pull request #1059 from jkczyz/2021-08-payment-retry

Payment Retries

2 years agoImplement Payer and Router for lightning crate
Jeffrey Czyz [Tue, 24 Aug 2021 05:14:10 +0000 (00:14 -0500)]
Implement Payer and Router for lightning crate

Implements Payer for ChannelManager and Rotuer for find_route, which can
be used to parameterize InvoicePayer when needing payment retries.

2 years agoFail payment retry if Invoice is expired
Jeffrey Czyz [Thu, 30 Sep 2021 18:30:24 +0000 (11:30 -0700)]
Fail payment retry if Invoice is expired

According to BOLT 11:

- after the `timestamp` plus `expiry` has passed
  - SHOULD NOT attempt a payment

Add a convenience method for checking if an Invoice has expired, and use
it to short-circuit payment retries.

2 years agoSupport paying zero-value invoices
Jeffrey Czyz [Mon, 4 Oct 2021 16:39:59 +0000 (11:39 -0500)]
Support paying zero-value invoices

2 years agoAdd InvoicePayer for retrying failed payments
Jeffrey Czyz [Tue, 24 Aug 2021 05:08:15 +0000 (00:08 -0500)]
Add InvoicePayer for retrying failed payments

When a payment fails, it's useful to retry the payment once the network
graph and channel scores are updated. InvoicePayer is a utility for
making payments which will retry any failed payment paths for a payment
up to a configured number of total attempts. It is parameterized by a
Payer and Router for ease of customization and testing.

Implement EventHandler for InvoicePayer as a decorator that intercepts
PaymentPathFailed events and retries that payment using the parameters
from the event. It delegates to the decorated EventHandler after retries
have been exhausted and for other events.

2 years agoUnify route finding methods
Jeffrey Czyz [Mon, 25 Oct 2021 23:48:52 +0000 (18:48 -0500)]
Unify route finding methods

An upcoming Router interface will be used for finding a Route both when
initially sending a payment and also when retrying failed payment paths.
Unify the three varieties of get_route so the interface can consist of a
single method implemented by the new `find_route` method. Give get_route
pub(crate) visibility so it can still be used in tests.

2 years agoRewrite Invoice's interface in terms of msats
Jeffrey Czyz [Mon, 4 Oct 2021 14:20:49 +0000 (09:20 -0500)]
Rewrite Invoice's interface in terms of msats

InvoiceBuilder's interface was changed recently to work in terms of
msats. Update Invoice's interface to return the amount in msats, too,
and make amount_pico_btc private.

2 years agoAdd PaymentId to PaymentPathFailed event
Jeffrey Czyz [Thu, 30 Sep 2021 22:29:44 +0000 (15:29 -0700)]
Add PaymentId to PaymentPathFailed event

The PaymentId is needed when retrying payments. Include it in the
PaymentPathFailed event so it can be used in that manner.

2 years agoAdd PaymentId to PaymentSent event
Jeffrey Czyz [Sun, 17 Oct 2021 22:21:01 +0000 (17:21 -0500)]
Add PaymentId to PaymentSent event

The payment_hash may not uniquely identify the payment if it has been
reused. Include the payment_id in PaymentSent events so it can
correlated with the send_payment call.

2 years agoExpose log_bytes! macro for use in other crates
Jeffrey Czyz [Tue, 24 Aug 2021 04:55:28 +0000 (23:55 -0500)]
Expose log_bytes! macro for use in other crates

Needed to log PaymentHash in the lightning-invoice crate when retrying
payments.

2 years agoAdd `PeerManager::disconnect_all_peers` to avoid complexity in BP
Matt Corallo [Tue, 26 Oct 2021 02:03:02 +0000 (02:03 +0000)]
Add `PeerManager::disconnect_all_peers` to avoid complexity in BP

In the coming commits simply calling `timer_tick_occurred` will no
longer disconnect all peers, so its helpful to have a utility
method.

2 years agoCorrect send-bounding logic in `TestRoutingMessageHandler`
Matt Corallo [Mon, 25 Oct 2021 21:51:08 +0000 (21:51 +0000)]
Correct send-bounding logic in `TestRoutingMessageHandler`

The `cmp::min` appeared to confused `end` for a count.

2 years agoMerge pull request #1138 from TheBlueMatt/2021-10-payee-in-monitors
Matt Corallo [Mon, 25 Oct 2021 20:32:27 +0000 (20:32 +0000)]
Merge pull request #1138 from TheBlueMatt/2021-10-payee-in-monitors

Store `Payee` info with HTLCs

2 years agoStore `Payee` information in `HTLCSource::OutboundRoute`. 2021-10-payee-in-monitors
Matt Corallo [Mon, 25 Oct 2021 04:46:26 +0000 (04:46 +0000)]
Store `Payee` information in `HTLCSource::OutboundRoute`.

This stores and tracks HTLC payee information with HTLCSource info,
allowing us to provide it back to the user if the HTLC fails and
ensuring persistence by keeping it with the HTLC itself as it
passes between Channel and ChannelMonitor.

2 years agoCopy `Payee` into `Route`s to provide them to `ChannelManager`
Matt Corallo [Mon, 25 Oct 2021 04:42:29 +0000 (04:42 +0000)]
Copy `Payee` into `Route`s to provide them to `ChannelManager`

2 years agoMake `Payee::pubkey` pub.
Matt Corallo [Mon, 25 Oct 2021 17:52:30 +0000 (17:52 +0000)]
Make `Payee::pubkey` pub.

`Payee` is expected to be used by users to get routes for payment
retries, potentially with their own router. Thus, its helpful if it
is pub, even if it is redundant with the last hop in the `path`
field in `Events::PaymentPathFailed`.

2 years agoMerge pull request #1134 from jkczyz/2021-10-payee-arg
Matt Corallo [Mon, 25 Oct 2021 16:09:06 +0000 (16:09 +0000)]
Merge pull request #1134 from jkczyz/2021-10-payee-arg

Payee abstraction for use in get_route and PaymentPathFailed

2 years agoUse option TLV decoding for short_channel_id
Jeffrey Czyz [Fri, 22 Oct 2021 05:27:58 +0000 (00:27 -0500)]
Use option TLV decoding for short_channel_id

Using ignorable TLV decoding is only applicable for an Option containing
an enum, but short_channel_id is an Option<u64>. Use option TLV encoding
instead.

2 years agoInclude PaymentPathRetry data in PaymentPathFailed
Jeffrey Czyz [Thu, 21 Oct 2021 22:52:53 +0000 (17:52 -0500)]
Include PaymentPathRetry data in PaymentPathFailed

When a payment path fails, it may be retried. Typically, this means
re-computing the route after updating the NetworkGraph and channel
scores in order to avoid the failing hop. The last hop in
PaymentPathFailed's path field contains the pubkey, amount, and CLTV
values needed to pass to get_route. However, it does not contain the
payee's features and route hints from the invoice.

Include the entire set of parameters in PaymentPathRetry and add it to
the PaymentPathFailed event. Add a get_retry_route wrapper around
get_route that takes PaymentPathRetry. This allows an EventHandler to
retry failed payment paths using the payee's route hints and features.

2 years agoRemove outdated line from get_route docs
Jeffrey Czyz [Wed, 20 Oct 2021 14:22:38 +0000 (09:22 -0500)]
Remove outdated line from get_route docs

2 years agoDefine Payee abstraction for use in get_route
Jeffrey Czyz [Wed, 20 Oct 2021 14:15:31 +0000 (09:15 -0500)]
Define Payee abstraction for use in get_route

A payee can be identified by a pubkey and optionally have an associated
set of invoice features and route hints. Use this in get_route instead
of three separate parameters. This may be included in PaymentPathFailed
later to use when finding a new route.

2 years agoMerge pull request #1104 from TheBlueMatt/2021-10-payment-id-in-monitors
Matt Corallo [Fri, 22 Oct 2021 19:33:33 +0000 (19:33 +0000)]
Merge pull request #1104 from TheBlueMatt/2021-10-payment-id-in-monitors

Reload pending outbound payments from ChannelMonitors on startup

2 years agoAdd a test of an HTLC being fulfilled and then later failed 2021-10-payment-id-in-monitors
Matt Corallo [Wed, 20 Oct 2021 23:40:09 +0000 (23:40 +0000)]
Add a test of an HTLC being fulfilled and then later failed

Peers probably shouldn't do this, but if they want to give us free
money, we should take it and not generate any spurious events.

2 years agoMove test_dup_htlc_onchain_fails_on_reload to payment_tests
Matt Corallo [Sun, 10 Oct 2021 23:42:03 +0000 (23:42 +0000)]
Move test_dup_htlc_onchain_fails_on_reload to payment_tests

test_dup_htlc_onchain_fails_on_reload is now more of a
payment_test than a functional_test, testing for handling of
pending payments.

2 years agoAdd some basic test coverage of monitor payment data reloading
Matt Corallo [Sun, 10 Oct 2021 23:36:57 +0000 (23:36 +0000)]
Add some basic test coverage of monitor payment data reloading

2 years agoReload pending payments from ChannelMonitor HTLC data on reload
Matt Corallo [Sun, 10 Oct 2021 23:36:44 +0000 (23:36 +0000)]
Reload pending payments from ChannelMonitor HTLC data on reload

If we go to send a payment, add the HTLC(s) to the channel(s),
commit the ChannelMonitor updates to disk, and then crash, we'll
come back up with no pending payments but HTLC(s) ready to be
claim/failed.

This makes it rather impractical to write a payment sender/retryer,
as you cannot guarantee atomicity - you cannot guarantee you'll
have retry data persisted even if the HTLC(s) are actually pending.

Because ChannelMonitors are *the* atomically-persisted data in LDK,
we lean on their current HTLC data to figure out what HTLC(s) are a
part of an outbound payment, rebuilding the pending payments list
on reload.

2 years agoAdd PaymentSecrets to HTLCSource::OutboundRoute objects
Matt Corallo [Mon, 4 Oct 2021 04:04:46 +0000 (04:04 +0000)]
Add PaymentSecrets to HTLCSource::OutboundRoute objects

2 years agoRename payment object vars to refer to payments and not session IDs
Matt Corallo [Thu, 21 Oct 2021 19:05:48 +0000 (19:05 +0000)]
Rename payment object vars to refer to payments and not session IDs

2 years agoTrack payments after they resolve until all HTLCs are finalized
Matt Corallo [Sun, 3 Oct 2021 22:33:12 +0000 (22:33 +0000)]
Track payments after they resolve until all HTLCs are finalized

In the next commit, we will reload lost pending payments from
ChannelMonitors during restart. However, in order to avoid
re-adding pending payments which have already been fulfilled, we
must ensure that we do not fully remove pending payments until all
HTLCs for the payment have been fully removed from their
ChannelMonitors.

We do so here, introducing a new PendingOutboundPayment variant
called `Completed` which only tracks the set of pending HTLCs.

2 years agoInform ChannelManager when fulfilled HTLCs are finalized
Matt Corallo [Sat, 2 Oct 2021 22:35:07 +0000 (22:35 +0000)]
Inform ChannelManager when fulfilled HTLCs are finalized

When an HTLC has been failed, we track it up until the point there
exists no broadcastable commitment transaction which has the HTLC
present, at which point Channel returns the HTLCSource back to the
ChannelManager, which fails the HTLC backwards appropriately.

When an HTLC is fulfilled, however, we fulfill on the backwards path
immediately. This is great for claiming upstream HTLCs, but when we
want to track pending payments, we need to ensure we can check with
ChannelMonitor data to rebuild pending payments. In order to do so,
we need an event similar to the HTLC failure event, but for
fulfills instead.

Specifically, if we force-close a channel, we remove its off-chain
`Channel` object entirely, at which point, on reload, we may notice
HTLC(s) which are not present in our pending payments map (as they
may have received a payment preimage, but not fully committed to
it). Thus, we'd conclude we still have a retryable payment, which
is untrue.

This commit does so, informing the ChannelManager via a new return
element where appropriate of the HTLCSource corresponding to the
failed HTLC.

2 years agoImplement `HashMap` read for `MaybeReadable` values
Matt Corallo [Sun, 3 Oct 2021 00:46:10 +0000 (00:46 +0000)]
Implement `HashMap` read for `MaybeReadable` values

This allows us to read a `HashMap` that has values which may be
skipped if they are some backwards-compatibility type.

We also take this opportunity to fail deserialization if keys are
duplicated.

2 years agoMake `Channel::monitor_updating_restored`'s return tuple a struct
Matt Corallo [Sun, 10 Oct 2021 23:56:11 +0000 (23:56 +0000)]
Make `Channel::monitor_updating_restored`'s return tuple a struct

This improves readability at the callsite and in the function.

2 years agoMake `Channel::revoke_and_ack`'s return tuple a struct
Matt Corallo [Sat, 2 Oct 2021 01:59:38 +0000 (01:59 +0000)]
Make `Channel::revoke_and_ack`'s return tuple a struct

This substantially improves readability at the callsite and in the
function.

2 years agoMerge pull request #1108 from TheBlueMatt/2021-10-persist-mon-blocks
Matt Corallo [Wed, 20 Oct 2021 00:53:26 +0000 (00:53 +0000)]
Merge pull request #1108 from TheBlueMatt/2021-10-persist-mon-blocks

Persist ChannelMonitors after new blocks are connected

2 years agoClarify the contexts in which persist_new_channel may be called 2021-10-persist-mon-blocks
Matt Corallo [Tue, 19 Oct 2021 21:49:03 +0000 (21:49 +0000)]
Clarify the contexts in which persist_new_channel may be called

Its somewhat confusing that `persist_new_channel` is called on
startup for an existing channel in common deployments, so we call
it out explicitly.

2 years agoAlways release `MonitorEvent`s to `ChannelManager` after 3 blocks
Matt Corallo [Thu, 14 Oct 2021 23:38:08 +0000 (23:38 +0000)]
Always release `MonitorEvent`s to `ChannelManager` after 3 blocks

If we have a `ChannelMonitor` update from an on-chain event which
returns a `TemporaryFailure`, we block `MonitorEvent`s from that
`ChannelMonitor` until the update is persisted. This prevents
duplicate payment send events to the user after payments get
reloaded from monitors on restart.

However, if the event being avoided isn't going to generate a
PaymentSent, but instead result in us claiming an HTLC from an
upstream channel (ie the HTLC was forwarded), then the result of a
user delaying the event is that we delay getting our money, not a
duplicate event.

Because user persistence may take an arbitrary amount of time, we
need to bound the amount of time we can possibly wait to return
events, which we do here by bounding it to 3 blocks.

Thanks to Val for catching this in review.

2 years agoUpdate test_dup_htlc_onchain_fails_on_reload for new persist API
Matt Corallo [Sun, 10 Oct 2021 18:02:17 +0000 (18:02 +0000)]
Update test_dup_htlc_onchain_fails_on_reload for new persist API

ChannelMonitors now require that they be re-persisted before
MonitorEvents be provided to the ChannelManager, the exact thing
that test_dup_htlc_onchain_fails_on_reload was testing for when it
*didn't* happen. As such, test_dup_htlc_onchain_fails_on_reload is
now testing that we bahve correctly when the API guarantees are not
met, something we don't need to do.

Here, we adapt it to test the new API requirements through
ChainMonitor's calls to the Persist trait instead.

2 years agoPersist `ChannelMonitor`s after new blocks are connected
Matt Corallo [Wed, 13 Oct 2021 20:05:48 +0000 (20:05 +0000)]
Persist `ChannelMonitor`s after new blocks are connected

This resolves several user complaints (and issues in the sample
node) where startup is substantially delayed as we're always
waiting for the chain data to sync.

Further, in an upcoming PR, we'll be reloading pending payments
from ChannelMonitors on restart, at which point we'll need the
change here which avoids handling events until after the user
has confirmed the `ChannelMonitor` has been persisted to disk.
It will avoid a race where we
 * send a payment/HTLC (persisting the monitor to disk with the
   HTLC pending),
 * force-close the channel, removing the channel entry from the
   ChannelManager entirely,
 * persist the ChannelManager,
 * connect a block which contains a fulfill of the HTLC, generating
   a claim event,
 * handle the claim event while the `ChannelMonitor` is being
   persisted,
 * persist the ChannelManager (before the CHannelMonitor is
   persisted fully),
 * restart, reloading the HTLC as a pending payment in the
   ChannelManager, which now has no references to it except from
   the ChannelMonitor which still has the pending HTLC,
 * replay the block connection, generating a duplicate PaymentSent
   event.

2 years agoUse an opaque type to describe monitor updates in Persist
Matt Corallo [Thu, 7 Oct 2021 23:59:47 +0000 (23:59 +0000)]
Use an opaque type to describe monitor updates in Persist

In the next commit, we'll be originating monitor updates both from
the ChainMonitor and from the ChannelManager, making simple
sequential update IDs impossible.

Further, the existing async monitor update API was somewhat hard to
work with - instead of being able to generate monitor_updated
callbacks whenever a persistence process finishes, you had to
ensure you only did so at least once all previous updates had also
been persisted.

Here we eat the complexity for the user by moving to an opaque
type for monitor updates, tracking which updates are in-flight for
the user and only generating monitor-persisted events once all
pending updates have been committed.

2 years agoMove ChannelManager::monitor_updated to a MonitorEvent
Matt Corallo [Thu, 7 Oct 2021 18:51:49 +0000 (18:51 +0000)]
Move ChannelManager::monitor_updated to a MonitorEvent

In the next commit we'll need ChainMonitor to "see" when a monitor
persistence completes, which means `monitor_updated` needs to move
to `ChainMonitor`. The simplest way to then communicate that
information to `ChannelManager` is via `MonitorEvet`s, which seems
to line up ok, even if they're now constructed by multiple
different places.

2 years agoMerge pull request #1133 from jkczyz/2021-10-expand-scorer
Matt Corallo [Tue, 19 Oct 2021 21:55:49 +0000 (21:55 +0000)]
Merge pull request #1133 from jkczyz/2021-10-expand-scorer

Include source and destination nodes in routing::Score

2 years agoAdd source and target nodes to routing::Score
Jeffrey Czyz [Mon, 18 Oct 2021 23:36:35 +0000 (18:36 -0500)]
Add source and target nodes to routing::Score

Expand routing::Score::channel_penalty_msat to include the source and
target node ids of the channel. This allows scorers to avoid certain
nodes altogether if desired.

2 years agoSimplify prefers_shorter_route_with_higher_fees
Jeffrey Czyz [Sat, 16 Oct 2021 02:31:33 +0000 (21:31 -0500)]
Simplify prefers_shorter_route_with_higher_fees

In order to make the scoring tests easier to read, only check the
relevant RouteHop fields. The remaining fields are tested elsewhere.
Expand the test to show the path used without scoring.

2 years agoMove the two-AtomicUsize counter in peer_handler to a util struct
Matt Corallo [Fri, 8 Oct 2021 22:54:32 +0000 (22:54 +0000)]
Move the two-AtomicUsize counter in peer_handler to a util struct

We also take this opportunity to drop byte_utils::le64_to_array, as
our MSRV now supports the native to_le_bytes() call.

2 years agoMove MonitorEvent serialization to TLV-enum-upgradable from custom
Matt Corallo [Thu, 7 Oct 2021 04:14:35 +0000 (04:14 +0000)]
Move MonitorEvent serialization to TLV-enum-upgradable from custom

2 years agoMerge pull request #1127 from TheBlueMatt/2021-10-0.0.102 v0.0.102
Matt Corallo [Mon, 18 Oct 2021 19:23:25 +0000 (19:23 +0000)]
Merge pull request #1127 from TheBlueMatt/2021-10-0.0.102

Cut 0.0.102

2 years agoBump crate versions to 0.0.102 and lightning-invoice 0.10 2021-10-0.0.102
Matt Corallo [Sat, 16 Oct 2021 00:23:33 +0000 (00:23 +0000)]
Bump crate versions to 0.0.102 and lightning-invoice 0.10

2 years agoAdd CHANGELOG entries for 0.0.102
Matt Corallo [Sat, 16 Oct 2021 00:21:57 +0000 (00:21 +0000)]
Add CHANGELOG entries for 0.0.102

2 years agoMerge pull request #1121 from TheBlueMatt/2021-10-return-temp-id
Matt Corallo [Sat, 16 Oct 2021 02:15:07 +0000 (02:15 +0000)]
Merge pull request #1121 from TheBlueMatt/2021-10-return-temp-id

Expose temporary channel ID and user channel ID pre-funding

2 years agoMerge pull request #1124 from jkczyz/2021-10-default-channel-scoring
Matt Corallo [Sat, 16 Oct 2021 01:58:15 +0000 (01:58 +0000)]
Merge pull request #1124 from jkczyz/2021-10-default-channel-scoring

Add channel scoring to get_route

2 years agoRename create_channel param to user_channel_id to standardize it 2021-10-return-temp-id
Matt Corallo [Fri, 15 Oct 2021 20:16:15 +0000 (20:16 +0000)]
Rename create_channel param to user_channel_id to standardize it

2 years agoMerge pull request #1123 from tnull/fix_video_url
Matt Corallo [Fri, 15 Oct 2021 22:07:34 +0000 (22:07 +0000)]
Merge pull request #1123 from tnull/fix_video_url

Fixed 'Advancing Bitcoin' video URL.

2 years agoAdd channel scoring to get_route
Jeffrey Czyz [Mon, 27 Sep 2021 20:52:57 +0000 (13:52 -0700)]
Add channel scoring to get_route

Failed payments may be retried, but calling get_route may return a Route
with the same failing path. Add a routing::Score trait used to
parameterize get_route, which it calls to determine how much a channel
should be penalized in terms of msats willing to pay to avoid the
channel.

Also, add a Scorer struct that implements routing::Score with a constant
constant penalty. Subsequent changes will allow for more robust scoring
by feeding back payment path success and failure to the scorer via event
handling.

2 years agoFixed 'Advancing Bitcoin' video URL.
Elias Rohrer [Thu, 14 Oct 2021 08:35:12 +0000 (10:35 +0200)]
Fixed 'Advancing Bitcoin' video URL.

2 years agoMerge pull request #1112 from TheBlueMatt/2021-10-mon-refactors
Matt Corallo [Thu, 14 Oct 2021 01:45:20 +0000 (01:45 +0000)]
Merge pull request #1112 from TheBlueMatt/2021-10-mon-refactors

Hide internals of ChainMonitor behind getter

2 years agoUse Persister to return errors in fuzzers not chain::Watch 2021-10-mon-refactors
Matt Corallo [Sat, 9 Oct 2021 00:23:44 +0000 (00:23 +0000)]
Use Persister to return errors in fuzzers not chain::Watch

2 years agoUse Persister to return errors in tests not chain::Watch
Matt Corallo [Fri, 8 Oct 2021 06:16:28 +0000 (06:16 +0000)]
Use Persister to return errors in tests not chain::Watch

As ChainMonitor will need to see those errors in a coming PR,
we need to return errors via Persister so that our ChainMonitor
chain::Watch implementation sees them.

2 years agoHandle Persister returning TemporaryFailure for new channels
Matt Corallo [Fri, 8 Oct 2021 20:40:34 +0000 (20:40 +0000)]
Handle Persister returning TemporaryFailure for new channels

Previously, if a Persister returned a TemporaryFailure error when
we tried to persist a new channel, the ChainMonitor wouldn't track
the new ChannelMonitor at all, generating a PermanentFailure later
when the updating is restored.

This fixes that by correctly storing the ChannelMonitor on
TemporaryFailures, allowing later update restoration to happen
normally.

This is (indirectly) tested in the next commit where we use
Persister to return all monitor-update errors.