Commit Graph

729 Commits

Author SHA1 Message Date
Joost Jager
aa359160de
htlcswitch: return consistent failure message for internal error 2019-10-23 09:57:18 +02:00
Conner Fromknecht
dbc0e88584
Merge pull request #3564 from joostjager/htlcswitch-logging
build+htlcswitch+lnwallet: add prefix logger
2019-10-16 13:00:36 +02:00
Wilmer Paulino
4e1658a02f
htlcswitch: raise max cltv limit to 2016 blocks
The previous limit of 1008 proved to be low, given that almost 50% of
the network still advertises CLTV deltas of 144 blocks, possibly
resulting in routes with many hops failing.
2019-10-11 18:07:40 -04:00
Joost Jager
b58dbb2d70
multi: fix canceled spelling 2019-10-03 17:27:36 +02:00
Joost Jager
536dd47ce9
htlcswitch: log in lower case 2019-10-03 10:22:07 +02:00
Joost Jager
654b3cc718
htlcswitch: use prefix logger for remaining log statements in link 2019-10-03 10:22:05 +02:00
Joost Jager
03ed1b0aa3
htlcswitch: use prefix logger in link 2019-10-03 10:22:03 +02:00
Joost Jager
426ee28895
htlcswitch/test: move test functions into context 2019-09-26 15:11:23 +02:00
Joost Jager
23617bb9fd
htlcswitch/test: move test code 2019-09-26 15:11:21 +02:00
Olaoluwa Osuntokun
3f8526a0ca
peer+lnpeer: add new methods to expose local+global features for lnpeer interface 2019-09-25 18:26:01 -07:00
Olaoluwa Osuntokun
4b65aea306
watchtower+htlcswitch: update client tower logic to recognize safu commitments
In this commit, we update the tower+link logic to tag a commitment as
the new (tweakless) format if it applies. In order to do this, the
BackupTask method has gained an additional parameter to indicate the
type of commitment that we're attempting to upload. This new tweakless
bool is then threaded through all the way to back up task creation to
ensure that we make the proper input.Input.

Finally, we've added a new test case for each existing test case to test
each case w/ and w/o the tweakless modifier.
2019-09-25 18:25:55 -07:00
Olaoluwa Osuntokun
0b62126067
multi: update funding workflow to be aware of new tweakless commits
In this commit, we update the funding workflow to be aware of the new
channel type that doesn't tweak the remote party's output within the
non-delay script on their commitment transaction. To do this, we now
allow the caller of `InnitChannelReservation` to signal if they want the
old or new (tweakless) commitment style.

The funding tests are also updated to test both funding variants, as
we'll still need to understand the legacy format for older nodes.
2019-09-25 18:25:46 -07:00
Olaoluwa Osuntokun
b399203e71
lnwallet: update channel state machine to be aware of tweakless commits
In this commit, we update the channel state machine to be aware of
tweakless commits. In several areas, we'll now check the channel's type
to see if it's `SingleFunderTweakless`. If so, then we'll opt to use the
remote party's non-delay based point directly in the script, skipping
any additional cryptographic operations. Along the way we move the
`validateCommitmentSanity` method to be defined _before_ it's used as is
cutomary within the codebase.

Notably, within the `NewUnilateralCloseSummary` method, we'll now _blank
out_ the `SingleTweak` value if the commitment is tweakless. This
indicates to callers the witness type they should map to, as the value
isn't needed at all any longer when sweeping a non-delay output.

We also update the signing+verification tests to also test that we're
able to properly generate a valid witness for the new tweakless
commitment format.
2019-09-25 18:25:43 -07:00
Johan T. Halseth
2d194c9672
htlcswitch/link: remove chan sync delay
Earlier this delay was needed to increase the likelihood that the DLP
scanario was successfully completed. Since we would risk the connection
being torn down, and the link exit, we could end up with the remote
marking the channel borked, but not finishing the force close.

With the previous set of commits, we should now trigger the force close
before we merk the channel borked, which should ensure we'll resume the
orocess on next restart/connect.
2019-09-25 14:04:44 +02:00
Johan T. Halseth
2a6ad6e634
channeldb+lnwallet: don't pass isRestoredChan to ChanSyncMsg
Since we have access to the internal state of the channel, we can
instead get it directly instead of passing it in as a parameter.
2019-09-25 14:04:44 +02:00
Johan T. Halseth
9423fadf56
htlcswitch/link: don't mark channel borked on force close scanarios
Instead of marking the channel Borked in cases where we want to force
close it, we immediately let the peer fail the link. The channel state
will instead be updated by the channel arbitrator, which will transition
to StateBroadcastCommit, marking the channel borked, then marking the
commitment tx broadcasted right before publishing the force close tx. We
do this to avoid the case where we would mark it Borked, but go down
before being able to publish the closing tx.

Storing the force close tx ensures it will be re-published on startup.
2019-09-25 14:04:44 +02:00
Johan T. Halseth
6e361d04cf
lnwallet+link: move marking channel states to link
Instead of marking the database state when processing the channel
reestablishment message, we wait for the result of this processing to
arrive in the link, and mark it accordingly in the database here.

