Matt Corallo [Wed, 1 Sep 2021 16:48:35 +0000 (16:48 +0000)]
XXX: Track SCID aliases from our counterparty and use them in invoices
New `funding_locked` messages can include SCID aliases which our
counterparty will recognize as "ours" for the purposes of relaying
transactions to us. This avoids telling the world about our
on-chain transactions every time we want to receive a payment, and
will allow for receiving payments before the funding transaction
appears on-chain.
Here we store the new SCID aliases and use them in invoices instead
of he "standard" SCIDs.
XXX: Note in spec pr that we need to drop the "MUST NOT retransmit funding_locked"
message in reconnection if we are passed initial reconnect. This may
imply a feature bit, but will at least imply some kind of "MUST NOT
retransmit if it doesn't have evidence the counterparty interpreted the
SCID alias previously sent" (to avoid backwards incompat).
Matt Corallo [Tue, 7 Dec 2021 19:11:18 +0000 (19:11 +0000)]
Make `Channel::get_announcement_sigs` return an Option and log
Channel::get_announcement_sigs is only used in contexts where we
have a logger already, and the error returned is always ignored, so
instead of returning an ignored error message we return an `Option`
directly and log when it won't be too verbose.
Matt Corallo [Thu, 18 Nov 2021 21:54:13 +0000 (21:54 +0000)]
Disconect `announcement_signatures` sending from `funding_locked`
The spec actually requires we never send `announcement_signatures`
(and, thus, `channel_announcement`s) until after six confirmations.
However, we would happily have sent them prior to that as long as
we exchange `funding_locked` messages with our countarparty. Thanks
to re-broadcasting this issue is largely harmless, however it could
have some negative interactions with less-robust peers. Much more
importantly, this represents an important step towards supporting
0-conf channels, where `funding_locked` messages may be exchanged
before we even have an SCID to construct the messages with.
Because there is no ACK mechanism for `announcement_signatures` we
rely on existing channel updates to stop rebroadcasting them - if
we sent a `commitment_signed` after an `announcement_signatures`
and later receive a `revoke_and_ack`, we know our counterparty also
received our `announcement_signatures`. This may resolve some rare
edge-cases where we send a `funding_locked` which our counterparty
receives, but lose connection before the `announcement_signatures`
(usually the very next message) arrives.
Sadly, because the set of places where an `announcement_signatures`
may now be generated more closely mirrors where `funding_locked`
messages may be generated, but they are now separate, there is a
substantial amount of code motion providing relevant parameters
about current block information and ensuring we can return new
`announcement_signatures` messages.
Matt Corallo [Thu, 18 Nov 2021 21:54:10 +0000 (21:54 +0000)]
Unset `Channel::is_usable` if mon update is blocking funding_locked
If we have not yet sent `funding_locked` only because of a pending
channel monitor update, we shouldn't consider a channel
`is_usable`. This has a number of downstream effects, including
not attempting to route payments through the channel, not sending
private `channel_update` messages to our counterparty, or sending
channel_announcement messages if our couterparty has already signed
for it.
We further gate generation of `node_announcement`s on `is_usable`,
preventing generation of those or `announcement_signatures` until
we've sent our `funding_locked`.
Finally, `during_funding_monitor_fail` is updated to test a case
where we see the funding transaction lock in but have a pending
monitor update failure, then receive `funding_locked` from our
counterparty and ensure we don't generate the above messages until
after the monitor update completes.
Matt Corallo [Mon, 15 Nov 2021 01:09:27 +0000 (01:09 +0000)]
Do not Send FundingLocked messages while disconnected
While its generally harmless to do so (the messages will simply be
dropped in `PeerManager`) there is a potential race condition where
the FundingLocked message enters the outbound message queue, then
the peer reconnects, and then the FundingLocked message is
delivered prior to the normal ChannelReestablish flow.
We also take this opportunity to rewrite
`test_funding_peer_disconnect` to be explicit instead of using
`reconnect_peers`. This allows it to check each message being sent
carefully, whereas `reconnect_peers` is rather lazy and accepts
that sometimes signatures will be exchanged, and sometimes not.
Matt Corallo [Sun, 14 Nov 2021 17:25:39 +0000 (17:25 +0000)]
Move node_id signing of ChannelAnnouncement into Signer
This removes one more place where we directly access the node_id
secret key in `ChannelManager`, slowly marching towards allowing
the node_id secret key to be offline in the signer.
More importantly, it allows more ChannelAnnouncement logic to move
into the `Channel` without having to pass the node secret key
around, avoiding the announcement logic being split across two
files.
Matt Corallo [Fri, 17 Dec 2021 22:38:46 +0000 (22:38 +0000)]
Swap around generic argument ordering in DefaultRouter for bindings
The bindings generation really should support default generic types
in where clauses, but currently does not. To avoid needing to add
support during the current release process, we simply swap around
the arguments to move them to the first <> instead of the where.
Add new invoice CreationError::InvalidAmount for use in checking `create_inbound_payment`
in an invoice creation utility. Note that if the error type of `create_inbound_payment` ever
changed, we'd be forced to update the invoice utility's callsite to handle the new error
Matt Corallo [Tue, 14 Dec 2021 01:33:37 +0000 (01:33 +0000)]
Reject channel_update messages with timestamps too old or new
Because we time out channel info that is older than two weeks now,
we should also reject new channel info that is older than two
weeks, in addition to rejecting future channel info.
Matt Corallo [Sat, 4 Dec 2021 23:41:37 +0000 (23:41 +0000)]
Use `Event::PaymentFailed` in `InvoicePayer` to remove retry count
This finally fixes the bug described in the previous commits where
we retry a payment after its retry count has expired due to early
removal of the payment from the retry count tracking map. A test is
also added which demonstrates the bug in previous versions and
which passes now.
Matt Corallo [Fri, 10 Dec 2021 00:28:24 +0000 (00:28 +0000)]
Expose an event when a payment has failed and retries complete
When a payment fails, a payer needs to know when they can consider
a payment as fully-failed, and when only some of the HTLCs in the
payment have failed. This isn't possible with the current event
scheme, as discovered recently and as described in the previous
commit.
This adds a new event which describes when a payment is fully and
irrevocably failed, generating it only after the payment has
expired or been marked as expired with
`ChannelManager::mark_retries_exceeded` *and* all HTLCs for it
have failed. With this, a payer can more simply deduce when a
payment has failed and use that to remove payment state or
finalize a payment failure.
Matt Corallo [Fri, 3 Dec 2021 19:57:37 +0000 (19:57 +0000)]
Add a variant to `PendingOutboundPayment` for retries-exceeded
When a payer gives up trying to retry a payment, they don't know
for sure what the current state of the event queue is.
Specifically, they cannot be sure that there are not multiple
additional `PaymentPathFailed` or even `PaymentSuccess` events
pending which they will see later. Thus, they have a very hard
time identifying whether a payment has truly failed (and informing
the UI of that fact) or if it is still pending. See [1] for more
information.
In order to avoid this mess, we will resolve it here by having the
payer give `ChannelManager` a bit more information - when they
have given up on a payment - and using that to generate a
`PaymentFailed` event when all paths have failed.
This commit adds the neccessary storage and changes for the new
state inside `ChannelManager` and a public method to mark a payment
as failed, the next few commits will add the new `Event` and use
the new features in our `PaymentRetrier`.
Matt Corallo [Tue, 7 Dec 2021 19:17:57 +0000 (19:17 +0000)]
Upgrade to codecov uploader v2
Some time ago codecov stopped supporting their old v1 uploader, and
it seems they've now finally turned it off, so we aren't getting
any coverage reports anymore. Hopefully upgrading is pretty trivial.
Matt Corallo [Mon, 6 Dec 2021 00:18:59 +0000 (00:18 +0000)]
Support the `channel_type` feature bit.
Note that this feature bit does absolutely nothing. We signal it
(as we already support channel type negotiation), but do not bother
to look to see if peers support it, as we don't care - we simply
look for the TLV entry and deduce if a peer supports channel type
negotiation from that.
The only behavioral change at all here is that we don't barf if a
peer sets channel type negotiation to required via the feature bit
(instead of failing the channel at open-time), but of course no
implementations do this, and likely won't for some time (if ever -
you can simply fail channels with unknown types later, and there's
no reason to refuse connections, really).
As defined in https://github.com/lightning/bolts/pull/906
Jeffrey Czyz [Fri, 3 Dec 2021 19:04:58 +0000 (13:04 -0600)]
Ensure ChannelManager methods are idempotent
During event handling, ChannelManager methods may need to be called as
indicated in the Event documentation. Ensure that these calls are
idempotent for the same event rather than panicking. This allows users
to persist events for later handling without needing to worry about
processing the same event twice (e.g., if ChannelManager is not
persisted but the events were, the restarted ChannelManager would return
some of the same events).
Matt Corallo [Mon, 29 Nov 2021 21:36:12 +0000 (21:36 +0000)]
Drop `MonitorUpdateErr` in favor of opaque errors.
We don't expect users to ever change behavior based on the string
contained in a `MonitorUpdateErr`, except log it, so there's little
reason to not just log it ourselves and return a `()` for errors.
We do so here, simplifying the callsite in `ChainMonitor` as well.
Matt Corallo [Sun, 17 Oct 2021 21:28:50 +0000 (21:28 +0000)]
Always return failure in `update_monitor` after funding spend
Previously, monitor updates were allowed freely even after a
funding-spend transaction confirmed. This would allow a race
condition where we could receive a payment (including the
counterparty revoking their broadcasted state!) and accept it
without recourse as long as the ChannelMonitor receives the block
first, the full commitment update dance occurs after the block is
connected, and before the ChannelManager receives the block.
Obviously this is an incredibly contrived race given the
counterparty would be risking their full channel balance for it,
but its worth fixing nonetheless as it makes the potential
ChannelMonitor states simpler to reason about.
The test in this commit also tests the behavior changed in the
previous commit.
Matt Corallo [Mon, 6 Dec 2021 00:12:35 +0000 (00:12 +0000)]
Remove OnionV2 parsing support
OnionV2s don't (really) work on Tor anymore anyway, and the field
is set for removal in the BOLTs [1]. Sadly because of the way
addresses are parsed we have to continue to understand that type 3
addresses are 12 bytes long. Thus, for simplicity we keep the
`OnionV2` enum variant around and just make it an opaque 12 bytes,
with the documentation updated to note the deprecation.
Jeffrey Czyz [Wed, 1 Dec 2021 04:57:32 +0000 (22:57 -0600)]
Fix shift overflow in Scorer::channel_penalty_msat
An unchecked shift of more than 64 bits on u64 values causes a shift
overflow panic. This may happen if a channel is penalized only once and
(1) is not successfully routed through and (2) after 64 or more half
life decays. Use a checked shift to prevent this from happening.
Jeffrey Czyz [Wed, 1 Dec 2021 00:27:08 +0000 (18:27 -0600)]
Decay channel failure penalty upon success
If a payment failed to route through a channel, a penalty is applied to
the channel in the future when finding a route. This penalty decays over
time. Immediately decay the penalty by one half life when a payment is
successfully routed through the channel.
Jeffrey Czyz [Tue, 30 Nov 2021 23:16:05 +0000 (17:16 -0600)]
Score successful payment paths
Expand the Score trait with a payment_path_successful function for
scoring successful payment paths. Called by InvoicePayer's EventHandler
implementation when processing PaymentPathSuccessful events. May be used
by Score implementations to revert any channel penalties that were
applied by calls to payment_path_failed.
Matt Corallo [Mon, 29 Nov 2021 20:05:35 +0000 (20:05 +0000)]
Fix regression when reading `Event::PaymentReceived` in some cases
For some reason rustc was deciding on a type for the `Option` being
deserialized for us as `_user_payment_id`. This really, really,
absolutely should have been a compile failure - the type (with
methods called on it!) was ambiguous! Instead, rustc seems to have
been defaulting to `Option<()>`, causing us to read zero of the
eight bytes in the `user_payment_id` field, which returns an
`Err(InvalidValue)` error as TLVs must always be read fully.
This should likely be reported to rustc as its definitely a bug,
but I cannot seem to cause the same error on any kinda of
vaguely-minimized version of the same code.
Matt Corallo [Tue, 9 Nov 2021 21:25:33 +0000 (21:25 +0000)]
Explicitly support counterparty setting 0 channel reserve
A peer providing a channel_reserve_satoshis of 0 (or less than our
dust limit) is insecure, but only for them. Because some LSPs do it
with some level of trust of the clients (for a substantial UX
improvement), we explicitly allow it. Because its unlikely to
happen often in normal testing, we test it explicitly here.
Matt Corallo [Sun, 17 Oct 2021 21:26:04 +0000 (21:26 +0000)]
Continue after a single failure in `ChannelMonitor::update_monitor`
`ChannelMonitorUpdate`s may contain multiple updates, including, eg
a payment preimage after a commitment transaction update. While
such updates are generally not generated today, we shouldn't return
early out of the update loop, causing us to miss any updates after
an earlier update fails.
Matt Corallo [Mon, 22 Nov 2021 18:00:08 +0000 (18:00 +0000)]
Seal `scoring::Time` and only use `Instant` or `Eternity` publicly
`scoring::Time` exists in part to make testing the passage of time
in `Scorer` practical. To allow no-std users to provide a time
source it was exposed as a trait as well. However, it seems
somewhat unlikely that a no-std user is going to have a use for
providing their own time source (otherwise they wouldn't be a
no-std user), and likely they won't have a graph in memory either.
`scoring::Time` as currently written is also exceptionally hard to
write C bindings for - the C bindings trait mappings relies on the
ability to construct trait implementations at runtime with function
pointers (i.e. `dyn Trait`s). `scoring::Time`, on the other hand,
is a supertrait of `core::ops::Sub` which requires a `sub` method
which takes a type parameter and returns a type parameter. Both of
which aren't practical in bindings, especially given the
`Sub::Output` associated type is not bound by any trait bounds at
all (implying we cannot simply map the `sub` function to return an
opaque trait object).
Thus, for simplicity, we here simply seal `scoring::Time` and make
it effectively-private, ensuring the bindings don't need to bother
with it.
Matt Corallo [Mon, 22 Nov 2021 03:27:17 +0000 (03:27 +0000)]
Make `Score : Writeable` in c_bindings and impl on `LockedScore`
Ultimately we likely need to wrap the locked `Score` in a struct
that exposes writeable somehow, but because all traits have to be
fully concretized for C bindings we'll still need `Writeable` on
all `Score` in order to expose `Writeable` on the locked score.
Otherwise, we'll only have a `LockedScore` with a `Score` visible
that only has the `Score` methods, never the original type.
Matt Corallo [Sat, 13 Nov 2021 01:54:54 +0000 (01:54 +0000)]
Re-broadcast our own gossip even if its same as the last broadcast
Even if our gossip hasn't changed, we should be willing to
re-broadcast it to our peers. All our peers may have been
disconnected the last time we broadcasted it.
Matt Corallo [Sat, 13 Nov 2021 01:06:09 +0000 (01:06 +0000)]
Update `ChannelUpdate::timestamp` when channels are dis-/en-abled
We update the `Channel::update_time_counter` field (which is copied
into `ChannelUpdate::timestamp`) only when the channel is
initialized or closes, and when a new block is connected. However,
if a peer disconnects or reconnects, we may wish to generate
`ChannelUpdate` updates in between new blocks. In such a case, we
need to make sure the `timestamp` field is newer than any previous
updates' `timestamp` fields, which we do here by simply
incrementing it when the channel status is changed.
As a side effect of this we have to update
`test_background_processor` to ensure it eventually succeeds even
if the serialization of the `ChannelManager` changes after the test
begins.
Matt Corallo [Sat, 13 Nov 2021 00:27:05 +0000 (00:27 +0000)]
Separate ChannelAnnouncement and ChannelUpdate broadcast conditions
When a `ChannelUpdate` message is generated for broadcast as a part
of a `BroadcastChannelAnnouncement` event, it may be newer than our
previous `ChannelUpdate` and need to be broadcast. However, if the
`ChannelAnnouncement` had already been seen we wouldn't
re-broadcast either message as the `handle_channel_announcement`
call would fail, short-circuiting the condition to broadcast both.
Instead, we split the broadcast of each message as well as the
conditional so that we always attempt to handle each message and
update our local graph state, then broadcast the message if its
update was processed successfully.
Matt Corallo [Tue, 9 Nov 2021 21:12:30 +0000 (21:12 +0000)]
Store holder channel reserve and max-htlc-in-flight explicitly
Previously, `holder_selected_channel_reserve_satoshis` and
`holder_max_htlc_value_in_flight_msat` were constant functions
of the channel value satoshis. However, in the future we may allow
allow users to specify it. In order to do so, we'll need to track
them explicitly, including serializing them as appropriate.
We go ahead and do so here, in part as it will make testing
different counterparty-selected channel reserve values easier.
Jeffrey Czyz [Thu, 18 Nov 2021 22:24:14 +0000 (16:24 -0600)]
Generate PaymentPathSuccessful event for each path
A single PaymentSent event is generated when a payment is fulfilled.
This is occurs when the preimage is revealed on the first claimed HTLC.
For subsequent HTLCs, the event is not generated.
In order to score channels involved with a successful payments, the
scorer must be notified of each successful path involved in the payment.
Add a PaymentPathSuccessful event for this purpose. Generate it whenever
a part is removed from a pending outbound payment. This avoids duplicate
events when reconnecting to a peer.