Matt Corallo [Sat, 4 Nov 2023 22:09:44 +0000 (22:09 +0000)]
Avoid allocating when checking gossip message signatures
When we check gossip message signatures, there's no reason to
serialize out the full gossip message before hashing, and it
generates a lot of allocations during the initial startup when we
fetch the full gossip from peers.
Matt Corallo [Sat, 4 Nov 2023 21:21:58 +0000 (21:21 +0000)]
Avoid a `tokio::mpsc::Sender` clone for each P2P send operation
Whenever we go to send bytes to a peer, we need to construct a
waker for tokio to call back into if we need to finish sending
later. That waker needs some reference to the peer's read task to
wake it up, hidden behind a single `*const ()`. To do this, we'd
previously simply stored a `Box<tokio::mpsc::Sender>` in that
pointer, which requires a `clone` for each waker construction. This
leads to substantial malloc traffic.
Instead, here, we replace this box with an `Arc`, leaving a single
`tokio::mpsc::Sender` floating around and simply change the
refcounts whenever we construct a new waker, which we can do
without allocations.
Matt Corallo [Sat, 4 Nov 2023 20:37:21 +0000 (20:37 +0000)]
Avoid re-allocating to encrypt gossip messages when forwarding
When we forward gossip messages, we store them in a separate buffer
before we encrypt them (and commit to the order in which they'll
appear on the wire). Rather than storing that buffer encoded with
no headroom, requiring re-allocating to add the message length and
two MAC blocks, we here add the headroom prior to pushing it into
the gossip buffer, avoiding an allocation.
Matt Corallo [Sat, 4 Nov 2023 20:20:12 +0000 (20:20 +0000)]
Use `VecDeque`, rather than `LinkedList` in peer message buffering
When buffering outbound messages for peers, `LinkedList` adds
rather substantial allocation overhead, which we avoid here by
swapping for a `VecDeque`.
Matt Corallo [Mon, 6 Nov 2023 16:57:13 +0000 (16:57 +0000)]
Avoid unnecessarily alloc'ing a new buffer when decrypting messages
When decrypting P2P messages, we already have a read buffer that we
read the message into. There's no reason to allocate a new `Vec` to
store the decrypted message when we can just overwrite the read
buffer and call it a day.
Matt Corallo [Sat, 4 Nov 2023 21:01:18 +0000 (21:01 +0000)]
Pre-allocate the full `Vec` prior to serializing as a `Vec<u8>`
We end up generating a substantial amount of allocations just
doubling `Vec`s when serializing to them, and our
`serialized_length` method is generally rather effecient, so we
just rely on it and allocate correctly up front.
Matt Corallo [Sat, 4 Nov 2023 03:53:46 +0000 (03:53 +0000)]
Reduce on-startup heap frag due to network graph map/vec doubling
When we're reading a `NetworkGraph`, we know how many
nodes/channels we are reading, there's no reason not to
pre-allocate the `IndexedMap`'s inner `HashMap` and `Vec`, which we
do here.
This seems to reduce on-startup heap fragmentation with glibc by
something like 100MiB.
Chris Waterson [Wed, 6 Sep 2023 18:38:34 +0000 (11:38 -0700)]
Add basic async signer tests
Adds a `get_signer` method to the context so that a test can get ahold of the
channel signer. Adds a `set_available` method on the `TestChannelSigner` to
allow a test to enable and disable the signer: when disabled some of the
signer's methods will return `Err` which will typically activate the error
handling case. Adds a `set_channel_signer_available` function on the test
`Node` class to make it easy to enable and disable a specific signer.
Adds a new `async_signer_tests` module:
* Check for asynchronous handling of `funding_created` and `funding_signed`.
* Check that we correctly resume processing after awaiting an asynchronous
signature for a `commitment_signed` event.
* Verify correct handling during peer disconnect.
* Verify correct handling for inbound zero-conf.
If sign_counterparty_commitment fails (i.e. because the signer is
temporarily disconnected), this really indicates that we should
retry the message sending which required the signature later,
rather than force-closing the channel (which probably won't even
work if the signer is missing).
This commit adds retrying of inbound funding_created signing
failures, regenerating the `FundingSigned` message, attempting to
re-sign, and sending it to our peers if we succeed.
If sign_counterparty_commitment fails (i.e. because the signer is
temporarily disconnected), this really indicates that we should
retry the message sending which required the signature later,
rather than force-closing the channel (which probably won't even
work if the signer is missing).
This commit adds retrying of outbound funding_created signing
failures, regenerating the `FundingCreated` message, attempting to
re-sign, and sending it to our peers if we succeed.
If sign_counterparty_commitment fails (i.e. because the signer is
temporarily disconnected), this really indicates that we should
retry the message sending which required the signature later,
rather than force-closing the channel (which probably won't even
work if the signer is missing).
This commit adds initial retrying of failures, specifically
regenerating commitment updates, attempting to re-sign the
`CommitmentSigned` message, and sending it to our peers if we
succed.
Matt Corallo [Tue, 5 Sep 2023 21:13:07 +0000 (21:13 +0000)]
Handle sign_counterparty_commitment failing during inb funding
If sign_counterparty_commitment fails (i.e. because the signer is
temporarily disconnected), this really indicates that we should
retry the message sending which required the signature later,
rather than force-closing the channel (which probably won't even
work if the signer is missing).
Here we add initial handling of sign_counterparty_commitment
failing during inbound channel funding, setting a flag in
`ChannelContext` which indicates we should retry sending the
`funding_signed` later. We don't yet add any ability to do that
retry.
Matt Corallo [Tue, 5 Sep 2023 21:06:22 +0000 (21:06 +0000)]
Handle sign_counterparty_commitment failing during outb funding
If sign_counterparty_commitment fails (i.e. because the signer is
temporarily disconnected), this really indicates that we should
retry the message sending which required the signature later,
rather than force-closing the channel (which probably won't even
work if the signer is missing).
Here we add initial handling of sign_counterparty_commitment
failing during outbound channel funding, setting a new flag in
`ChannelContext` which indicates we should retry sending the
`funding_created` later. We don't yet add any ability to do that
retry.
Matt Corallo [Tue, 5 Sep 2023 20:46:28 +0000 (20:46 +0000)]
Handling for sign_counterparty_commitment failing during normal op
If sign_counterparty_commitment fails (i.e. because the signer is
temporarily disconnected), this really indicates that we should
retry the message sending later, rather than force-closing the
channel (which probably won't even work if the signer is missing).
Here we add initial handling of sign_counterparty_commitment
failing during normal channel operation, setting a new flag in
`ChannelContext` which indicates we should retry sending the
commitment update later. We don't yet add any ability to do that
retry.
Jeffrey Czyz [Wed, 18 Oct 2023 21:28:54 +0000 (16:28 -0500)]
Re-add one-hop onion message fuzzing test
Revert fuzz test removal in 6dc42235baaa22320ad78d3e05fab31edad99328.
The test originally checked that OnionMessenger would fail for one-hop
blinded paths. The commit added support for such paths, but changing the
checks was not sufficient since the node was not connected to the
introduction node of the reply path. This is required in order to work
with the trivial TestMessageRouter. Fix this by explicitly connecting
the nodes.
Jeffrey Czyz [Wed, 25 Oct 2023 21:37:26 +0000 (16:37 -0500)]
Wrap long onion_message fuzz strings
Some editors like vim slow to a crawl when scrolling over long strings
when syntax highlighting is turned on. Limit the length in fuzz strings
to avoid this.
Additional BOLT 12 tests specific to Offer were added, which will live
in the offer module. Thus, it makes sense to move the bech32 tests to
the parse module.
Matt Corallo [Mon, 23 Oct 2023 18:55:17 +0000 (18:55 +0000)]
Use a tuple, not a struct, for `PendingOnionMessage` in bindings
Bindings aren't currently able to handle a struct with a generic
which is actually exposed - we map all structs concretely to a
single type, whereas having fluctuating types on a struct requires
mapping the inner field to a trait first.
Since this isn't super practical, we make `PendingOnionMessage` a
tuple in bindings, rather than a struct.
Matt Corallo [Sat, 21 Oct 2023 02:42:48 +0000 (02:42 +0000)]
Do not compile the `Simple*` type aliases in `c_bindings` at all
Because the bindings changes now require further changes to our
type definitions, avoiding building the `Simple*` type aliases
entirely makes the patchset there simpler.
Matt Corallo [Fri, 20 Oct 2023 17:34:12 +0000 (17:34 +0000)]
Use `Default::default()` for scoring params in tests
In 26c1639ab69d6780c97a118f09e42cb42304088a we switched to using
`Default::default()` to initialize `()` for scoring parameters in
tests. A number of `()`s slipped back in recently, which we replace
here.
Wilmer Paulino [Fri, 13 Oct 2023 21:09:37 +0000 (14:09 -0700)]
Don't sign holder HTLCs along with holder commitments
`sign_holder_commitment_and_htlcs` never really made sense. Unlike
`sign_counterparty_commitment`, the signatures for holder HTLC
transactions may be required much later than the commitment
transaction's. While it was nice for us to only reach the signer once to
obtain all holder signatures, it's not really ideal anymore as we want
our signatures to be random and not reused.
We no longer return all holder HTLC signatures and instead defer to
obtaining them via `EcdsaChannelSigner::sign_holder_htlc_transaction`.
Wilmer Paulino [Fri, 13 Oct 2023 20:52:23 +0000 (13:52 -0700)]
Use sign_holder_htlc_transaction to sign non-anchors holder HTLCs
We want to ensure we use fresh random signatures to prevent certain
classes of transaction replacement attacks at the bitcoin P2P layer.
This was already covered for commitment transactions and zero fee holder
HTLC transactions, but was missing for holder HTLC transactions on
non-anchors channels.
We can easily do this by reusing the existing
`EcdsaChannelSigner::sign_holder_htlc_transaction` method and
circumventing the existing `holder_htlc_sigs/prev_holder_htlc_sigs`
caches, which will be removed in a later commit anyway.
Matt Corallo [Fri, 20 Oct 2023 17:31:42 +0000 (17:31 +0000)]
Apply a default max fee rather than none when paying for BOLT12
If the user declines to specify a `max_total_routing_fee_msat` in
the new BOLT12 payment methods, rather than defaulting to no limit
on the fee we pay at all, we should default to our "usual default",
ie the one calculated in
`RouteParameters::from_payment_params_and_value`.
We do this here, as well as documenting the behavior on the payment
methods.
Wilmer Paulino [Thu, 19 Oct 2023 16:29:21 +0000 (09:29 -0700)]
Only account for fee spike buffer multiple on non-anchor channels
Anchor outputs channels are no longer susceptible to fee spikes as they
now mostly target the dynamic minimum mempool fee and can contribute the
remainder of fees when closing.
Wilmer Paulino [Thu, 19 Oct 2023 16:27:57 +0000 (09:27 -0700)]
Consider anchor outputs value on channel open
We should make sure the funding amount of a channel can cover all its
associated costs, including the value of anchor outputs, to make sure
that it is actually usable once "opened".
Wilmer Paulino [Thu, 19 Oct 2023 16:25:23 +0000 (09:25 -0700)]
Consider anchor outputs value in get_available_balances
This could lead us to sending/forwarding HTLCs that would put us below
our reserve, forcing our counterparty to close the channel on us due to
an invalid update.
Wilmer Paulino [Fri, 13 Oct 2023 20:47:45 +0000 (13:47 -0700)]
Provide missing derivation parameters to OnchainTxHandler
`OnchainTxHandler` will need to construct `HTLCDescriptor`s for holder
HTLCs, but it did not have access to all of the derivation parameters
that need to be provided.
Wilmer Paulino [Fri, 13 Oct 2023 20:49:50 +0000 (13:49 -0700)]
Support signing non-anchors HTLCs with HTLCDescriptor
We plan to use `EcdsaChannelSigner::sign_holder_htlc_transaction` to
also sign holder HTLC transactions on non-anchor outputs channels.
`HTLCDescriptor` was only used in an anchor outputs context, so a few
things needed changing, mostly to handle the different scripts and
feerate.
Matt Corallo [Tue, 17 Oct 2023 16:23:20 +0000 (16:23 +0000)]
Update docs on `MonitorEvent::HolderForceClosed`
In a96e2fe144383ea6fd670153fb895ee07a3245ef we renamed
`MonitorEvent::CommitmentTxConfirmed` to `HolderForceClosed` to
better document what actually happened. However, we failed to
update the documentation on the type, which we do here.
Define the BOLT 12 message flow in ChannelManager's
OffersMessageHandler implementation.
- An invoice_request message results in responding with an invoice
message if it can be verified that the request is for a valid offer.
- An invoice is paid if it can be verified to have originated from a
sent invoice_request or a refund.
- An invoice_error is sent in some failure cases.
- Initial messages enqueued for sending are released to OnionMessenger
Jeffrey Czyz [Thu, 19 Oct 2023 22:49:13 +0000 (17:49 -0500)]
Check offer expiry when building invoice in no-std
Building an invoice will fail if the underlying offer or refund has
already expired. The check was skipped in no-std since there is no
system clock. However, the invoice creation time can be used instead.
This prevents responding to an invoice request if the offer has already
expired.
Add a utility to ChannelManager for creating a Bolt12Invoice for a
Refund such that the ChannelManager can recognize the PaymentHash and
reconstruct the PaymentPreimage from the PaymentSecret, the latter of
which is contained in a BlindedPath within the invoice.
Add a utility to ChannelManager for sending an InvoiceRequest for an
Offer such that derived keys are used for the payer id. This allows for
stateless verification of any Invoice messages before it is paid.
Also tracks future payments using the given PaymentId such that the
corresponding Invoice is paid only once.
Jeffrey Czyz [Thu, 19 Oct 2023 19:38:16 +0000 (14:38 -0500)]
Absolute expiry or timer tick payment expiration
Pending outbound payments use an absolute expiry to determine when they
are considered stale and should be fail. In `no-std`, this may result in
long timeouts as the highest seen block time is used. Instead, allow for
expiration based on timer ticks. This will be use in an upcoming commit
for invoice request expiration.
Upcoming commits will add utilities for sending an InvoiceRequest for an
Offer and an Invoice for a Refund. These messages need to be enqueued so
that they can be released in ChannelManager's implementation of
OffersMessageHandler to OnionMessenger for sending.
These messages do not need to be serialized as they must be resent upon
restart.
Matt Corallo [Wed, 11 Oct 2023 14:01:28 +0000 (14:01 +0000)]
Immediately unblock channels on duplicate claims
When `MonitorUpdateCompletionAction`s were added, we didn't
consider the case of a duplicate claim during normal HTLC
processing (as the handling only had an `if let` rather than a
`match`, which made the branch easy to miss). This can lead to a
channel freezing indefinitely if an HTLC is claimed (without a
`commitment_signed`), the peer disconnects, and then the HTLC is
claimed again, leading to a never-completing
`MonitorUpdateCompletionAction`.
The fix is simple - if we get back an
`UpdateFulfillCommitFetch::DuplicateClaim` when claiming from the
inbound edge, immediately unlock the outbound edge channel with a
new `MonitorUpdateCompletionAction::FreeOtherChannelImmediately`.
Here we implement this fix by actually generating the new variant
when a claim is duplicative.
Matt Corallo [Wed, 11 Oct 2023 13:56:00 +0000 (13:56 +0000)]
Add an immediately-freeing `MonitorUpdateCompletionAction`.
When `MonitorUpdateCompletionAction`s were added, we didn't
consider the case of a duplicate claim during normal HTLC
processing (as the handling only had an `if let` rather than a
`match`, which made the branch easy to miss). This can lead to a
channel freezing indefinitely if an HTLC is claimed (without a
`commitment_signed`), the peer disconnects, and then the HTLC is
claimed again, leading to a never-completing
`MonitorUpdateCompletionAction`.
The fix is simple - if we get back an
`UpdateFulfillCommitFetch::DuplicateClaim` when claiming from the
inbound edge, immediately unlock the outbound edge channel with a
new `MonitorUpdateCompletionAction::FreeOtherChannelImmediately`.
Here we add the new variant, which we start generating in the next
commit.
Elias Rohrer [Thu, 19 Oct 2023 15:00:50 +0000 (17:00 +0200)]
Don't apply PathFailure::ChannelUpdateMessage
If we receive a channel update from an intermediary via a failure onion
we shouldn't apply them in a persisted and network-observable way to our
network graph, as this might introduce a privacy leak. Here, we
therefore avoid applying such updates to our network graph.
Willem Van Lint [Thu, 28 Sep 2023 01:36:21 +0000 (18:36 -0700)]
Construct ShutdownResult as a struct in Channel
This refactors ShutdownResult as follows:
- Makes ShutdownResult a struct instead of a tuple to represent
individual results that need to be handled. This recently also
includes funding batch closure propagations.
- Makes Channel solely responsible for constructing ShutdownResult as
it should own all channel-specific logic.