We do this move the logic determining whether we should force close the
channel or not, and what state to mark it in the DB, to the same place,
as these need to be consistent.
2019-09-25 14:04:43 +02:00
Johan T. Halseth
f40f4620f7
lnwallet/channel: make ErrCommitSyncLocalDataLoss type
This commit converts the ErrCommitSyncLocalDataLoss error into a struct,
that also holds the received last unrevoked commit point from the remote
party.
2019-09-25 14:04:43 +02:00
Johan T. Halseth
eb1b84c0b4
channeldb+lnwallet: make ChanSyncMsg method on OpenChannel 2019-09-25 14:04:42 +02:00
Olaoluwa Osuntokun
9b1ecbd3fa
Merge pull request #2485 from halseth/error-codes-dont-send
[lnwire+funding] Don't send ErrorCode on wire
2019-09-23 17:50:27 -07:00
Valentine Wallace
9a52cb6dab
multi: update internals to support updating max htlc
In this commit, we update the router and link to support users
updating the max HTLC policy for their channels. By updating these internal
systems before updating the RPC server and lncli, we protect users from
being shown an option that doesn't actually work.
2019-09-23 13:07:10 +02:00
Joost Jager
c80feeb4b3
routing+discovery: extract local channel manager
The policy update logic that resided part in the gossiper and
part in the rpc server is extracted into its own object.

This prepares for additional validation logic to be added for policy
updates that would otherwise make the gossiper heavier.

It is also a small first step towards separation of our own channel data
from the rest of the graph.
2019-09-23 13:07:08 +02:00
Johan T. Halseth
33fe09482b
lnwire+multi: define Error() for lnwire.Error
To make lnwire.Error actually satisfy the error interface, define the
Error method directly.
2019-09-20 10:55:21 +02:00
Conner Fromknecht
3276bf2960
htlcswitch/link: remove channel reestablish deadline
Now that the link will remain ineligible until it receives
channel_reestablish from the remote peer, we can remove the channel
reestablish timeout entirely.
2019-09-19 12:47:08 -07:00
Conner Fromknecht
9d6ee2ebd9
htlcswitch/link: restrict EligibleToForward to wait for reestablish
This commit modifies the link's EligibleToForward() method only return
true once the peers have successfully exchanged channel reestablish
messages. This is a preliminary step to increasing the reestablish
timeout, ensuring the switch won't try to forward over links while
we're waiting for the remote peer to resume the connection.
2019-09-19 12:46:56 -07:00
Conner Fromknecht
6dca07577d
multi: move active/inactive ntfns from switch to link
Since we will now wait to deliver the event after channel reestablish,
notifying when the link is added to the switch will no longer be
sufficient. Later, we will add receiving reestablish as an additional
requirement for EligibleToForward returning true.

The inactive ntfn is also moved, to ensure that we don't fire inactive
notifications if no corresponding active notification was sent.
2019-09-19 12:46:44 -07:00
Joost Jager
f60e4b1e14
lnwire+htlcswitch: report height for invalid payment details failure
Extends the invalid payment details failure with the new accept height
field. This allows sender to distinguish between a genuine invalid
details situation and a delay caused by intermediate nodes.
2019-09-16 10:10:20 +02:00
Joost Jager
4e140213f9
htlcswitch+invoices: circuit key based hodl notifications
This commit modifies hodl htlc notification from invoice registry from a
single notification per hash to distinct notifications per htlc. This
prepares for htlc-specific information (accept height) to be added to the
notification.
2019-09-16 10:10:14 +02:00
Conner Fromknecht
72c5d11a1c
Merge pull request #3502 from joostjager/err-returns
multi: fix dropped errors
2019-09-13 11:24:04 -07:00
Joost Jager
1e0ed1e52f
multi: fix dropped errors 2019-09-13 09:50:38 +02:00
Lars Lehtonen
3b29ecb921 routing: Fix dropped errors in tests.
lnd: Fix dropped errors in tests.

contractcourt: Fix dropped errors in tests.

htlcswitch: Fix dropped errors in tests.

invoices: Fix dropped error in tests.

lnwallet: Fix dropped errors in tests.

macaroons: Fix dropped error in tests.
2019-09-13 06:28:05 +00:00
Conner Fromknecht
2c3ce2a183
Merge pull request #3484 from joostjager/fix-hop-log
htlcswitch/hop: fix logging
2019-09-11 13:37:43 -07:00
Joost Jager
3d7de2ad39
multi: remove dead code 2019-09-10 17:21:59 +02:00
Valentine Wallace
8ce7f82da0 discovery+switch: apply zero forwarding policy updates in-memory as well as on disk
In this commit, we fix a bug where if a user updates a forwarding policy to be
zero, the update will be applied to the policy correctly on-disk, but not
in-memory.

We solve this issue by having the gossiper return the list of on-disk updated
policies and passing these policies to the switch, so the switch can assume
that zero-valued fields are intentional and not just uninitialized.
2019-09-09 23:39:44 -07:00
Olaoluwa Osuntokun
2cf10ada0f
Merge pull request #3465 from cfromknecht/tlv-parsed-types
tlv+htlcswitch: validate presence/omission of parsed onion payload types
2019-09-09 05:42:03 -07:00
Joost Jager
3a2ca434fe htlcswitch/hop: fix logging
Logging for the hop package is controlled via the parent htlcswitch
package. Unfortunately the parent package only controlled the
initialization, but didn't enable the logger when the log level came
in from the main lnd package.
2019-09-09 13:52:35 +02:00
Conner Fromknecht
6015567927
htlcswitch/iterator: validate presence/omission of payload types
From BOLT 04:

The writer:
 - MUST include amt_to_forward and outgoing_cltv_value for every node.
 - MUST include short_channel_id for every non-final node.
 - MUST NOT include short_channel_id for the final node.
2019-09-05 09:32:03 -07:00
Conner Fromknecht
aefec9b10f
tlv: return parsed types from DecodeWithParsedTypes
This commit adds an additional return value to
Stream.DecodeWithParsedTypes, which returns the set of types that were
encountered during decoding. The set will contain all known types that
were decoded, as well as unknown odd types that were ignored.

