When we receive an inbound HTLC from a peer on an inbound channel,
make sure the funder can still cover the additional on-chain cost
of the HTLC while maintaining their channel reserve.
When we're sending an outbound HTLC, make sure the funder can still
cover the additional on-chain cost of the HTLC while maintaining
their channel reserve.
+ implement fee spike buffer for channel initiators sending payments.
Also add an additional spec-deviating fee spike buffer on the
receiving side (but don't close the channel if this reserve is
violated, just fail the HTLC).
From lightning-rfc PR #740.
Co-authored-by: Matt Corallo <git@bluematt.me> Co-authored-by: Valentine Wallace <vwallace@protonmail.com>
Refactor: move channel checks for HTLC adds into Channel
This also includes adding a closure that creates a new pending HTLC status
as a parameter for Channel's update_add_htlc. This will later be useful
when we add the check for fee spike buffer violations, which will also result
in changing an HTLC's pending status to failing.
Matt Corallo [Thu, 28 May 2020 20:00:46 +0000 (16:00 -0400)]
Expose private keys from InMemoryChannelKeys publicly
As we drop the requirement that all ChannelKeys expose the private
keys used, we should have a way to access the private keys in use
when using InMemoryChannelKeys.
Antoine Riard [Mon, 18 May 2020 08:19:32 +0000 (04:19 -0400)]
Add test_key_derivation_params
`to_local` output or remote output on remote commitment transaction
needs a channel keys to be spent. As per-channel keys are derived from
KeysManager seed and per-channel secrets those must be backed up by
any descriptor bookmarking for latter spend. We test that generating
a new KeysManager loaded with such backed-up seed/per-channel secrets
return the correct keys for spending a `to_local` output.
Antoine Riard [Mon, 4 May 2020 06:35:54 +0000 (02:35 -0400)]
Dry-up witnessScript in sign_remote_htlc_transaction
Instead of blindly signing provided witnessScript, signer must derive
channel keys corresponding to the provided per-commitment-point and
regenerate templated witnessScript to ensure its syntax correctness.
Antoine Riard [Mon, 4 May 2020 06:20:56 +0000 (02:20 -0400)]
Dry-up witnessScript in sign_justice_transaction
Instead of blindly signing provided witnessScript, signer must derive
channel keys corresponding to the provided per-commitment-point and
regenerate templated witnessScript to ensure its syntax correctness.
Antoine Riard [Tue, 28 Apr 2020 00:07:17 +0000 (20:07 -0400)]
Dedup RemoteTxCache by removing OnchainTxHandler copy
RemoteTxCache was providing all data needed at transaction
signature for any remote HTLC transaction or justice transaction.
This move was making the API between OnchainTxHandle akward and
scope of responsibilites with ChannelMonitor unclear.
Instead scope OnchainTxHandler to transaction-finalization, fee-bumping
and broadcast only.
Antoine Riard [Wed, 6 May 2020 00:00:01 +0000 (20:00 -0400)]
Extend KeysInterface with derive_channel_keys
A dynamic-p2wsh-output like `to_local` on local commitment/HTLC txn
require a signature from delayed_payment_key to be spend. Instead of
sending private key in descriptor, we ask for spender to derive again
the corresponding ChannelKeys based on key state, uniquely identifying
a channel and encompassing its unique start data.
Matt Corallo [Tue, 12 May 2020 17:47:54 +0000 (13:47 -0400)]
Three small fixes to work around our bindings generator limitations
* Return Self instead of the fully-written types for constructors,
* Place definitions before use (in this case for KeysInterface),
* Don't import foo::bar::self, but import foo::bar
+ a spelling fix in the KeysInterface docs for get_onion_rand.
Matt Corallo [Tue, 12 May 2020 17:31:20 +0000 (13:31 -0400)]
Make RoutingMessageHandler a generic Deref instead of an Arc
We also update to use single idents when referencing the Deref=*
types since the automated code generator is pretty braindead.
This also moves some test utils out of peer_handler.rs and into
util::test_utils to standardize things a little bit, which we need
to concretize the PeerHandler types used in testing.
Matt Corallo [Tue, 12 May 2020 17:20:31 +0000 (13:20 -0400)]
Make ManyChannelMonitor Keys an associated type
Instead of using a raw generic type, an associted type allows us
to have explicit docs on the type, which is nice. More importantly,
however, our automated bindings generator knows how to read
associated types but not raw generics.
Also, our bindings generator expects things which are referenced to
have already been defined, so we move ManyChannelMonitor below the
ChannelMonitor definition.
Arik Sosman [Mon, 18 May 2020 17:55:28 +0000 (10:55 -0700)]
Extract encode_and_send_msg into a method.
This is a response to splitting #585 into smaller components. This extraction will permit a future extraction of all message handling into a separate method, and then later even into a separate trait that will be accessible through language bindings.
Antoine Riard [Tue, 12 May 2020 00:29:39 +0000 (20:29 -0400)]
Add KeysManager::derive_unique_start
In next commit, we add derive_channel_keys, a helper to rederive
keys from a SpendableOuptutDescriptor. We still need to ensure
that user rederive same set of keys even if KeyManager is started
at a later time. For doing so we need to pass starting time as
part of the re-derived sha_state, therefore we need to make it
accessible and part of channel state key material.
Seed is already required to be conserved between KeysManager
serializations.
Antoine Riard [Tue, 24 Mar 2020 03:28:00 +0000 (23:28 -0400)]
Replace is_htlc in InputMaterial by InputDescriptor
As we cache more and more transaction elements in OnchainTxHandler
we should dry up completly InputMaterial until them being replaced
directly by InputDescriptor
As we can't predict if any and which revoked commitment tx is
going to appear onchain we have by design to cache all htlc information
to regenerate htlc script if needed.
Matt Corallo [Tue, 12 May 2020 17:17:49 +0000 (13:17 -0400)]
Drop OutPoint::new since the struct is all pub
This makes it easier for our automated bindings generator to
function as it tries to automatically create a ::new if the struct
contains only pub elements who's type is convertible.
This caused a bunch of cascading changes, including
passing loggers down to Channels in function calls
rather than having each Channel have a pointer to the
ChannelManager's Logger (which was a circular reference).
Other structs that the Channel had passed its Logger to also
had their loggers removed. Other newly unused Loggers were
also removed, especially when keeping them would've caused
a bunch of extra test changes to be necessary, e.g. with
the ChainWatchInterfaceUtil's Logger.
Matt Corallo [Tue, 12 May 2020 01:09:44 +0000 (21:09 -0400)]
Fix a few new (and one old) issues in the new channel_update
We need to always set lowest_inbound_channel_fees to None if there
are no channels (and we should ignore the channels which are
disabled for the purpose of lowest-fee calculations). Further, we
cannot unwrap the channel lookups as they may be for channels which
are not related to the channel we are processing an update for.
Finally, we can satisfy borrowck much easier since things are on
self instead of on a MutexGuard.
Matt Corallo [Tue, 12 May 2020 01:08:35 +0000 (21:08 -0400)]
Add assertion since we now have a pub field that is PartialEq
We previously were only able to assert that the route graph
serialization roundtrips were good by comparing the network
messages returned from them, but we can now do better as the graph
is exposed publicly via a simple datastructure that implements
PartialEq.
Matt Corallo [Tue, 12 May 2020 01:07:02 +0000 (21:07 -0400)]
Move get_addresses to network_graph and drop now-useless log_trace
Because we expose the internals we don't need a method to log
their contents anymore, and get_addresses can now avoid copying as
we expose the RwLock directly
8ce2223b6952567b28adfcc11c23c9f19c4c0324 introduced a new field in
the "Node" objects used in our functional tests - the node_id. Its
not a bad idea to cache it, but unless we want to commit and use it
everywhere, we should avoid duplicating data, especially in tests
where we'd rather exercise the underlying code than bypass it.
Matt Corallo [Sun, 3 May 2020 02:00:08 +0000 (22:00 -0400)]
Require option_static_remotekey in channel/channelmonitor.
This simplifies channelmonitor quite nicely (as expected) as we
never have to be concerned with learning data in a DataLossProtect
which is require for us to claim our funds from the latest remote
commitment transaction.
Matt Corallo [Tue, 3 Mar 2020 20:27:45 +0000 (15:27 -0500)]
Add detection of feature_static_remotekey support and print
This adds the ability to check for static_remotekey in appropriate
feature contexts and prints it at connect time. It is still
considered unknown for the purposes of requires_unknown_bits() as
we don't yet implement it.
Make channel reserve variable names less confusing.
Previous to this commit, variables such as their_channel_reserve
referred to the channel reserve that _we_ are required to keep,
(the value is initially set by the remote). Similarly,
variables such as our_channel_reserve referred to the channel
reserve that we require the remote to keep.
Change this to use local_channel_reserve / remote_channel_reserve
to refer to the the channel reserve that the local is required to keep
and the channel reserve that the remote is required to keep, respectively.
Matt Corallo [Mon, 9 Mar 2020 17:45:15 +0000 (13:45 -0400)]
Check local signtures explicitly in channel tx-generation tests
It appears the local signatures which are specified in the channel
transaction-generation tests were never checked directly (though
they were checked as a part of the overall fully-signed-transaction
tests).
Check them explicitly so that they can be updated for static remote
key.
Include tests for requires_unknown_bits and supports_unknown_bits when
an unknown even bit, odd bit, or neither is set. Refactor bit clearing
such that tests and production code share the same code path. Fix a
potential spec incompatibility (currently only exposed in testing code)
where trailing zero bytes are not removed after a bit is cleared.
Converting from InitFeatures to other Features is accomplished using
Features::with_known_relevant_init_flags. Define a more general
to_context method which converts from Features of one Context to
another.
Additionally, ensure the source context only has known flags before
selecting flags for the target context.
Refactoring the features module allowed for making code specific to
certain contexts generalizable. Specifically, KNOWN_FEATURE_MASK
is defined on Context instead of hardcoded in each method
specialization. Thus, such methods are no longer required.
Features for a given context are duplicated throughout the features
module. Use a macro for defining a Context and the applicable features
such that features only need to be defined for a Context in one place.
The Context provides bitmasks for selecting known and unknown feature
flags.
BOLT 1 and BOLT 9 refer to features as "known" if a peer understands
them. They also use the term "supported" to mean either optional or
required.
Update the features module to use similar terminology.
- Define contexts in terms of required and optional features rather than
just supported features
- Define known features as those that are optional or required
- Rename supported() constructor to known()
For completeness, clear_optional_bit for each feature is now called
clear_bits and clears both optional and required bits.
Encapsulate feature flag checking and manipulation
Each feature is represented by two bits within Features' flags field.
Working with these flags requires bitwise operations, which can be error
prone. Rather than directly checking and manipulating bits, encapsulate
the bits within each feature trait and provide mechanisms for doing so.
This removes the need to comment on which features correspond to bitwise
expressions since the expressions use feature trait identifiers instead.
With this approach, byte literals and expressions can be evaluated at
compile time still. However, for these cases, knowing which byte within
the flags that a feature corresponds to still must be determined by the
implementor.
Remove the special case where initial_routing_sync has no even bit. Now,
it (bit 2) is considered known by the implementation.
The initial_routing_sync feature is set by peer_handler whenever a full
sync of the network graph is desired. It is not explicitly set when
creating features with InitFeatures::supported().
An upcoming refactor will change supported() to known(), which will
return all features known by the implementation. Thus, the
initial_routing_sync flag will need to be set by default. This commit
makes the behavior change ahead of the refactor.
The test_upfront_shutdown_script functional test clears this feature
flag. However, the method used to clear the flag is implemented by bit
toggling. Thus, if the flag is not set the method would actually set it.
Implement the method using bit clearing instead.
Matt Corallo [Thu, 23 Apr 2020 19:43:21 +0000 (15:43 -0400)]
Don't modify LocalCommitmemntTransaction after construction
Instead of adding signatures to LocalCommitmentTransactions, we
instead leave them unsigned and use them to construct signed
Transactions when we want them. This cleans up the guts of
LocalCommitmentTransaction enough that we can, and do, expose its
state to the world, allowing external signers to have a basic
awareness of what they're signing.
Matt Corallo [Mon, 20 Apr 2020 02:59:53 +0000 (22:59 -0400)]
Batch-sign local HTLC txn with a well-doc'd API, returning sigs
1107ab06c33bd360bdee7ee64f4b690e753003f6 introduced an API to have a
ChannelKeys implementer sign HTLC transactions by calling into the
LocalCommitmentTransaction object, which would then store the tx.
This API was incredibly awkward, both because it required an
external signer trust our own internal interfaces, but also because
it didn't allow for any inspection of what was about to be signed.
Further, it signed the HTLC transactions one-by-one in a somewhat
inefficient way, and there isn't a clear way to resolve this (as
the which-HTLC parameter has to refer to something in between the
HTLC's arbitrary index, and its index in the commitment tx, which
has "holes" for the non-HTLC outputs and skips some HTLCs).
We replace it with a new function in ChannelKeys which allows us
to sign all HTLCs in a given commitment transaction (which allows
for a bit more effeciency on the signers' part, as well as
sidesteps the which-HTLC issue). This may also simplify the signer
implementation as we will always want to sign all HTLCs spending a
given commitment transaction at once anyway.
We also de-mut the LocalCommitmentTransaction passed to the
ChanKeys, instead opting to make LocalCommitmentTransaction const
and avoid storing any new HTLC-related data in it.
Matt Corallo [Sun, 19 Apr 2020 21:26:41 +0000 (17:26 -0400)]
Return Result<Signature> instead of modifying args in ChannelKeys
This cleans up sign_local_commitment somewhat by returning a
Result<Signaure, ()> over the local commitment transaction instead
of modifying the struct which was passed in.
This is the first step in making LocalCommitmentTransaction a
completely pub struct, using it just to communicate enough
information to the user to allow them to construct a signaure
instead of having it contain a bunch of logic.
This should make it much easier to implement a custom ChannelKeys
by disconnecting the local commitment transaction signing from our
own datastructures.
Matt Corallo [Sun, 19 Apr 2020 18:15:56 +0000 (14:15 -0400)]
Track signing of local txn in channelmonitor and refuse updates
In e46e183084ed858f41aa304acd78503aea1a96ed we began tracking
whether a local commitment transaction had been signed and
broadcast in OnchainTxHandler, refusing to update the local
commitment transaction state in the ChannelMonitor on that basis.
This is fine, except that it doesn't make a lot of sense to store
the full local transaction state in OnchainTxHandler - we should be
providing it the unsigned local transaction at the time we wish to
broadcast and no more (just like we do all other transaction data).
Antoine Riard [Tue, 21 Apr 2020 01:19:00 +0000 (21:19 -0400)]
Dry-up InputMaterial::Funding
As channel_value last usage was for computing feerate but as this
one is static per-commitment and will always-be following specification,
we remove it.
Antoine Riard [Fri, 10 Apr 2020 01:51:29 +0000 (21:51 -0400)]
Document exactly our CLTV sanitization policy for final incoming HTLCs
We want to avoid a third-party channel closure, where a random node
by sending us a payment expiring at current height, would trigger our
onchain logic to close the channel due to a near-expiration.