The rationale for the return value (rather than an internal member) is
so that the stream remains stateless.

This return value can be used by callers during decoding to make
assertions as to whether specific types were included in the stream.
This is need, for example, when parsing onion payloads where certain
fields must be included/omitted depending on the hop type.

The original Decode method would incur the additional performance hit of
needing to track the parsed types, so we can selectively enable this
functionality when a decoder requires it by using a helper which
conditionally tracks the parsed types.
2019-09-05 09:30:37 -07:00
Joost Jager
e54b24289f
htlcswitch: move hop iterator into htlcswitch/hop package
Prepares for onion blob decoding outside of htlcswitch.
2019-09-05 15:30:31 +02:00
Conner Fromknecht
138b0798f5
htlcswitch/iterator: use hop.Payload constructors 2019-09-05 01:35:24 -07:00
Conner Fromknecht
378e0558c5
htlcswitch/hop: move hop.Exit and hop.Source to hop pkg 2019-09-05 01:35:23 -07:00
Conner Fromknecht
fc0e4be4d8
htlcswitch+hop: move ForwardingInfo to hop.ForwaringInfo 2019-09-05 01:35:23 -07:00
Conner Fromknecht
83d2112e8b
htlcswitch/hop: move NetworkHop to hop.Network 2019-09-05 01:35:20 -07:00
Olaoluwa Osuntokun
866867a4b0
Merge pull request #3401 from wpaulino/channel-initiator-max-fee
htlcswitch: avoid proposing fee updates exceeding max fee allowed
2019-09-04 20:38:52 -07:00
Olaoluwa Osuntokun
00682584aa
Merge pull request #3441 from cfromknecht/truncated-sid
htlcswitch+routing: omit next_hop_id in final hop payload
2019-09-04 19:55:38 -07:00
Olaoluwa Osuntokun
7eca7b02a6
Merge pull request #3390 from joostjager/invoice-circuits
channeldb+cnct+invoices: track invoice htlcs
2019-09-04 19:51:37 -07:00
Conner Fromknecht
dc0f429271
htlcswitch+routing: use TLV hop constructors 2019-09-04 12:05:09 -07:00
Joost Jager
c1345a4117
multi: use separate cltv expiry field from invoice
Now that the Invoice struct contains the decoded final cltv delta value,
the decoding of payment requests can be removed from the invoice
registry.
2019-09-04 19:20:19 +02:00
Joost Jager
05e6b62cb2
cnct+htlcswitch+invoices: report circuit key to invoice registry
Currently the invoice registry cannot tell apart the htlcs that pay to
an invoice. Because htlcs may also be replayed on startup, it isn't
possible to determine the total amount paid to an invoice.

This commit is a first step towards fixing that. It reports the circuit
keys of htlcs to the invoice registry, which forms the basis for
accurate invoice accounting.
2019-09-04 19:20:13 +02:00
Wilmer Paulino
d8dd6b3245
htlcswitch: cap fee updates to max fee allocation
In this commit, we begin to enforce a maximum channel commitment fee for
channel initiators when attempting to update their commitment fee. Now,
if the new commitment fee happens to exceed their maximum, then a fee
update of the maximum fee allocation will be proposed instead if needed.

A default of up to 50% of the channel initiator's balance is enforced
for the maximum channel commitment fee. It can be modified through the
`--max-channel-fee-allocation` CLI flag.
2019-09-03 16:49:59 -07:00
Wilmer Paulino
047d5b173c
htlcswitch: refactor TestChannelLinkUpdateCommitFee common code into closure 2019-09-03 16:49:56 -07:00
Johan T. Halseth
9ef66f568f
Merge pull request #2203 from ccdle12/reject-htlc-option
htlcswitch+config+server: adding RejectHTLC flag
2019-08-26 14:53:32 +02:00
Olaoluwa Osuntokun
23cc8389f2
multi: add TLV awareness to htlcswitch, pass extra EOB to the invoice registry
In this commit, we update the `HopIterator` to gain awareness of the new
TLV hop payload. The default `HopIterator` will now hide the details of
the TLV from the caller, and return the same `ForwardingInfo` struct in
a uniform manner. We also add a new method: `ExtraOnionBlob` to allow
the caller to obtain the raw EOB (the serialized TLV stream) to pass
around.

Within the link, we'll now pass the EOB information into the invoice
registry. This allows the registry to parse out any additional
information from the EOB that it needs to settle the payment, such as a
preimage shard in the AMP case.
2019-08-22 18:53:05 -07:00
Olaoluwa Osuntokun
2f8d3c4526
Merge pull request #3256 from joostjager/failure-attribution
routing: failure attribution
2019-08-20 16:53:56 -07:00
ccdle12
05d0d028bc
htlcswitch+config+server: Adds a rejecthtlc flag that disables forwarded
htlcs

config: Adding RejectHTLC field in config struct

This commit adds a RejectHTLC field in the config struct in config.go.
This allows the user to run lnd as a node that does not accept onward
HTLCs.

htlcswitch/switch: Adding a field RejectHTLC to the switch config

This commit adds a field RejectHTLC to the switch config. When the
switch receives an HTLC it will check this flag and if the HTLC is not
from the source hop, the HTLC will be rejected.

htlcswitch/switch: adding check for RejectHTLC flag and incomingChanID

This commit adds a check when receiving UpdateAddHTLC. The check looks
for the RejectHTLC flag set and whether the HTLC is from the sourceHop
(the local switch). If the HTLC is not from the sourceHop, then we
reject the HTLC and return a FailChannelDisabled error.

server: adding RejectHTLC field to initialization of switch

lnd_test: adding test for RejectHTLC

This commit adds a test which tests that a node with the --rejecthtlc
flag will reject any onward HTLCs but still can receive direct HTLCs and
can send HTLCs.
2019-08-20 11:01:44 +01:00
Joost Jager
67e40d4433
htlcswitch: always assume an onion error for malformed htlc failures
Previously a temporary channel failure was returning for unexpected
malformed htlc failures. This is not what we want to communicate to the
sender, because the sender may apply a penalty to us only.

Returning the temporary channel failure is especially problematic if we
ourselves are the sender and the malformed htlc failure comes from our
direct peer. When interpretating the failure, we aren't able to
distinguish anymore between our channel not having enough balance and
our peer sending an unexpected failure back.
2019-08-17 10:24:05 +02:00
Joost Jager
4dd054ae90
multi: remove debug invoices
Debug invoices are rarely used nowadays, but keep asking for maintenance
every time refactoring in primarily the invoice registry occurs. We have
passed the cost/benefit tipping point, so therefore the debug invoice
concept is removed in this commit.

Previously the debughtlc flag also controlled whether hodl masks were
active. It is safe to remove that additional condition because the hodl
masks are still guarded by the dev build tag.
2019-08-14 21:33:03 +02:00
Conner Fromknecht
9a5ac78912
Merge pull request #3391 from joostjager/always-return-invalid-details
htlcswitch+invoices: always return incorrect_or_unknown_payment_details
2019-08-12 20:14:49 -07:00
Joost Jager
98fac9fb99
htlcswitch+invoices: always return incorrect_or_unknown_payment_details
In order to prevent information leaks by nodes probing with a payment
hash, this commit changes exit hop processing so that it always returns
incorrect_or_unknown_payment_details and leaves the prober in the dark
about whether an invoice actually exists.
2019-08-08 11:04:23 +02:00
Joost Jager
922f133fd2
htlcswitch: report incoming htlc time lock with FinalIncorrectCltvExpiry
Previously the time lock in the onion payload was reported. This is no
new information to the sender.
2019-08-08 11:04:21 +02:00
Joost Jager
45b3c647f7
htlcswitch: return final_incorrect_htlc_amount on onion payload mismatch
This commit fixes exit hop behavior to be in line with the lightning
spec.
2019-08-08 11:04:19 +02:00
Joost Jager
aabd68ebcd
multi: rename FailUnknownPaymentHash to FailIncorrectDetails
Align naming better with the lightning spec. Not the full name of the
failure (FailIncorrectOrUnknownPaymentDetails) is used, because this
would cause too many long lines in the code.
2019-08-08 11:04:17 +02:00
Joost Jager
8681729561
htlcswitch/test: extract failure code assertion to function 2019-08-08 11:04:15 +02:00
Johan T. Halseth
21baa7bf18
multi: fix linter errors 2019-08-07 10:53:10 +02:00
Wilmer Paulino
24ca962f75
htlcswitch: lower max outgoing cltv expiry to one week worth of blocks
The current value was based on the previous default CLTV delta of 144
blocks. This has been lowered to 40 since lnd v0.6.0-beta, making the
current value of 5000 blocks a bit high. Lowering it to one week should
be more than enough to account for the other major lightning
implementations. Eclair currently has a default CLTV delta of 144, while
c-lightning's is 14.
2019-07-26 18:06:40 -07:00
Wilmer Paulino
87ff463abd
htlcswitch+lnd: make max cltv expiry configurable 2019-07-26 18:05:58 -07:00
nsa
00814dc7c1 htlcswitch: pipeline settles to switch
This commit makes the outgoing link pipeline the settle to the
switch as soon as it receives it. Previously, it would wait for a
revocation before sending it, which caused increased latency on
payments as well as possibly never settling on the incoming link.
A duplicate settle is still sent to the switch, but it is handled
gracefully. A new AckEventTicker was added to the switch which
acknowledges any pending settle / fail entries in an outgoing
link's fwd pkgs in batch. This was needed in order to reduce the
number of db txn's which would have been incurred by acking whenever
we receive a duplicate settle without batching.
2019-07-18 17:20:40 -04:00
Joost Jager
2726f50d7c
htlcswitch: do not consider unknown failures an error 2019-07-11 19:49:49 +02:00
Joost Jager
c6f9517e48
lnwire+htlcswitch: only use references for failure messages
Methods on failure message types used to be defined on value receivers.
This allowed assignment of a failure message to ForwardingError both as
a value and as a pointer. This is error-prone, especially when using a
type switch.

In this commit the failure message methods are changed so that they
target pointer receivers.

Two instances where a value was assigned instead of a reference are
fixed.
2019-07-11 19:49:47 +02:00
Joost Jager
418fe364de
htlcswitch: use distinct error for unreadable failures 2019-07-11 19:49:45 +02:00
Joost Jager
0cdae56d28
htlcswitch+routing: make error decryption mockable 2019-07-11 10:37:28 +02:00
Joost Jager
2b47632b26
htlcswitch+routing+routerrpc: return error source as index 2019-07-11 10:37:26 +02:00
Joost Jager
55bef96cf3
htlcswitch/test: stricter error check in TestSwitchSendPayment 2019-07-11 10:37:24 +02:00
Conner Fromknecht
933e723ec7
Merge pull request #3178 from federicobond/once-refactor
multi: replace manual CAS with sync.Once in several more modules
2019-07-08 20:33:44 -07:00
Conner Fromknecht
851c070595
htlcswitch/link: fix Min/MaxFeeUpdateTimeout godocs 2019-06-13 19:54:18 -07:00
Conner Fromknecht
c41017610b
htlcswitch/link: backup revoked states to watchtower 2019-06-13 19:54:18 -07:00
Conner Fromknecht
7566b26e03
htlcswitch/interface: add TowerClient iface 2019-06-13 19:54:17 -07:00
Federico Bond
0a9141763e multi: replace manual CAS with sync.Once in several more modules 2019-06-12 09:37:26 -03:00
Johan T. Halseth
dd88015985
htlcswitch/switch test: add TestSwitchGetPaymentResult
TestSwitchGetPaymentResult tests that the switch interacts as expected
with the circuit map and network result store when looking up the result
of a payment ID. This is important for not to lose results under
concurrent lookup and receiving results.
2019-06-07 16:53:33 +02:00
Johan T. Halseth
dd3abbc4ef
htlcswitch/payment_result_test: add TestNetworkResultStore
TestNetworkResultStore tests that the networkResult store behaves as
expected, and that we can store, get and subscribe to results.
2019-06-07 16:53:33 +02:00
Johan T. Halseth
2cc778d309
htlcswitch/switch: use paymentResultStore to keep track of results 2019-06-07 16:53:32 +02:00
Johan T. Halseth
2dea790b55
multi: make GetPaymentResult take payment hash
Used for logging in the switch, and when we remove the pending payments,
only the router will have the hash stored across restarts.
2019-06-07 16:53:32 +02:00
Johan T. Halseth
1febe1a6d5
htlcswitch/payment_result: add paymentResultStore
paymentResultStore is a persistent store where we keep track of all
received payment results. This is used to ensure we don't lose results
from payment attempts on restarts.
2019-06-07 16:53:32 +02:00
Johan T. Halseth
df3f5d02ad
htlcswitch/payment_result: add (de)serialization of networkResult + test 2019-06-07 16:53:32 +02:00
Johan T. Halseth
f5dee02ff4
htlcswitch/mock: set SelfKey and mock ErrorSource 2019-06-07 16:42:25 +02:00
Olaoluwa Osuntokun
19fafd7a9a
Merge pull request #2761 from halseth/reliable-payments-router-state-machine
[reliable payments] router payment state machine
2019-05-27 16:46:19 -07:00
Olaoluwa Osuntokun
5f0fad85be multi: address lingering TODO by no longer wiping out local HTLCs on remote close
In this commit, we fix a lingering TOOD statement in the channel arb.
Before this commitment, we would simply wipe our our local HTLC set of
the HTLC set that was on the remote commitment transaction on force
close. This was incorrect as if our commitment transaction had an HTLC
that the remote commitment didn't, then we would fail to cancel that
back, and cause both channels to time out on chain.

In order to remedy this, we introduce a new `HtlcSetKey` struct to track
all 3 possible in-flight set of HTLCs: ours, theirs, and their pending.

We also we start to tack on additional data to all the unilateral close
messages we send to subscribers. This new data is the CommitSet, or the
set of valid commitments at channel closure time. This new information
will be used by the channel arb in an upcoming commit to ensure it will
cancel back HTLCs in the case of split commitment state.

Finally, we start to thread through an optional *CommitSet to the
advanceState method. This additional information will give the channel
arb addition information it needs to ensure it properly cancels back
HTLCs that are about to time out or may time out depending on which
commitment is played.

Within the htlcswitch pakage, we modify the `SignNextCommitment` method
to return the new set of pending HTLCs for the remote party's commitment
transaction and `ReceiveRevocation` to return the latest set of
commitment transactions on the remote party's commitment as well. This
is a preparatory change which is part of a larger change to address a
lingering TODO in the cnct.

Additionally, rather than just send of the set of HTLCs after the we
revoke, we'll also send of the set of HTLCs after the remote party
revokes, and we create a pending commitment state for it.
2019-05-27 14:34:13 -07:00
Johan T. Halseth
d027e10201
htlcswitch+channeldb: move control tower to channeldb 2019-05-27 20:18:56 +02:00
Johan T. Halseth
cd02c22977
htlcswitch+router: move deobfuscator creation to GetPaymentResult call
In this commit we move handing the deobfuscator from the router to the
switch from when the payment is initiated, to when the result is
queried.

We do this because only the router can recreate the deobfuscator after a
restart, and we are preparing for being able to handle results across
restarts.

Since the deobfuscator cannot be nil anymore, we can also get rid of
that special case.
2019-05-16 23:56:12 +02:00
Johan T. Halseth
f99d0c4c68
htlcswitch/switch+payment_result: define networkResult, extractResult 2019-05-16 23:56:12 +02:00
Johan T. Halseth
ec087a9f73
htlcswitch+router: define PaymentResult, GetPaymentResult
This lets us distinguish an critical error from a actual payment result
(success or failure). This is important since we know that we can only
attempt another payment when a final result from the previous payment
attempt is received.
2019-05-16 23:56:12 +02:00
Johan T. Halseth
be129eb7c7
htlcswitch/switch: remove numPendingPayments only used in tests 2019-05-16 23:56:12 +02:00
Johan T. Halseth
cff4d3547d
htlcswitch/switch: clarify paymentID uniqueness
With the following commits, it'll become important to not resuse
paymentIDs, since there is no way to tell whether the HTLC in question
has already been forwarded and settled/failed.

We clarify this in the SendHTLC comments, and alter the tests to not
attempt to resend an HTLC with a duplicate payment ID.
2019-05-16 23:56:11 +02:00
Johan T. Halseth
bbbe3a37f5
htlcswitch/switch: make parseFailedPayment not dependent on pkt
We will later persist the fields necessary to decrypt a received error.
2019-05-16 23:56:11 +02:00
Johan T. Halseth
c9e8ff6a34
switch+router+server: move NextPaymentID to router
This commit moves the responsibility of generating a unique payment ID
from the switch to the router. This will make it easier for the router
to keep track of which HTLCs were successfully forwarded onto the
network, as it can query the switch for existing HTLCs as long as the
paymentIDs are kept.

The router is expected to maintain a map from paymentHash->paymentID,
such that they can be replayed on restart. This also lets the router
check the status of a sent payment after a restart, by querying the
switch for the paymentID in question.
2019-05-16 23:56:06 +02:00
Joost Jager
570f9ca57e
htlcswitch/test: hodl invoice restart test
This commit adds a test that covers the hodl invoice behaviour after a
link restart.
2019-05-15 14:42:24 +02:00
Joost Jager
e5ead599cc
htlcswitch/test: use single channel restore function
This commit refactors test code around channel restoration in unit
tests to make it easier to use.
2019-05-15 14:42:21 +02:00
Joost Jager
064e8492de
cnct+htlcswitch+invoices: move invoice parameter check out of link
This commit is the final step in making the link unaware of invoices. It
now purely offers the htlc to the invoice registry and follows
instructions from the invoice registry about how and when to respond to
the htlc.

The change also fixes a bug where upon restart, hodl htlcs were
subjected to the invoice minimum cltv delta requirement again. If the
block height has increased in the mean while, the htlc would be canceled
back.

Furthermore the invoice registry interaction is aligned between link and
contract resolvers.
2019-05-15 14:42:12 +02:00
Joost Jager
d55a8b7b29
channel+cnct: remove preimage from channel and resolution
Now that the success resolver preimage field is always populated by the
incoming contest resolver, preimage lookups earlier in the
process (channel and channel arbitrator) can mostly be removed.
2019-05-15 14:41:49 +02:00
Olaoluwa Osuntokun
a8fa4094ba
Merge pull request #3027 from Roasbeef/new-onion-structs
router+build: update to the latest version of lightning-onion
2019-05-03 13:30:41 -07:00
Joost Jager
f5f6a52ed8
htlcswitch: check channel policy for local htlcs 2019-05-03 12:22:36 +02:00
Joost Jager
e571532d9a
htlcswitch: reorder policy checks
This commit reorders the policies check as a preparation for splitting
the checks in separate sets for the incoming and outgoing htlc.
2019-05-03 12:22:33 +02:00
Olaoluwa Osuntokun
56c969c911
htlcswitch: add new TestUpdateFailMalformedHTLCErrorConversion test
In this commit, we add a new test to ensure that we're able to properly
convert malformed HTLC errors that are sourced from multiple hops away,
or our direct channel peers. In order to test this effectively, we force
the onion decryptors of various peers to always fail which will trigger
the malformed HTLC logic.
2019-04-30 20:13:38 -07:00
Olaoluwa Osuntokun
be63c7d286
htlcswitch: properly convert multi-hop malformed HTLC failures
In this commit, we now properly convert multi-hop malformed HTLC
failures. Before this commit, we wouldn't properly add a layer of
encryption to these errors meaning that the destination would fail to
decrypt the error as it was actually plaintext.

To remedy this, we'll now check if we need to convert an error, and if
so we'll encrypt it as if it we were the source of the error (the true
source is our direct channel peer).
2019-04-30 20:13:37 -07:00
Olaoluwa Osuntokun
cdc4aca40f
htlcswitch: properly handle direct link malformed HTLC failures
In this commit, we fix a bug that caused us to be unable to properly
handle malformed HTLC failures from our direct link. Before this commit,
we would attempt to decrypt it and fail since it wasn't well formed. In
this commit, if its an error for a local payment, and it needed to be
converted, then we'll decode it w/o decrypting since it's already
plaintext.
2019-04-30 20:13:36 -07:00
Olaoluwa Osuntokun
c67ca0a329
htlcswitch: add new EncryptMalformedError method to ErrorEncrypter
In this commit, we add a new method to the ErrorEncrypter interface:
`EncryptMalformedError`. This takes a raw error (no encryption or MAC),
and encrypts it as if we were the originator of this error. This will be
used by the switch to convert malformed fail errors to regular fully
encrypted errors.
2019-04-30 20:13:35 -07:00
Olaoluwa Osuntokun
649e080da6
htlcswitch: for UpdateFailMalformedHTLC packets mark fail as needing conversion
In this commit, we start the first phase of fixing an existing bug
within the switch. As is, we don't properly convert
`UpdateFailMalformedHTLC` to regular `UpdateFailHTLC` messages that are
fully encrypted. When we receive a `UpdateFailMalformedHTLC` today,
we'll convert it into a regular fail message by simply encoding the
failure message raw. This failure message doesn't have  a MAC yet, so if
we sent it backwards, then the destination wouldn't be able to decrypt
it. We can recognize this type of failure as it'll be the same size as
the raw failure message max size, but it has 4 extra bytes for the
encoding. When we come across this message, we'll mark is as needing
conversion so the switch can take care of it.
2019-04-30 20:13:34 -07:00
Olaoluwa Osuntokun
8418dc5530
Merge pull request #2939 from Roasbeef/hodl-htlc-fix
htlcswitch: only perform CLTV checks for HTLCs with open invoices
2019-04-15 12:52:45 -07:00
Joost Jager
40cea6b487
htlcswitch/test: increase test timeout for hodl invoice tests 2019-04-12 09:01:05 +02:00
Olaoluwa Osuntokun
5d68f0f9eb
htlcswitch: only perform CLTV checks for HTLCs with open invoices
In this commit, we fix a bug that would cause a node with a hodl HTLC to
cancel back the HTLC upon restart if the invoice has been settled, but
the HTLC is still present on the commitment transaction. A fix for the
HTLC still being present (not triggering a new commitment) has been
fixed recently. However, for older nodes with a lingering HTLC, on
restart it would be failed back.

In this commit, we make the check stricter by only performing these
checks for HTLCs that are in the open state. This ensures that we'll
only check this constraints the first time around, before the HTLC has
been transitioned to the accepted state.
2019-04-11 17:53:25 -07:00
Conner Fromknecht
057bed2b92
htlcswitch/link: delay restored channel reestablish
This commit adds a brief delay when sending our channel reestablish
message if the link contains a restored channel to ensure we first have
a stable connection. Sending the message will cause the remote peer to
force close the channel, which currently may not be resumed reliably if
the connection is being torn town simultaneously. This delay can be
removed after the force close is reliable, but in the meantime it
improves the reliability of successfully closing out the channel and
allows the `channel_backup_restore/restore_during_creation` to pass
reliably.
2019-04-11 15:42:02 -07:00
Olaoluwa Osuntokun
bc425b1a77
Merge pull request #2918 from joostjager/hodl-drop-fix
htlcswitch: ensure commit tx gets updated after settle hodl invoice
2019-04-11 15:38:56 -07:00
Olaoluwa Osuntokun
5ac9ba6472
htlcswitch: synchronously send the chan sync message to the remote peer
In this commit, we modify the starting link logic to always send the
chan sync message to the remote peer in a synchronous manner. Otherwise,
it's possible that we fail very quickly below this block, and don't ever
send the message to the remote peer.
2019-04-10 18:01:52 -07:00
Joost Jager
72c86fbf5d
htlcswitch/test: test revocation window exhaustion 2019-04-10 21:30:31 +02:00
Joost Jager
6d2dfed03d
htlcswitch: increase batch counter for exit hop settle and fail
The idea of the batch counter is to increase it for commit tx updates,
so that if the commit tx cannot be updated immediately (revocation
window exhausted), the batch ticker makes sure it happens later.

The batch counter was increased for forwarded htlcs, but not for exit hop
resolutions.

This lead to the situation where the commitment tx would not be updated,
even though the htlc was settled locally. When no other changes happen
on the channel, the htlc eventually reaches its expiry and the channel
is force closed.
2019-04-10 21:04:51 +02:00
Joost Jager
038ce342b3
htlcswitch: do not check final cltv for accepted invoices 2019-04-08 18:16:21 +02:00
Joost Jager
206d93d856
htlcswitch/test: test zero value for outbound cltv reject delta 2019-04-05 11:36:18 +02:00
Joost Jager
1b2816006f
htlcswitch/test: align test invoice cltv expiry 2019-04-05 11:36:16 +02:00
Joost Jager
af7d0e5ff5
htlcswitch/test: convert TestChannelLinkSingleHopPayment to two hop network 2019-04-05 11:36:13 +02:00
Joost Jager
037913fd28
link: rewrite height comparisons without subtraction
Prevent the case where a uint32 wrap around could happen.
2019-04-05 11:36:10 +02:00
Joost Jager
ab4da0f53d
cnct: define separate broadcast delta for outgoing htlcs
This commits exposes the various parameters around going to chain and
accepting htlcs in a clear way.

In addition to this, it reverts those parameters to what they were
before the merge of commit d107627145.
2019-04-05 11:36:07 +02:00
Olaoluwa Osuntokun
893cff60c4
Merge pull request #2839 from joostjager/htlc-expiry-check
link: increase expiry grace delta for exit hop and forwarded htlcs
2019-04-01 18:15:56 -07:00
Olaoluwa Osuntokun
1afec1342b
htlcswitch: update syncChanStates for new ChanSyncMsg API 2019-03-28 17:53:56 -07:00
Johan T. Halseth
59e3390f6c
Merge pull request #2750 from cryptagoras/patch-1
htlcswitch/switch: log target node on insufficient cap error
2019-03-27 15:10:08 +01:00
Joost Jager
cd535b9401
link: increase expiry grace delta
This commit increase the expiry grace delta to a value above the
broadcast delta. This prevents htlcs from being accepted that would
immediately trigger a channel force close.

A correct delta is generated in server.go where there is access to
the broadcast delta and passed via the peer to the links.

Co-authored-by: Jim Posen <jim.posen@gmail.com>
2019-03-26 18:42:00 +01:00
Joost Jager
e6fbbaa1dc
link: also check expiry grace delta for forwarded htlcs
Previously there was no minimum remaining blocks requirement on
forwarded htlcs, which may cause channel arbitrator to force
close the channel directly after forwarding the htlc.

Co-authored-by: Jim Posen <jim.posen@gmail.com>
2019-03-26 18:41:41 +01:00
cryptagoras
a50428ca96 htlcswitch/switch: log target node on insufficient cap error 2019-03-25 18:25:58 +02:00
Joost Jager
0823c79e4e
htlcswitch/test: hodl invoice test 2019-03-15 10:09:20 +01:00
Joost Jager
32f2b047e8
htlcswitch: hodl invoice
This commit modifies the invoice registry to handle invoices for which
the preimage is not known yet (hodl invoices). In that case, the
resolution channel passed in from links and resolvers is stored until we
either learn the preimage or want to cancel the htlc.
2019-03-15 10:09:17 +01:00
Joost Jager
1f41a2abce
htlcswitch: abtract invoice from link
This commit detaches signaling the invoice registry that an htlc was
locked in from the actually settling of the htlc.

It is a preparation for hodl invoices.
2019-03-15 10:09:15 +01:00
Joost Jager
aeb35d9898
htlcswitch/test: use real invoice registry with temp db as mock
In further commits the behaviour of invoice registry becomes more
intrinsically connected to the link. This commit prepares for that by
allowing link and registry to be tested as a single unit.
2019-03-15 10:09:12 +01:00
Joost Jager
e464ed18c7
htlcswitch/test: make unknown hash test independent of mock
In the TestChannelLinkMultiHopUnknownPaymentHash test, a preimage was
modified to trigger an unknown payment hash failure. The way the mock is
implemented, it would take the hash of that modified preimage and store
it. It basically stores a completely different invoice. For this test,
it is just as good to store no invoice at all.
2019-03-15 10:09:09 +01:00
Joost Jager
c23bb5b3f1
htlcswitch: extract settle invoice into method 2019-03-15 10:09:03 +01:00
Joost Jager
19f79613df
channeldb: store hold invoice 2019-03-15 10:08:55 +01:00
Joost Jager
4141773e90
htlcswitch: resolve invoice cancelation race condition
Previously it could happen that an invoice was open at the time of the
LookupInvoice call, the htlc was settled because of that, but when the
SettleInvoice call was made eventually, it would fail because the
invoice was canceled in the mean time. The htlc would then be settled,
but the invoice not marked as such.
2019-03-15 10:08:46 +01:00
Joost Jager
eb598ec7a4
htlcswitch: extract exit hop processing to method 2019-03-15 10:08:43 +01:00
Joost Jager
9643b45dbc
htlcswitch/test: move preimage cache to server level
In this commit the preimage cache is instantiated on the mock server
level where it belongs. Previously it was a cache shared across all mock
servers.
2019-03-15 10:08:40 +01:00
Conner Fromknecht
f39edd8000
peer: add SendMessageLazy 2019-03-05 17:08:22 -08:00
Valentine Wallace
f0e668974e htlcswitch/link: verify an htlc is not too large in HtlcSatifiesPolicy
Before forwarding an HTLC, ensure that the amount to forward
including fees does not exceed the max HTLC set for the channel
link.
2019-02-21 18:45:37 -08:00
Valentine Wallace
833c31eaca htlcswitch/link_test+test_utils: add max htlc to forwarding policies 2019-02-21 18:39:32 -08:00
Valentine Wallace
20b3114100 htlcswitch+lnwallet+peer: default max htlc in fwding policy of new chans
In this commit, we set a default max HTLC in the forwarding
policies of newly open channels.

The ForwardingPolicy's MaxHTLC field (added in this commit)
will later be used to decide whether an HTLC satisfies our policy before
forwarding it.

To ensure the ForwardingPolicy's MaxHTLC default matches the max HTLC
advertised in the ChannelUpdate sent out for this channel,  we also add
a MaxPendingAmount() function to the lnwallet.Channel.
2019-02-21 18:39:32 -08:00
Olaoluwa Osuntokun
cbe0bf6a22
Merge pull request #2501 from cfromknecht/batch-preimage-writes
htlcswitch: batch preimage writes/consistency fix
2019-02-21 17:00:00 -08:00
Conner Fromknecht
3428fde5ab
htlcswitch/link_test: batch preimage write test 2019-02-19 17:06:28 -08:00
Conner Fromknecht
76cecb1396
htlcswitch/link: batch write to preimage cache
This commit makes use of the batched AddWitness
method of the WitnessCache, in order to avoid
performing one write for each accepted preimage.

Additionally, this fixes an existing hole in the
consistency guarantees since the batched writes
are now guaranteed to take place before accepting
the next CommitSig. Previously, these writes were
processed in an unsynchronized go routine that
could be delayed arbitrarily long before being
executed.

With this change, the async_payments_benchmarks
actually shows a slight improvement in
performance, presumably because we no longer do
an individual write per preimage, even though
the execution is now explicitly in the critical
path. There is likely also a marginal performance
improvement from the reduction in goroutine
overhead.
2019-02-19 17:06:15 -08:00
Conner Fromknecht
29f07a58cb
cnct+lnwl+hswc: use lntypes.Preimage for witness beacon 2019-02-19 17:06:00 -08:00
Conner Fromknecht
30f61b7630
multi: make AddPreimage variadic, optimistically compute key
In this commit, we modify the WitnessCache's
AddPreimage method to accept a variadic number
of preimages. This enables callers to batch
preimage writes in performance critical areas
of the codebase, e.g. the htlcswitch.

Additionally, we lift the computation of the
witnesses' keys outside of the db transaction.
This saves us from having to do hashing inside
and blocking other callers, and limits extraneous
blocking at the call site.
2019-02-19 17:05:04 -08:00
Wilmer Paulino
abdd01ed9a
ticker+htlcswitch: rename Mock -> Force 2019-02-12 16:05:24 -08:00
Joost Jager
077852cd4e
htlcswitch/test: test canceled invoice 2019-02-06 07:29:35 +01:00
Joost Jager
f80fb286d8
htlcswitch/test: add two hop network 2019-02-06 07:29:32 +01:00
Joost Jager
524d2465e0
htlcswitch/test: extract generic hop network 2019-02-06 07:29:29 +01:00