2017-05-01 20:03:41 +03:00
|
|
|
package htlcswitch
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2018-06-01 06:31:40 +03:00
|
|
|
"crypto/sha256"
|
2018-01-17 07:13:42 +03:00
|
|
|
"fmt"
|
2019-08-24 02:04:59 +03:00
|
|
|
"math"
|
2018-05-11 00:40:29 +03:00
|
|
|
prand "math/rand"
|
2017-05-03 17:07:55 +03:00
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
2017-05-01 20:03:41 +03:00
|
|
|
"time"
|
|
|
|
|
2018-10-30 12:36:27 +03:00
|
|
|
"github.com/btcsuite/btcd/wire"
|
2019-10-01 12:06:56 +03:00
|
|
|
"github.com/btcsuite/btclog"
|
2018-03-13 04:52:52 +03:00
|
|
|
"github.com/davecgh/go-spew/spew"
|
2017-06-29 16:40:45 +03:00
|
|
|
"github.com/go-errors/errors"
|
2019-10-01 12:06:56 +03:00
|
|
|
"github.com/lightningnetwork/lnd/build"
|
2018-01-17 07:13:42 +03:00
|
|
|
"github.com/lightningnetwork/lnd/channeldb"
|
|
|
|
"github.com/lightningnetwork/lnd/contractcourt"
|
2018-04-27 12:51:13 +03:00
|
|
|
"github.com/lightningnetwork/lnd/htlcswitch/hodl"
|
2019-08-31 00:11:20 +03:00
|
|
|
"github.com/lightningnetwork/lnd/htlcswitch/hop"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/lightningnetwork/lnd/input"
|
2019-02-20 14:11:15 +03:00
|
|
|
"github.com/lightningnetwork/lnd/invoices"
|
2018-06-08 06:17:15 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnpeer"
|
2019-01-15 13:31:22 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lntypes"
|
2017-05-01 20:03:41 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet"
|
2019-10-31 05:43:05 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
|
2017-05-01 20:03:41 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwire"
|
2019-02-11 14:01:05 +03:00
|
|
|
"github.com/lightningnetwork/lnd/queue"
|
2018-08-01 22:42:38 +03:00
|
|
|
"github.com/lightningnetwork/lnd/ticker"
|
2017-05-01 20:03:41 +03:00
|
|
|
)
|
|
|
|
|
2018-05-11 00:40:29 +03:00
|
|
|
func init() {
|
|
|
|
prand.Seed(time.Now().UnixNano())
|
|
|
|
}
|
|
|
|
|
2017-08-03 07:10:35 +03:00
|
|
|
const (
|
2019-07-27 04:05:58 +03:00
|
|
|
// DefaultMaxOutgoingCltvExpiry is the maximum outgoing time lock that
|
|
|
|
// the node accepts for forwarded payments. The value is relative to the
|
|
|
|
// current block height. The reason to have a maximum is to prevent
|
|
|
|
// funds getting locked up unreasonably long. Otherwise, an attacker
|
|
|
|
// willing to lock its own funds too, could force the funds of this node
|
|
|
|
// to be locked up for an indefinite (max int32) number of blocks.
|
2018-10-15 09:41:56 +03:00
|
|
|
//
|
2019-10-11 22:47:52 +03:00
|
|
|
// The value 2016 corresponds to on average two weeks worth of blocks
|
|
|
|
// and is based on the maximum number of hops (20), the default CLTV
|
|
|
|
// delta (40), and some extra margin to account for the other lightning
|
|
|
|
// implementations and past lnd versions which used to have a default
|
|
|
|
// CLTV delta of 144.
|
|
|
|
DefaultMaxOutgoingCltvExpiry = 2016
|
2018-10-15 09:41:56 +03:00
|
|
|
|
2018-07-31 11:29:12 +03:00
|
|
|
// DefaultMinLinkFeeUpdateTimeout represents the minimum interval in
|
|
|
|
// which a link should propose to update its commitment fee rate.
|
2018-05-11 00:40:29 +03:00
|
|
|
DefaultMinLinkFeeUpdateTimeout = 10 * time.Minute
|
2018-07-31 11:29:12 +03:00
|
|
|
|
|
|
|
// DefaultMaxLinkFeeUpdateTimeout represents the maximum interval in
|
|
|
|
// which a link should propose to update its commitment fee rate.
|
2018-05-11 00:40:29 +03:00
|
|
|
DefaultMaxLinkFeeUpdateTimeout = 60 * time.Minute
|
2019-08-24 02:04:59 +03:00
|
|
|
|
|
|
|
// DefaultMaxLinkFeeAllocation is the highest allocation we'll allow
|
|
|
|
// a channel's commitment fee to be of its balance. This only applies to
|
|
|
|
// the initiator of the channel.
|
|
|
|
DefaultMaxLinkFeeAllocation float64 = 0.5
|
2017-08-03 07:10:35 +03:00
|
|
|
)
|
|
|
|
|
2017-06-17 00:30:55 +03:00
|
|
|
// ForwardingPolicy describes the set of constraints that a given ChannelLink
|
|
|
|
// is to adhere to when forwarding HTLC's. For each incoming HTLC, this set of
|
|
|
|
// constraints will be consulted in order to ensure that adequate fees are
|
|
|
|
// paid, and our time-lock parameters are respected. In the event that an
|
|
|
|
// incoming HTLC violates any of these constraints, it is to be _rejected_ with
|
|
|
|
// the error possibly carrying along a ChannelUpdate message that includes the
|
|
|
|
// latest policy.
|
|
|
|
type ForwardingPolicy struct {
|
2019-11-15 12:09:27 +03:00
|
|
|
// MinHTLC is the smallest HTLC that is to be forwarded.
|
|
|
|
MinHTLCOut lnwire.MilliSatoshi
|
2017-06-17 00:30:55 +03:00
|
|
|
|
2018-12-08 05:39:34 +03:00
|
|
|
// MaxHTLC is the largest HTLC that is to be forwarded.
|
|
|
|
MaxHTLC lnwire.MilliSatoshi
|
|
|
|
|
2017-06-17 00:30:55 +03:00
|
|
|
// BaseFee is the base fee, expressed in milli-satoshi that must be
|
|
|
|
// paid for each incoming HTLC. This field, combined with FeeRate is
|
|
|
|
// used to compute the required fee for a given HTLC.
|
2017-08-22 09:36:43 +03:00
|
|
|
BaseFee lnwire.MilliSatoshi
|
2017-06-17 00:30:55 +03:00
|
|
|
|
|
|
|
// FeeRate is the fee rate, expressed in milli-satoshi that must be
|
|
|
|
// paid for each incoming HTLC. This field combined with BaseFee is
|
|
|
|
// used to compute the required fee for a given HTLC.
|
2017-08-22 09:36:43 +03:00
|
|
|
FeeRate lnwire.MilliSatoshi
|
2017-06-17 00:30:55 +03:00
|
|
|
|
|
|
|
// TimeLockDelta is the absolute time-lock value, expressed in blocks,
|
|
|
|
// that will be subtracted from an incoming HTLC's timelock value to
|
|
|
|
// create the time-lock value for the forwarded outgoing HTLC. The
|
|
|
|
// following constraint MUST hold for an HTLC to be forwarded:
|
|
|
|
//
|
|
|
|
// * incomingHtlc.timeLock - timeLockDelta = fwdInfo.OutgoingCTLV
|
|
|
|
//
|
|
|
|
// where fwdInfo is the forwarding information extracted from the
|
|
|
|
// per-hop payload of the incoming HTLC's onion packet.
|
|
|
|
TimeLockDelta uint32
|
|
|
|
|
|
|
|
// TODO(roasbeef): add fee module inside of switch
|
|
|
|
}
|
|
|
|
|
|
|
|
// ExpectedFee computes the expected fee for a given htlc amount. The value
|
|
|
|
// returned from this function is to be used as a sanity check when forwarding
|
|
|
|
// HTLC's to ensure that an incoming HTLC properly adheres to our propagated
|
|
|
|
// forwarding policy.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): also add in current available channel bandwidth, inverse
|
|
|
|
// func
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
func ExpectedFee(f ForwardingPolicy,
|
|
|
|
htlcAmt lnwire.MilliSatoshi) lnwire.MilliSatoshi {
|
2017-08-22 09:36:43 +03:00
|
|
|
|
2017-06-17 00:30:55 +03:00
|
|
|
return f.BaseFee + (htlcAmt*f.FeeRate)/1000000
|
|
|
|
}
|
|
|
|
|
2017-05-03 17:02:22 +03:00
|
|
|
// ChannelLinkConfig defines the configuration for the channel link. ALL
|
|
|
|
// elements within the configuration MUST be non-nil for channel link to carry
|
|
|
|
// out its duties.
|
|
|
|
type ChannelLinkConfig struct {
|
2017-06-17 00:30:55 +03:00
|
|
|
// FwrdingPolicy is the initial forwarding policy to be used when
|
|
|
|
// deciding whether to forwarding incoming HTLC's or not. This value
|
|
|
|
// can be updated with subsequent calls to UpdateForwardingPolicy
|
|
|
|
// targeted at a given ChannelLink concrete interface implementation.
|
|
|
|
FwrdingPolicy ForwardingPolicy
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// Circuits provides restricted access to the switch's circuit map,
|
|
|
|
// allowing the link to open and close circuits.
|
|
|
|
Circuits CircuitModifier
|
|
|
|
|
|
|
|
// Switch provides a reference to the HTLC switch, we only use this in
|
|
|
|
// testing to access circuit operations not typically exposed by the
|
|
|
|
// CircuitModifier.
|
2018-03-13 04:43:04 +03:00
|
|
|
//
|
2017-11-27 10:20:17 +03:00
|
|
|
// TODO(conner): remove after refactoring htlcswitch testing framework.
|
2017-05-03 17:02:22 +03:00
|
|
|
Switch *Switch
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// ForwardPackets attempts to forward the batch of htlcs through the
|
2018-07-30 23:11:11 +03:00
|
|
|
// switch, any failed packets will be returned to the provided
|
|
|
|
// ChannelLink. The link's quit signal should be provided to allow
|
|
|
|
// cancellation of forwarding during link shutdown.
|
|
|
|
ForwardPackets func(chan struct{}, ...*htlcPacket) chan error
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-02-24 04:30:29 +03:00
|
|
|
// DecodeHopIterators facilitates batched decoding of HTLC Sphinx onion
|
|
|
|
// blobs, which are then used to inform how to forward an HTLC.
|
2018-03-13 04:52:52 +03:00
|
|
|
//
|
|
|
|
// NOTE: This function assumes the same set of readers and preimages
|
|
|
|
// are always presented for the same identifier.
|
2019-09-05 14:35:39 +03:00
|
|
|
DecodeHopIterators func([]byte, []hop.DecodeHopIteratorRequest) (
|
|
|
|
[]hop.DecodeHopIteratorResponse, error)
|
2017-06-29 16:40:45 +03:00
|
|
|
|
2018-03-12 22:39:13 +03:00
|
|
|
// ExtractErrorEncrypter function is responsible for decoding HTLC
|
2017-07-15 06:08:29 +03:00
|
|
|
// Sphinx onion blob, and creating onion failure obfuscator.
|
2019-09-05 14:35:39 +03:00
|
|
|
ExtractErrorEncrypter hop.ErrorEncrypterExtracter
|
2017-06-29 16:40:45 +03:00
|
|
|
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
// FetchLastChannelUpdate retrieves the latest routing policy for a
|
|
|
|
// target channel. This channel will typically be the outgoing channel
|
|
|
|
// specified when we receive an incoming HTLC. This will be used to
|
|
|
|
// provide payment senders our latest policy when sending encrypted
|
|
|
|
// error messages.
|
|
|
|
FetchLastChannelUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate, error)
|
2017-05-02 22:01:46 +03:00
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// Peer is a lightning network node with which we have the channel link
|
|
|
|
// opened.
|
2018-06-08 06:17:15 +03:00
|
|
|
Peer lnpeer.Peer
|
2017-05-03 17:02:22 +03:00
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// Registry is a sub-system which responsible for managing the invoices
|
|
|
|
// in thread-safe manner.
|
2017-05-03 17:02:22 +03:00
|
|
|
Registry InvoiceDatabase
|
|
|
|
|
2018-02-07 06:11:11 +03:00
|
|
|
// PreimageCache is a global witness beacon that houses any new
|
|
|
|
// preimages discovered by other links. We'll use this to add new
|
2018-01-17 07:13:16 +03:00
|
|
|
// witnesses that we discover which will notify any sub-systems
|
|
|
|
// subscribed to new events.
|
|
|
|
PreimageCache contractcourt.WitnessBeacon
|
2018-01-17 07:13:42 +03:00
|
|
|
|
2018-05-09 16:49:58 +03:00
|
|
|
// OnChannelFailure is a function closure that we'll call if the
|
|
|
|
// channel failed for some reason. Depending on the severity of the
|
|
|
|
// error, the closure potentially must force close this channel and
|
|
|
|
// disconnect the peer.
|
|
|
|
//
|
|
|
|
// NOTE: The method must return in order for the ChannelLink to be able
|
|
|
|
// to shut down properly.
|
|
|
|
OnChannelFailure func(lnwire.ChannelID, lnwire.ShortChannelID,
|
|
|
|
LinkFailureError)
|
|
|
|
|
2018-01-17 07:13:42 +03:00
|
|
|
// UpdateContractSignals is a function closure that we'll use to update
|
|
|
|
// outside sub-systems with the latest signals for our inner Lightning
|
|
|
|
// channel. These signals will notify the caller when the channel has
|
|
|
|
// been closed, or when the set of active HTLC's is updated.
|
|
|
|
UpdateContractSignals func(*contractcourt.ContractSignals) error
|
|
|
|
|
2018-01-19 01:15:42 +03:00
|
|
|
// ChainEvents is an active subscription to the chain watcher for this
|
|
|
|
// channel to be notified of any on-chain activity related to this
|
|
|
|
// channel.
|
|
|
|
ChainEvents *contractcourt.ChainEventSubscription
|
|
|
|
|
2017-11-24 07:31:45 +03:00
|
|
|
// FeeEstimator is an instance of a live fee estimator which will be
|
|
|
|
// used to dynamically regulate the current fee of the commitment
|
|
|
|
// transaction to ensure timely confirmation.
|
2019-10-31 05:43:05 +03:00
|
|
|
FeeEstimator chainfee.Estimator
|
2017-11-24 07:31:45 +03:00
|
|
|
|
2018-04-27 12:51:13 +03:00
|
|
|
// hodl.Mask is a bitvector composed of hodl.Flags, specifying breakpoints
|
|
|
|
// for HTLC forwarding internal to the switch.
|
2017-11-24 07:31:45 +03:00
|
|
|
//
|
2019-08-14 20:57:31 +03:00
|
|
|
// NOTE: This should only be used for testing.
|
2018-04-27 12:51:13 +03:00
|
|
|
HodlMask hodl.Mask
|
2017-07-09 02:30:20 +03:00
|
|
|
|
|
|
|
// SyncStates is used to indicate that we need send the channel
|
|
|
|
// reestablishment message to the remote peer. It should be done if our
|
|
|
|
// clients have been restarted, or remote peer have been reconnected.
|
|
|
|
SyncStates bool
|
2018-01-16 23:17:14 +03:00
|
|
|
|
|
|
|
// BatchTicker is the ticker that determines the interval that we'll
|
|
|
|
// use to check the batch to see if there're any updates we should
|
2018-03-13 04:52:52 +03:00
|
|
|
// flush out. By batching updates into a single commit, we attempt to
|
|
|
|
// increase throughput by maximizing the number of updates coalesced
|
|
|
|
// into a single commit.
|
2018-08-01 22:42:38 +03:00
|
|
|
BatchTicker ticker.Ticker
|
2018-01-16 23:17:14 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// FwdPkgGCTicker is the ticker determining the frequency at which
|
2018-03-13 04:52:52 +03:00
|
|
|
// garbage collection of forwarding packages occurs. We use a
|
|
|
|
// time-based approach, as opposed to block epochs, as to not hinder
|
|
|
|
// syncing.
|
2018-08-01 22:42:38 +03:00
|
|
|
FwdPkgGCTicker ticker.Ticker
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-01-16 23:17:14 +03:00
|
|
|
// BatchSize is the max size of a batch of updates done to the link
|
|
|
|
// before we do a state update.
|
|
|
|
BatchSize uint32
|
2017-11-27 10:20:17 +03:00
|
|
|
|
|
|
|
// UnsafeReplay will cause a link to replay the adds in its latest
|
|
|
|
// commitment txn after the link is restarted. This should only be used
|
|
|
|
// in testing, it is here to ensure the sphinx replay detection on the
|
|
|
|
// receiving node is persistent.
|
|
|
|
UnsafeReplay bool
|
2018-05-11 00:40:29 +03:00
|
|
|
|
2019-06-14 03:28:33 +03:00
|
|
|
// MinFeeUpdateTimeout represents the minimum interval in which a link
|
|
|
|
// will propose to update its commitment fee rate. A random timeout will
|
|
|
|
// be selected between this and MaxFeeUpdateTimeout.
|
2018-05-11 00:40:29 +03:00
|
|
|
MinFeeUpdateTimeout time.Duration
|
2019-06-14 03:28:33 +03:00
|
|
|
|
|
|
|
// MaxFeeUpdateTimeout represents the maximum interval in which a link
|
|
|
|
// will propose to update its commitment fee rate. A random timeout will
|
|
|
|
// be selected between this and MinFeeUpdateTimeout.
|
2018-05-11 00:40:29 +03:00
|
|
|
MaxFeeUpdateTimeout time.Duration
|
2019-03-26 14:05:43 +03:00
|
|
|
|
2019-04-03 13:18:19 +03:00
|
|
|
// OutgoingCltvRejectDelta defines the number of blocks before expiry of
|
|
|
|
// an htlc where we don't offer an htlc anymore. This should be at least
|
|
|
|
// the outgoing broadcast delta, because in any case we don't want to
|
|
|
|
// risk offering an htlc that triggers channel closure.
|
|
|
|
OutgoingCltvRejectDelta uint32
|
2019-06-14 03:28:14 +03:00
|
|
|
|
|
|
|
// TowerClient is an optional engine that manages the signing,
|
|
|
|
// encrypting, and uploading of justice transactions to the daemon's
|
|
|
|
// configured set of watchtowers.
|
|
|
|
TowerClient TowerClient
|
2019-07-27 04:05:58 +03:00
|
|
|
|
2019-12-05 01:34:18 +03:00
|
|
|
// MaxOutgoingCltvExpiry is the maximum outgoing timelock that the link
|
|
|
|
// should accept for a forwarded HTLC. The value is relative to the
|
|
|
|
// current block height.
|
2019-07-27 04:05:58 +03:00
|
|
|
MaxOutgoingCltvExpiry uint32
|
2019-08-24 02:04:59 +03:00
|
|
|
|
|
|
|
// MaxFeeAllocation is the highest allocation we'll allow a channel's
|
|
|
|
// commitment fee to be of its balance. This only applies to the
|
|
|
|
// initiator of the channel.
|
|
|
|
MaxFeeAllocation float64
|
2019-09-19 22:46:44 +03:00
|
|
|
|
|
|
|
// NotifyActiveChannel allows the link to tell the ChannelNotifier when
|
|
|
|
// channels becomes active.
|
|
|
|
NotifyActiveChannel func(wire.OutPoint)
|
|
|
|
|
|
|
|
// NotifyInactiveChannel allows the switch to tell the ChannelNotifier
|
|
|
|
// when channels become inactive.
|
|
|
|
NotifyInactiveChannel func(wire.OutPoint)
|
2017-05-03 17:02:22 +03:00
|
|
|
}
|
|
|
|
|
2017-05-03 17:07:55 +03:00
|
|
|
// channelLink is the service which drives a channel's commitment update
|
2018-03-13 04:52:52 +03:00
|
|
|
// state-machine. In the event that an HTLC needs to be propagated to another
|
|
|
|
// link, the forward handler from config is used which sends HTLC to the
|
2017-05-03 17:07:55 +03:00
|
|
|
// switch. Additionally, the link encapsulate logic of commitment protocol
|
|
|
|
// message ordering and updates.
|
|
|
|
type channelLink struct {
|
2017-06-17 00:58:02 +03:00
|
|
|
// The following fields are only meant to be used *atomically*
|
2019-09-19 22:46:56 +03:00
|
|
|
started int32
|
|
|
|
reestablished int32
|
|
|
|
shutdown int32
|
2017-06-17 00:58:02 +03:00
|
|
|
|
2018-05-23 16:14:46 +03:00
|
|
|
// failed should be set to true in case a link error happens, making
|
|
|
|
// sure we don't process any more updates.
|
|
|
|
failed bool
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// keystoneBatch represents a volatile list of keystones that must be
|
2018-03-13 04:52:52 +03:00
|
|
|
// written before attempting to sign the next commitment txn. These
|
|
|
|
// represent all the HTLC's forwarded to the link from the switch. Once
|
|
|
|
// we lock them into our outgoing commitment, then the circuit has a
|
|
|
|
// keystone, and is fully opened.
|
2017-11-27 10:20:17 +03:00
|
|
|
keystoneBatch []Keystone
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// openedCircuits is the set of all payment circuits that will be open
|
|
|
|
// once we make our next commitment. After making the commitment we'll
|
|
|
|
// ACK all these from our mailbox to ensure that they don't get
|
|
|
|
// re-delivered if we reconnect.
|
2017-11-27 10:20:17 +03:00
|
|
|
openedCircuits []CircuitKey
|
2018-03-13 04:52:52 +03:00
|
|
|
|
|
|
|
// closedCircuits is the set of all payment circuits that will be
|
|
|
|
// closed once we make our next commitment. After taking the commitment
|
|
|
|
// we'll ACK all these to ensure that they don't get re-delivered if we
|
|
|
|
// reconnect.
|
2017-11-27 10:20:17 +03:00
|
|
|
closedCircuits []CircuitKey
|
|
|
|
|
2017-05-02 00:06:10 +03:00
|
|
|
// channel is a lightning network channel to which we apply htlc
|
|
|
|
// updates.
|
|
|
|
channel *lnwallet.LightningChannel
|
2017-05-03 17:02:22 +03:00
|
|
|
|
2018-02-04 05:14:09 +03:00
|
|
|
// shortChanID is the most up to date short channel ID for the link.
|
|
|
|
shortChanID lnwire.ShortChannelID
|
|
|
|
|
2017-05-03 17:02:22 +03:00
|
|
|
// cfg is a structure which carries all dependable fields/handlers
|
|
|
|
// which may affect behaviour of the service.
|
2017-06-17 00:58:02 +03:00
|
|
|
cfg ChannelLinkConfig
|
2017-05-03 17:07:55 +03:00
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// overflowQueue is used to store the htlc add updates which haven't
|
|
|
|
// been processed because of the commitment transaction overflow.
|
|
|
|
overflowQueue *packetQueue
|
2017-05-24 18:27:39 +03:00
|
|
|
|
2017-11-11 01:48:23 +03:00
|
|
|
// mailBox is the main interface between the outside world and the
|
|
|
|
// link. All incoming messages will be sent over this mailBox. Messages
|
|
|
|
// include new updates from our connected peer, and new packets to be
|
|
|
|
// forwarded sent by the switch.
|
2017-11-27 10:20:17 +03:00
|
|
|
mailBox MailBox
|
2017-09-25 22:31:52 +03:00
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// upstream is a channel that new messages sent from the remote peer to
|
|
|
|
// the local peer will be sent across.
|
2017-05-03 17:07:55 +03:00
|
|
|
upstream chan lnwire.Message
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// downstream is a channel in which new multi-hop HTLC's to be
|
|
|
|
// forwarded will be sent across. Messages from this channel are sent
|
|
|
|
// by the HTLC switch.
|
2017-05-03 17:07:55 +03:00
|
|
|
downstream chan *htlcPacket
|
|
|
|
|
2018-01-17 07:15:08 +03:00
|
|
|
// htlcUpdates is a channel that we'll use to update outside
|
|
|
|
// sub-systems with the latest set of active HTLC's on our channel.
|
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-17 03:23:26 +03:00
|
|
|
htlcUpdates chan *contractcourt.ContractUpdate
|
2018-01-17 07:15:08 +03:00
|
|
|
|
2018-05-11 00:40:29 +03:00
|
|
|
// updateFeeTimer is the timer responsible for updating the link's
|
|
|
|
// commitment fee every time it fires.
|
|
|
|
updateFeeTimer *time.Timer
|
|
|
|
|
2019-02-20 04:06:15 +03:00
|
|
|
// uncommittedPreimages stores a list of all preimages that have been
|
|
|
|
// learned since receiving the last CommitSig from the remote peer. The
|
|
|
|
// batch will be flushed just before accepting the subsequent CommitSig
|
|
|
|
// or on shutdown to avoid doing a write for each preimage received.
|
|
|
|
uncommittedPreimages []lntypes.Preimage
|
|
|
|
|
2018-02-04 05:14:09 +03:00
|
|
|
sync.RWMutex
|
|
|
|
|
2019-02-11 14:01:05 +03:00
|
|
|
// hodlQueue is used to receive exit hop htlc resolutions from invoice
|
|
|
|
// registry.
|
|
|
|
hodlQueue *queue.ConcurrentQueue
|
|
|
|
|
2019-08-14 22:11:34 +03:00
|
|
|
// hodlMap stores related htlc data for a circuit key. It allows
|
2019-02-11 14:01:05 +03:00
|
|
|
// resolving those htlcs when we receive a message on hodlQueue.
|
2019-08-14 22:11:34 +03:00
|
|
|
hodlMap map[channeldb.CircuitKey]hodlHtlc
|
2019-02-11 14:01:05 +03:00
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
// log is a link-specific logging instance.
|
|
|
|
log btclog.Logger
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
wg sync.WaitGroup
|
|
|
|
quit chan struct{}
|
2017-05-03 17:07:55 +03:00
|
|
|
}
|
|
|
|
|
2019-02-20 14:11:15 +03:00
|
|
|
// hodlHtlc contains htlc data that is required for resolution.
|
|
|
|
type hodlHtlc struct {
|
|
|
|
pd *lnwallet.PaymentDescriptor
|
2019-09-05 14:35:39 +03:00
|
|
|
obfuscator hop.ErrorEncrypter
|
2019-02-20 14:11:15 +03:00
|
|
|
}
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// NewChannelLink creates a new instance of a ChannelLink given a configuration
|
|
|
|
// and active channel that will be used to verify/apply updates to.
|
2018-06-01 06:31:40 +03:00
|
|
|
func NewChannelLink(cfg ChannelLinkConfig,
|
|
|
|
channel *lnwallet.LightningChannel) ChannelLink {
|
2017-05-02 00:06:10 +03:00
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
logPrefix := fmt.Sprintf("ChannelLink(%v):", channel.ShortChanID())
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
return &channelLink{
|
2017-07-09 02:38:50 +03:00
|
|
|
cfg: cfg,
|
|
|
|
channel: channel,
|
2018-02-04 05:14:09 +03:00
|
|
|
shortChanID: channel.ShortChanID(),
|
2017-09-25 22:31:52 +03:00
|
|
|
// TODO(roasbeef): just do reserve here?
|
2019-04-10 17:05:09 +03:00
|
|
|
overflowQueue: newPacketQueue(input.MaxHTLCNumber / 2),
|
|
|
|
htlcUpdates: make(chan *contractcourt.ContractUpdate),
|
|
|
|
hodlMap: make(map[channeldb.CircuitKey]hodlHtlc),
|
|
|
|
hodlQueue: queue.NewConcurrentQueue(10),
|
|
|
|
log: build.NewPrefixLog(logPrefix, log),
|
|
|
|
quit: make(chan struct{}),
|
2017-05-02 00:06:10 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-03 17:07:55 +03:00
|
|
|
// A compile time check to ensure channelLink implements the ChannelLink
|
|
|
|
// interface.
|
|
|
|
var _ ChannelLink = (*channelLink)(nil)
|
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// Start starts all helper goroutines required for the operation of the channel
|
|
|
|
// link.
|
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) Start() error {
|
|
|
|
if !atomic.CompareAndSwapInt32(&l.started, 0, 1) {
|
2017-07-09 02:30:20 +03:00
|
|
|
err := errors.Errorf("channel link(%v): already started", l)
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Warn("already started")
|
2017-07-09 02:30:20 +03:00
|
|
|
return err
|
2017-05-03 17:07:55 +03:00
|
|
|
}
|
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Info("starting")
|
2017-05-03 17:07:55 +03:00
|
|
|
|
2019-06-14 03:28:14 +03:00
|
|
|
// If the config supplied watchtower client, ensure the channel is
|
|
|
|
// registered before trying to use it during operation.
|
|
|
|
if l.cfg.TowerClient != nil {
|
|
|
|
err := l.cfg.TowerClient.RegisterChannel(l.ChanID())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
l.mailBox.ResetMessages()
|
2017-09-23 01:54:10 +03:00
|
|
|
l.overflowQueue.Start()
|
2019-02-11 14:01:05 +03:00
|
|
|
l.hodlQueue.Start()
|
2017-09-23 01:54:10 +03:00
|
|
|
|
2018-05-04 06:11:46 +03:00
|
|
|
// Before launching the htlcManager messages, revert any circuits that
|
|
|
|
// were marked open in the switch's circuit map, but did not make it
|
|
|
|
// into a commitment txn. We use the next local htlc index as the cut
|
|
|
|
// off point, since all indexes below that are committed. This action
|
|
|
|
// is only performed if the link's final short channel ID has been
|
|
|
|
// assigned, otherwise we would try to trim the htlcs belonging to the
|
2019-08-31 00:11:38 +03:00
|
|
|
// all-zero, hop.Source ID.
|
|
|
|
if l.ShortChanID() != hop.Source {
|
2018-05-04 06:11:46 +03:00
|
|
|
localHtlcIndex, err := l.channel.NextLocalHtlcIndex()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to retrieve next local "+
|
|
|
|
"htlc index: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NOTE: This is automatically done by the switch when it
|
|
|
|
// starts up, but is necessary to prevent inconsistencies in
|
|
|
|
// the case that the link flaps. This is a result of a link's
|
|
|
|
// life-cycle being shorter than that of the switch.
|
|
|
|
chanID := l.ShortChanID()
|
|
|
|
err = l.cfg.Circuits.TrimOpenCircuits(chanID, localHtlcIndex)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to trim circuits above "+
|
|
|
|
"local htlc index %d: %v", localHtlcIndex, err)
|
|
|
|
}
|
2018-07-13 04:16:32 +03:00
|
|
|
|
|
|
|
// Since the link is live, before we start the link we'll update
|
|
|
|
// the ChainArbitrator with the set of new channel signals for
|
|
|
|
// this channel.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): split goroutines within channel arb to avoid
|
|
|
|
go func() {
|
|
|
|
signals := &contractcourt.ContractSignals{
|
|
|
|
HtlcUpdates: l.htlcUpdates,
|
|
|
|
ShortChanID: l.channel.ShortChanID(),
|
|
|
|
}
|
|
|
|
|
|
|
|
err := l.cfg.UpdateContractSignals(signals)
|
|
|
|
if err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to update signals")
|
2018-07-13 04:16:32 +03:00
|
|
|
}
|
|
|
|
}()
|
2018-05-04 06:11:46 +03:00
|
|
|
}
|
|
|
|
|
2018-05-11 00:40:29 +03:00
|
|
|
l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
|
|
|
|
|
2017-05-03 17:07:55 +03:00
|
|
|
l.wg.Add(1)
|
2017-06-17 00:58:02 +03:00
|
|
|
go l.htlcManager()
|
2017-05-03 17:07:55 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop gracefully stops all active helper goroutines, then waits until they've
|
|
|
|
// exited.
|
2017-06-01 02:43:37 +03:00
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) Stop() {
|
|
|
|
if !atomic.CompareAndSwapInt32(&l.shutdown, 0, 1) {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Warn("already stopped")
|
2017-05-03 17:07:55 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Info("stopping")
|
2017-05-03 17:07:55 +03:00
|
|
|
|
2019-02-11 14:01:05 +03:00
|
|
|
// As the link is stopping, we are no longer interested in hodl events
|
|
|
|
// coming from the invoice registry.
|
|
|
|
l.cfg.Registry.HodlUnsubscribeAll(l.hodlQueue.ChanIn())
|
|
|
|
|
2018-01-19 01:15:42 +03:00
|
|
|
if l.cfg.ChainEvents.Cancel != nil {
|
|
|
|
l.cfg.ChainEvents.Cancel()
|
|
|
|
}
|
|
|
|
|
2018-05-11 00:40:29 +03:00
|
|
|
l.updateFeeTimer.Stop()
|
2017-09-23 01:54:10 +03:00
|
|
|
l.overflowQueue.Stop()
|
2019-02-11 14:01:05 +03:00
|
|
|
l.hodlQueue.Stop()
|
2017-09-23 01:54:10 +03:00
|
|
|
|
2017-05-03 17:07:55 +03:00
|
|
|
close(l.quit)
|
|
|
|
l.wg.Wait()
|
2019-02-20 04:06:15 +03:00
|
|
|
|
|
|
|
// As a final precaution, we will attempt to flush any uncommitted
|
|
|
|
// preimages to the preimage cache. The preimages should be re-delivered
|
|
|
|
// after channel reestablishment, however this adds an extra layer of
|
|
|
|
// protection in case the peer never returns. Without this, we will be
|
|
|
|
// unable to settle any contracts depending on the preimages even though
|
|
|
|
// we had learned them at some point.
|
|
|
|
err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
|
|
|
|
if err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to add preimages=%v to cache: %v",
|
2019-02-20 04:06:15 +03:00
|
|
|
l.uncommittedPreimages, err)
|
|
|
|
}
|
2017-05-01 20:03:41 +03:00
|
|
|
}
|
|
|
|
|
2018-06-27 04:05:39 +03:00
|
|
|
// WaitForShutdown blocks until the link finishes shutting down, which includes
|
|
|
|
// termination of all dependent goroutines.
|
|
|
|
func (l *channelLink) WaitForShutdown() {
|
|
|
|
l.wg.Wait()
|
|
|
|
}
|
|
|
|
|
2017-12-06 04:48:28 +03:00
|
|
|
// EligibleToForward returns a bool indicating if the channel is able to
|
|
|
|
// actively accept requests to forward HTLC's. We're able to forward HTLC's if
|
|
|
|
// we know the remote party's next revocation point. Otherwise, we can't
|
2018-05-02 02:29:47 +03:00
|
|
|
// initiate new channel state. We also require that the short channel ID not be
|
|
|
|
// the all-zero source ID, meaning that the channel has had its ID finalized.
|
2017-12-06 04:48:28 +03:00
|
|
|
func (l *channelLink) EligibleToForward() bool {
|
2018-05-02 02:29:47 +03:00
|
|
|
return l.channel.RemoteNextRevocation() != nil &&
|
2019-09-19 22:46:56 +03:00
|
|
|
l.ShortChanID() != hop.Source &&
|
|
|
|
l.isReestablished()
|
|
|
|
}
|
|
|
|
|
|
|
|
// isReestablished returns true if the link has successfully completed the
|
|
|
|
// channel reestablishment dance.
|
|
|
|
func (l *channelLink) isReestablished() bool {
|
|
|
|
return atomic.LoadInt32(&l.reestablished) == 1
|
|
|
|
}
|
|
|
|
|
|
|
|
// markReestablished signals that the remote peer has successfully exchanged
|
|
|
|
// channel reestablish messages and that the channel is ready to process
|
|
|
|
// subsequent messages.
|
|
|
|
func (l *channelLink) markReestablished() {
|
|
|
|
atomic.StoreInt32(&l.reestablished, 1)
|
2017-12-06 04:48:28 +03:00
|
|
|
}
|
|
|
|
|
2017-11-24 07:31:45 +03:00
|
|
|
// sampleNetworkFee samples the current fee rate on the network to get into the
|
|
|
|
// chain in a timely manner. The returned value is expressed in fee-per-kw, as
|
|
|
|
// this is the native rate used when computing the fee for commitment
|
|
|
|
// transactions, and the second-level HTLC transactions.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (l *channelLink) sampleNetworkFee() (chainfee.SatPerKWeight, error) {
|
2018-07-28 04:20:58 +03:00
|
|
|
// We'll first query for the sat/kw recommended to be confirmed within 3
|
|
|
|
// blocks.
|
|
|
|
feePerKw, err := l.cfg.FeeEstimator.EstimateFeePerKW(3)
|
2017-11-24 07:31:45 +03:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Debugf("sampled fee rate for 3 block conf: %v sat/kw",
|
|
|
|
int64(feePerKw))
|
2017-11-24 07:31:45 +03:00
|
|
|
|
|
|
|
return feePerKw, nil
|
|
|
|
}
|
|
|
|
|
2017-11-24 07:21:46 +03:00
|
|
|
// shouldAdjustCommitFee returns true if we should update our commitment fee to
|
|
|
|
// match that of the network fee. We'll only update our commitment fee if the
|
|
|
|
// network fee is +/- 10% to our network fee.
|
2019-10-31 05:43:05 +03:00
|
|
|
func shouldAdjustCommitFee(netFee, chanFee chainfee.SatPerKWeight) bool {
|
2017-11-24 07:21:46 +03:00
|
|
|
switch {
|
|
|
|
// If the network fee is greater than the commitment fee, then we'll
|
|
|
|
// switch to it if it's at least 10% greater than the commit fee.
|
|
|
|
case netFee > chanFee && netFee >= (chanFee+(chanFee*10)/100):
|
|
|
|
return true
|
|
|
|
|
|
|
|
// If the network fee is less than our commitment fee, then we'll
|
|
|
|
// switch to it if it's at least 10% less than the commitment fee.
|
|
|
|
case netFee < chanFee && netFee <= (chanFee-(chanFee*10)/100):
|
|
|
|
return true
|
|
|
|
|
|
|
|
// Otherwise, we won't modify our fee.
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-27 17:01:18 +03:00
|
|
|
// createFailureWithUpdate retrieves this link's last channel update message and
|
|
|
|
// passes it into the callback. It expects a fully populated failure message.
|
|
|
|
func (l *channelLink) createFailureWithUpdate(
|
|
|
|
cb func(update *lnwire.ChannelUpdate) lnwire.FailureMessage) lnwire.FailureMessage {
|
|
|
|
|
|
|
|
update, err := l.cfg.FetchLastChannelUpdate(l.ShortChanID())
|
|
|
|
if err != nil {
|
|
|
|
return &lnwire.FailTemporaryNodeFailure{}
|
|
|
|
}
|
|
|
|
|
|
|
|
return cb(update)
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:15:51 +03:00
|
|
|
// syncChanState attempts to synchronize channel states with the remote party.
|
|
|
|
// This method is to be called upon reconnection after the initial funding
|
|
|
|
// flow. We'll compare out commitment chains with the remote party, and re-send
|
|
|
|
// either a danging commit signature, a revocation, or both.
|
|
|
|
func (l *channelLink) syncChanStates() error {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Info("attempting to re-resynchronize")
|
2018-01-17 07:15:51 +03:00
|
|
|
|
|
|
|
// First, we'll generate our ChanSync message to send to the other
|
|
|
|
// side. Based on this message, the remote party will decide if they
|
|
|
|
// need to retransmit any data or not.
|
2019-03-11 02:44:01 +03:00
|
|
|
chanState := l.channel.State()
|
2019-09-11 12:15:57 +03:00
|
|
|
localChanSyncMsg, err := chanState.ChanSyncMsg()
|
2018-01-17 07:15:51 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to generate chan sync message for "+
|
|
|
|
"ChannelPoint(%v)", l.channel.ChannelPoint())
|
|
|
|
}
|
2019-04-11 04:19:36 +03:00
|
|
|
|
2019-04-10 05:48:34 +03:00
|
|
|
if err := l.cfg.Peer.SendMessage(true, localChanSyncMsg); err != nil {
|
2018-01-17 07:15:51 +03:00
|
|
|
return fmt.Errorf("Unable to send chan sync message for "+
|
|
|
|
"ChannelPoint(%v)", l.channel.ChannelPoint())
|
|
|
|
}
|
|
|
|
|
|
|
|
var msgsToReSend []lnwire.Message
|
|
|
|
|
2019-09-19 22:47:08 +03:00
|
|
|
// Next, we'll wait indefinitely to receive the ChanSync message. The
|
|
|
|
// first message sent MUST be the ChanSync message.
|
2018-01-17 07:15:51 +03:00
|
|
|
select {
|
|
|
|
case msg := <-l.upstream:
|
|
|
|
remoteChanSyncMsg, ok := msg.(*lnwire.ChannelReestablish)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("first message sent to sync "+
|
|
|
|
"should be ChannelReestablish, instead "+
|
|
|
|
"received: %T", msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the remote party indicates that they think we haven't
|
|
|
|
// done any state updates yet, then we'll retransmit the
|
|
|
|
// funding locked message first. We do this, as at this point
|
|
|
|
// we can't be sure if they've really received the
|
|
|
|
// FundingLocked message.
|
|
|
|
if remoteChanSyncMsg.NextLocalCommitHeight == 1 &&
|
|
|
|
localChanSyncMsg.NextLocalCommitHeight == 1 &&
|
|
|
|
!l.channel.IsPending() {
|
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Infof("resending FundingLocked message to peer")
|
2018-01-17 07:15:51 +03:00
|
|
|
|
|
|
|
nextRevocation, err := l.channel.NextRevocationKey()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to create next "+
|
|
|
|
"revocation: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
fundingLockedMsg := lnwire.NewFundingLocked(
|
|
|
|
l.ChanID(), nextRevocation,
|
|
|
|
)
|
2018-06-08 06:17:15 +03:00
|
|
|
err = l.cfg.Peer.SendMessage(false, fundingLockedMsg)
|
2018-01-17 07:15:51 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to re-send "+
|
|
|
|
"FundingLocked: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// In any case, we'll then process their ChanSync message.
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Info("received re-establishment message from remote side")
|
2018-01-17 07:15:51 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
var (
|
|
|
|
openedCircuits []CircuitKey
|
|
|
|
closedCircuits []CircuitKey
|
|
|
|
)
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// We've just received a ChanSync message from the remote
|
|
|
|
// party, so we'll process the message in order to determine
|
|
|
|
// if we need to re-transmit any messages to the remote party.
|
2017-11-27 10:20:17 +03:00
|
|
|
msgsToReSend, openedCircuits, closedCircuits, err =
|
|
|
|
l.channel.ProcessChanSyncMsg(remoteChanSyncMsg)
|
2018-01-17 07:15:51 +03:00
|
|
|
if err != nil {
|
2018-07-12 12:02:54 +03:00
|
|
|
return err
|
2018-01-17 07:15:51 +03:00
|
|
|
}
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// Repopulate any identifiers for circuits that may have been
|
2018-03-13 04:52:52 +03:00
|
|
|
// opened or unclosed. This may happen if we needed to
|
|
|
|
// retransmit a commitment signature message.
|
2017-11-27 10:20:17 +03:00
|
|
|
l.openedCircuits = openedCircuits
|
|
|
|
l.closedCircuits = closedCircuits
|
|
|
|
|
|
|
|
// Ensure that all packets have been have been removed from the
|
|
|
|
// link's mailbox.
|
2018-08-19 05:35:20 +03:00
|
|
|
if err := l.ackDownStreamPackets(); err != nil {
|
2017-11-27 10:20:17 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:15:51 +03:00
|
|
|
if len(msgsToReSend) > 0 {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Infof("sending %v updates to synchronize the "+
|
2019-10-01 12:16:24 +03:00
|
|
|
"state", len(msgsToReSend))
|
2018-01-17 07:15:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// If we have any messages to retransmit, we'll do so
|
|
|
|
// immediately so we return to a synchronized state as soon as
|
|
|
|
// possible.
|
|
|
|
for _, msg := range msgsToReSend {
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, msg)
|
2018-01-17 07:15:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
case <-l.quit:
|
2018-05-02 02:29:47 +03:00
|
|
|
return ErrLinkShuttingDown
|
2018-01-17 07:15:51 +03:00
|
|
|
}
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
return nil
|
|
|
|
}
|
2018-01-17 07:15:51 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// resolveFwdPkgs loads any forwarding packages for this link from disk, and
|
2018-03-13 04:52:52 +03:00
|
|
|
// reprocesses them in order. The primary goal is to make sure that any HTLCs
|
|
|
|
// we previously received are reinstated in memory, and forwarded to the switch
|
|
|
|
// if necessary. After a restart, this will also delete any previously
|
|
|
|
// completed packages.
|
2017-11-27 10:20:17 +03:00
|
|
|
func (l *channelLink) resolveFwdPkgs() error {
|
|
|
|
fwdPkgs, err := l.channel.LoadFwdPkgs()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-01-17 07:15:51 +03:00
|
|
|
}
|
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Debugf("loaded %d fwd pks", len(fwdPkgs))
|
2018-01-17 07:18:35 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
for _, fwdPkg := range fwdPkgs {
|
2019-04-10 14:10:25 +03:00
|
|
|
if err := l.resolveFwdPkg(fwdPkg); err != nil {
|
2018-01-17 07:18:35 +03:00
|
|
|
return err
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// If any of our reprocessing steps require an update to the commitment
|
|
|
|
// txn, we initiate a state transition to capture all relevant changes.
|
2019-04-10 14:10:25 +03:00
|
|
|
if l.channel.PendingLocalUpdateCount() > 0 {
|
2017-11-27 10:20:17 +03:00
|
|
|
return l.updateCommitTx()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// resolveFwdPkg interprets the FwdState of the provided package, either
|
|
|
|
// reprocesses any outstanding htlcs in the package, or performs garbage
|
|
|
|
// collection on the package.
|
2019-04-10 14:10:25 +03:00
|
|
|
func (l *channelLink) resolveFwdPkg(fwdPkg *channeldb.FwdPkg) error {
|
2017-11-27 10:20:17 +03:00
|
|
|
// Remove any completed packages to clear up space.
|
|
|
|
if fwdPkg.State == channeldb.FwdStateCompleted {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Debugf("removing completed fwd pkg for height=%d",
|
2017-11-27 10:20:17 +03:00
|
|
|
fwdPkg.Height)
|
|
|
|
|
|
|
|
err := l.channel.RemoveFwdPkg(fwdPkg.Height)
|
2018-01-17 07:18:35 +03:00
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to remove fwd pkg for height=%d: "+
|
|
|
|
"%v", fwdPkg.Height, err)
|
2019-04-10 14:10:25 +03:00
|
|
|
return err
|
2018-01-17 07:18:35 +03:00
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
2018-01-17 07:18:35 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// Otherwise this is either a new package or one has gone through
|
2018-03-13 04:52:52 +03:00
|
|
|
// processing, but contains htlcs that need to be restored in memory.
|
|
|
|
// We replay this forwarding package to make sure our local mem state
|
|
|
|
// is resurrected, we mimic any original responses back to the remote
|
|
|
|
// party, and re-forward the relevant HTLCs to the switch.
|
2017-11-27 10:20:17 +03:00
|
|
|
|
|
|
|
// If the package is fully acked but not completed, it must still have
|
|
|
|
// settles and fails to propagate.
|
|
|
|
if !fwdPkg.SettleFailFilter.IsFull() {
|
2019-01-10 14:23:56 +03:00
|
|
|
settleFails, err := lnwallet.PayDescsFromRemoteLogUpdates(
|
2017-11-27 10:20:17 +03:00
|
|
|
fwdPkg.Source, fwdPkg.Height, fwdPkg.SettleFails,
|
|
|
|
)
|
2019-01-10 14:23:56 +03:00
|
|
|
if err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to process remote log updates: %v",
|
2019-01-10 14:23:56 +03:00
|
|
|
err)
|
2019-04-10 14:10:25 +03:00
|
|
|
return err
|
2019-01-10 14:23:56 +03:00
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
l.processRemoteSettleFails(fwdPkg, settleFails)
|
2018-01-17 07:18:35 +03:00
|
|
|
}
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// Finally, replay *ALL ADDS* in this forwarding package. The
|
|
|
|
// downstream logic is able to filter out any duplicates, but we must
|
|
|
|
// shove the entire, original set of adds down the pipeline so that the
|
|
|
|
// batch of adds presented to the sphinx router does not ever change.
|
2017-11-27 10:20:17 +03:00
|
|
|
if !fwdPkg.AckFilter.IsFull() {
|
2019-01-10 14:23:56 +03:00
|
|
|
adds, err := lnwallet.PayDescsFromRemoteLogUpdates(
|
2017-11-27 10:20:17 +03:00
|
|
|
fwdPkg.Source, fwdPkg.Height, fwdPkg.Adds,
|
|
|
|
)
|
2019-01-10 14:23:56 +03:00
|
|
|
if err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to process remote log updates: %v",
|
2019-01-10 14:23:56 +03:00
|
|
|
err)
|
2019-04-10 14:10:25 +03:00
|
|
|
return err
|
2019-01-10 14:23:56 +03:00
|
|
|
}
|
2019-04-10 14:10:25 +03:00
|
|
|
l.processRemoteAdds(fwdPkg, adds)
|
2018-05-23 16:14:46 +03:00
|
|
|
|
|
|
|
// If the link failed during processing the adds, we must
|
|
|
|
// return to ensure we won't attempted to update the state
|
|
|
|
// further.
|
|
|
|
if l.failed {
|
2019-04-10 14:10:25 +03:00
|
|
|
return fmt.Errorf("link failed while " +
|
2018-05-23 16:14:46 +03:00
|
|
|
"processing remote adds")
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
return nil
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// fwdPkgGarbager periodically reads all forwarding packages from disk and
|
|
|
|
// removes those that can be discarded. It is safe to do this entirely in the
|
|
|
|
// background, since all state is coordinated on disk. This also ensures the
|
|
|
|
// link can continue to process messages and interleave database accesses.
|
|
|
|
//
|
|
|
|
// NOTE: This MUST be run as a goroutine.
|
|
|
|
func (l *channelLink) fwdPkgGarbager() {
|
|
|
|
defer l.wg.Done()
|
|
|
|
|
2018-08-01 22:42:38 +03:00
|
|
|
l.cfg.FwdPkgGCTicker.Resume()
|
2017-11-27 10:20:17 +03:00
|
|
|
defer l.cfg.FwdPkgGCTicker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
2018-08-01 22:42:38 +03:00
|
|
|
case <-l.cfg.FwdPkgGCTicker.Ticks():
|
2017-11-27 10:20:17 +03:00
|
|
|
fwdPkgs, err := l.channel.LoadFwdPkgs()
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf("unable to load fwdpkgs for gc: %v",
|
|
|
|
err)
|
2017-11-27 10:20:17 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(conner): batch removal of forward packages.
|
|
|
|
for _, fwdPkg := range fwdPkgs {
|
|
|
|
if fwdPkg.State != channeldb.FwdStateCompleted {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
err = l.channel.RemoveFwdPkg(fwdPkg.Height)
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf("unable to remove fwd pkg "+
|
2017-11-27 10:20:17 +03:00
|
|
|
"for height=%d: %v",
|
|
|
|
fwdPkg.Height, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case <-l.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2018-01-17 07:18:35 +03:00
|
|
|
}
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// htlcManager is the primary goroutine which drives a channel's commitment
|
2017-05-01 20:03:41 +03:00
|
|
|
// update state-machine in response to messages received via several channels.
|
2017-05-04 00:03:47 +03:00
|
|
|
// This goroutine reads messages from the upstream (remote) peer, and also from
|
|
|
|
// downstream channel managed by the channel link. In the event that an htlc
|
|
|
|
// needs to be forwarded, then send-only forward handler is used which sends
|
|
|
|
// htlc packets to the switch. Additionally, the this goroutine handles acting
|
|
|
|
// upon all timeouts for any active HTLCs, manages the channel's revocation
|
|
|
|
// window, and also the htlc trickle queue+timer for this active channels.
|
2017-06-01 02:43:37 +03:00
|
|
|
//
|
|
|
|
// NOTE: This MUST be run as a goroutine.
|
2017-06-17 00:58:02 +03:00
|
|
|
func (l *channelLink) htlcManager() {
|
2017-11-11 06:37:47 +03:00
|
|
|
defer func() {
|
2018-07-31 08:25:38 +03:00
|
|
|
l.cfg.BatchTicker.Stop()
|
2017-11-11 06:37:47 +03:00
|
|
|
l.wg.Done()
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Infof("exited")
|
2017-11-11 06:37:47 +03:00
|
|
|
}()
|
2017-05-04 00:03:47 +03:00
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Infof("HTLC manager started, bandwidth=%v", l.Bandwidth())
|
2017-05-01 20:03:41 +03:00
|
|
|
|
2017-11-11 01:57:59 +03:00
|
|
|
// TODO(roasbeef): need to call wipe chan whenever D/C?
|
|
|
|
|
|
|
|
// If this isn't the first time that this channel link has been
|
|
|
|
// created, then we'll need to check to see if we need to
|
2018-01-17 07:15:51 +03:00
|
|
|
// re-synchronize state with the remote peer. settledHtlcs is a map of
|
|
|
|
// HTLC's that we re-settled as part of the channel state sync.
|
2017-07-09 02:30:20 +03:00
|
|
|
if l.cfg.SyncStates {
|
2018-05-02 02:29:47 +03:00
|
|
|
err := l.syncChanStates()
|
|
|
|
if err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Warnf("error when syncing channel states: %v", err)
|
2019-09-06 14:14:39 +03:00
|
|
|
|
2019-09-06 14:14:40 +03:00
|
|
|
errDataLoss, localDataLoss :=
|
2019-09-06 14:14:39 +03:00
|
|
|
err.(*lnwallet.ErrCommitSyncLocalDataLoss)
|
|
|
|
|
2018-07-12 12:02:54 +03:00
|
|
|
switch {
|
|
|
|
case err == ErrLinkShuttingDown:
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Debugf("unable to sync channel states, " +
|
2018-07-12 12:02:54 +03:00
|
|
|
"link is shutting down")
|
|
|
|
return
|
|
|
|
|
|
|
|
// We failed syncing the commit chains, probably
|
|
|
|
// because the remote has lost state. We should force
|
|
|
|
// close the channel.
|
|
|
|
case err == lnwallet.ErrCommitSyncRemoteDataLoss:
|
|
|
|
fallthrough
|
|
|
|
|
|
|
|
// The remote sent us an invalid last commit secret, we
|
|
|
|
// should force close the channel.
|
|
|
|
// TODO(halseth): and permanently ban the peer?
|
|
|
|
case err == lnwallet.ErrInvalidLastCommitSecret:
|
|
|
|
fallthrough
|
|
|
|
|
|
|
|
// The remote sent us a commit point different from
|
|
|
|
// what they sent us before.
|
|
|
|
// TODO(halseth): ban peer?
|
|
|
|
case err == lnwallet.ErrInvalidLocalUnrevokedCommitPoint:
|
2019-09-06 14:14:40 +03:00
|
|
|
// We'll fail the link and tell the peer to
|
|
|
|
// force close the channel. Note that the
|
|
|
|
// database state is not updated here, but will
|
|
|
|
// be updated when the close transaction is
|
|
|
|
// ready to avoid that we go down before
|
|
|
|
// storing the transaction in the db.
|
2018-07-12 12:02:54 +03:00
|
|
|
l.fail(
|
|
|
|
LinkFailureError{
|
|
|
|
code: ErrSyncError,
|
|
|
|
ForceClose: true,
|
|
|
|
},
|
|
|
|
"unable to synchronize channel "+
|
|
|
|
"states: %v", err,
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
|
|
|
// We have lost state and cannot safely force close the
|
|
|
|
// channel. Fail the channel and wait for the remote to
|
|
|
|
// hopefully force close it. The remote has sent us its
|
2019-09-06 14:14:40 +03:00
|
|
|
// latest unrevoked commitment point, and we'll store
|
|
|
|
// it in the database, such that we can attempt to
|
|
|
|
// recover the funds if the remote force closes the
|
|
|
|
// channel.
|
2019-09-06 14:14:39 +03:00
|
|
|
case localDataLoss:
|
2019-09-06 14:14:40 +03:00
|
|
|
err := l.channel.MarkDataLoss(
|
|
|
|
errDataLoss.CommitPoint,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to mark channel "+
|
2019-09-06 14:14:40 +03:00
|
|
|
"data loss: %v", err)
|
|
|
|
}
|
2018-07-12 12:02:54 +03:00
|
|
|
|
|
|
|
// We determined the commit chains were not possible to
|
|
|
|
// sync. We cautiously fail the channel, but don't
|
|
|
|
// force close.
|
|
|
|
// TODO(halseth): can we safely force close in any
|
|
|
|
// cases where this error is returned?
|
|
|
|
case err == lnwallet.ErrCannotSyncCommitChains:
|
2019-09-06 14:14:40 +03:00
|
|
|
if err := l.channel.MarkBorked(); err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to mark channel "+
|
2019-09-06 14:14:40 +03:00
|
|
|
"borked: %v", err)
|
|
|
|
}
|
2018-07-12 12:02:54 +03:00
|
|
|
|
|
|
|
// Other, unspecified error.
|
|
|
|
default:
|
2018-05-02 02:29:47 +03:00
|
|
|
}
|
2018-07-12 12:02:54 +03:00
|
|
|
|
|
|
|
l.fail(
|
|
|
|
LinkFailureError{
|
2019-08-08 05:49:59 +03:00
|
|
|
code: ErrRecoveryError,
|
2018-07-12 12:02:54 +03:00
|
|
|
ForceClose: false,
|
|
|
|
},
|
|
|
|
"unable to synchronize channel "+
|
|
|
|
"states: %v", err,
|
|
|
|
)
|
2017-07-09 02:30:20 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-19 22:46:56 +03:00
|
|
|
// We've successfully reestablished the channel, mark it as such to
|
|
|
|
// allow the switch to forward HTLCs in the outbound direction.
|
|
|
|
l.markReestablished()
|
|
|
|
|
|
|
|
// Now that we've received both funding locked and channel reestablish,
|
|
|
|
// we can go ahead and send the active channel notification. We'll also
|
|
|
|
// defer the inactive notification for when the link exits to ensure
|
|
|
|
// that every active notification is matched by an inactive one.
|
|
|
|
l.cfg.NotifyActiveChannel(*l.ChannelPoint())
|
|
|
|
defer l.cfg.NotifyInactiveChannel(*l.ChannelPoint())
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// With the channel states synced, we now reset the mailbox to ensure
|
|
|
|
// we start processing all unacked packets in order. This is done here
|
|
|
|
// to ensure that all acknowledgments that occur during channel
|
2017-11-27 10:20:17 +03:00
|
|
|
// resynchronization have taken affect, causing us only to pull unacked
|
|
|
|
// packets after starting to read from the downstream mailbox.
|
|
|
|
l.mailBox.ResetPackets()
|
|
|
|
|
|
|
|
// After cleaning up any memory pertaining to incoming packets, we now
|
|
|
|
// replay our forwarding packages to handle any htlcs that can be
|
2018-08-22 04:47:52 +03:00
|
|
|
// processed locally, or need to be forwarded out to the switch. We will
|
|
|
|
// only attempt to resolve packages if our short chan id indicates that
|
|
|
|
// the channel is not pending, otherwise we should have no htlcs to
|
|
|
|
// reforward.
|
2019-08-31 00:11:38 +03:00
|
|
|
if l.ShortChanID() != hop.Source {
|
2018-08-22 04:47:52 +03:00
|
|
|
if err := l.resolveFwdPkgs(); err != nil {
|
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to resolve fwd pkgs: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-08-22 04:47:52 +03:00
|
|
|
// With our link's in-memory state fully reconstructed, spawn a
|
|
|
|
// goroutine to manage the reclamation of disk space occupied by
|
|
|
|
// completed forwarding packages.
|
|
|
|
l.wg.Add(1)
|
|
|
|
go l.fwdPkgGarbager()
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
out:
|
|
|
|
for {
|
2018-05-23 16:14:46 +03:00
|
|
|
// We must always check if we failed at some point processing
|
|
|
|
// the last update before processing the next.
|
|
|
|
if l.failed {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("link failed, exiting htlcManager")
|
2018-05-23 16:14:46 +03:00
|
|
|
break out
|
|
|
|
}
|
|
|
|
|
2019-09-24 12:49:32 +03:00
|
|
|
// If the previous event resulted in a non-empty batch, resume
|
|
|
|
// the batch ticker so that it can be cleared. Otherwise pause
|
|
|
|
// the ticker to prevent waking up the htlcManager while the
|
|
|
|
// batch is empty.
|
2019-04-10 16:28:55 +03:00
|
|
|
if l.channel.PendingLocalUpdateCount() > 0 {
|
2019-04-09 17:22:50 +03:00
|
|
|
l.cfg.BatchTicker.Resume()
|
2019-09-24 12:49:32 +03:00
|
|
|
} else {
|
|
|
|
l.cfg.BatchTicker.Pause()
|
2019-04-09 17:22:50 +03:00
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
select {
|
2018-05-11 00:40:29 +03:00
|
|
|
// Our update fee timer has fired, so we'll check the network
|
|
|
|
// fee to see if we should adjust our commitment fee.
|
|
|
|
case <-l.updateFeeTimer.C:
|
|
|
|
l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
|
2017-08-03 07:10:35 +03:00
|
|
|
|
2017-11-24 07:31:45 +03:00
|
|
|
// If we're not the initiator of the channel, don't we
|
|
|
|
// don't control the fees, so we can ignore this.
|
|
|
|
if !l.channel.IsInitiator() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we are the initiator, then we'll sample the
|
|
|
|
// current fee rate to get into the chain within 3
|
|
|
|
// blocks.
|
2019-08-24 02:04:59 +03:00
|
|
|
netFee, err := l.sampleNetworkFee()
|
2017-11-24 07:31:45 +03:00
|
|
|
if err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to sample network fee: %v",
|
|
|
|
err)
|
2017-11-24 07:31:45 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// We'll check to see if we should update the fee rate
|
2019-08-24 02:04:59 +03:00
|
|
|
// based on our current set fee rate. We'll cap the new
|
|
|
|
// fee rate to our max fee allocation.
|
2017-11-24 07:31:45 +03:00
|
|
|
commitFee := l.channel.CommitFeeRate()
|
2019-08-24 02:04:59 +03:00
|
|
|
maxFee := l.channel.MaxFeeRate(l.cfg.MaxFeeAllocation)
|
2019-10-31 05:43:05 +03:00
|
|
|
newCommitFee := chainfee.SatPerKWeight(
|
2019-08-24 02:04:59 +03:00
|
|
|
math.Min(float64(netFee), float64(maxFee)),
|
|
|
|
)
|
|
|
|
if !shouldAdjustCommitFee(newCommitFee, commitFee) {
|
2017-11-24 07:31:45 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we do, then we'll send a new UpdateFee message to
|
|
|
|
// the remote party, to be locked in with a new update.
|
2019-08-24 02:04:59 +03:00
|
|
|
if err := l.updateChannelFee(newCommitFee); err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to update fee rate: %v",
|
|
|
|
err)
|
2017-11-24 07:31:45 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// The underlying channel has notified us of a unilateral close
|
|
|
|
// carried out by the remote peer. In the case of such an
|
|
|
|
// event, we'll wipe the channel state from the peer, and mark
|
|
|
|
// the contract as fully settled. Afterwards we can exit.
|
2018-02-28 09:19:21 +03:00
|
|
|
//
|
|
|
|
// TODO(roasbeef): add force closure? also breach?
|
2018-03-16 17:19:11 +03:00
|
|
|
case <-l.cfg.ChainEvents.RemoteUnilateralClosure:
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Warnf("remote peer has closed on-chain")
|
2017-05-01 20:03:41 +03:00
|
|
|
|
2017-11-11 01:57:59 +03:00
|
|
|
// TODO(roasbeef): remove all together
|
2017-07-09 02:20:56 +03:00
|
|
|
go func() {
|
2017-11-23 10:15:21 +03:00
|
|
|
chanPoint := l.channel.ChannelPoint()
|
2018-03-13 04:52:52 +03:00
|
|
|
err := l.cfg.Peer.WipeChannel(chanPoint)
|
|
|
|
if err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to wipe channel "+
|
|
|
|
"%v", err)
|
2017-07-09 02:20:56 +03:00
|
|
|
}
|
|
|
|
}()
|
2017-06-17 00:58:02 +03:00
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
break out
|
|
|
|
|
2018-08-01 22:42:38 +03:00
|
|
|
case <-l.cfg.BatchTicker.Ticks():
|
2019-09-24 12:49:32 +03:00
|
|
|
// Attempt to extend the remote commitment chain
|
|
|
|
// including all the currently pending entries. If the
|
|
|
|
// send was unsuccessful, then abandon the update,
|
|
|
|
// waiting for the revocation window to open up.
|
2017-05-04 00:03:47 +03:00
|
|
|
if err := l.updateCommitTx(); err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to update commitment: %v", err)
|
2017-05-01 20:03:41 +03:00
|
|
|
break out
|
|
|
|
}
|
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// A packet that previously overflowed the commitment
|
|
|
|
// transaction is now eligible for processing once again. So
|
|
|
|
// we'll attempt to re-process the packet in order to allow it
|
|
|
|
// to continue propagating within the network.
|
2017-09-23 01:54:10 +03:00
|
|
|
case packet := <-l.overflowQueue.outgoingPkts:
|
2017-05-24 18:27:39 +03:00
|
|
|
msg := packet.htlc.(*lnwire.UpdateAddHTLC)
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Tracef("reprocessing downstream add update "+
|
2017-08-03 07:10:35 +03:00
|
|
|
"with payment hash(%x)", msg.PaymentHash[:])
|
2017-06-01 02:43:37 +03:00
|
|
|
|
2017-09-25 22:31:52 +03:00
|
|
|
l.handleDownStreamPkt(packet, true)
|
2017-05-24 18:27:39 +03:00
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// A message from the switch was just received. This indicates
|
|
|
|
// that the link is an intermediate hop in a multi-hop HTLC
|
|
|
|
// circuit.
|
2017-05-04 00:03:47 +03:00
|
|
|
case pkt := <-l.downstream:
|
2017-06-17 00:58:02 +03:00
|
|
|
// If we have non empty processing queue then we'll add
|
|
|
|
// this to the overflow rather than processing it
|
|
|
|
// directly. Once an active HTLC is either settled or
|
|
|
|
// failed, then we'll free up a new slot.
|
2017-05-24 18:27:39 +03:00
|
|
|
htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
|
2017-09-23 01:54:10 +03:00
|
|
|
if ok && l.overflowQueue.Length() != 0 {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Infof("downstream htlc add update with "+
|
2017-06-17 00:58:02 +03:00
|
|
|
"payment hash(%x) have been added to "+
|
2019-04-10 16:28:55 +03:00
|
|
|
"reprocessing queue, pend_updates=%v",
|
2017-06-17 00:58:02 +03:00
|
|
|
htlc.PaymentHash[:],
|
2019-04-10 16:28:55 +03:00
|
|
|
l.channel.PendingLocalUpdateCount())
|
2017-05-24 18:27:39 +03:00
|
|
|
|
2017-09-23 01:54:10 +03:00
|
|
|
l.overflowQueue.AddPkt(pkt)
|
2017-05-24 18:27:39 +03:00
|
|
|
continue
|
|
|
|
}
|
2018-03-13 04:52:52 +03:00
|
|
|
|
2017-09-25 22:31:52 +03:00
|
|
|
l.handleDownStreamPkt(pkt, false)
|
2017-05-01 20:03:41 +03:00
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// A message from the connected peer was just received. This
|
|
|
|
// indicates that we have a new incoming HTLC, either directly
|
|
|
|
// for us, or part of a multi-hop HTLC circuit.
|
2017-05-04 00:03:47 +03:00
|
|
|
case msg := <-l.upstream:
|
|
|
|
l.handleUpstreamMsg(msg)
|
|
|
|
|
2019-02-11 14:01:05 +03:00
|
|
|
// A hodl event is received. This means that we now have a
|
|
|
|
// resolution for a previously accepted htlc.
|
|
|
|
case hodlItem := <-l.hodlQueue.ChanOut():
|
|
|
|
hodlEvent := hodlItem.(invoices.HodlEvent)
|
|
|
|
err := l.processHodlQueue(hodlEvent)
|
|
|
|
if err != nil {
|
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
fmt.Sprintf("process hodl queue: %v",
|
|
|
|
err.Error()),
|
|
|
|
)
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
|
2017-05-04 00:03:47 +03:00
|
|
|
case <-l.quit:
|
2017-05-01 20:03:41 +03:00
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-11 14:01:05 +03:00
|
|
|
// processHodlQueue processes a received hodl event and continues reading from
|
|
|
|
// the hodl queue until no more events remain. When this function returns
|
|
|
|
// without an error, the commit tx should be updated.
|
|
|
|
func (l *channelLink) processHodlQueue(firstHodlEvent invoices.HodlEvent) error {
|
|
|
|
// Try to read all waiting resolution messages, so that they can all be
|
|
|
|
// processed in a single commitment tx update.
|
|
|
|
hodlEvent := firstHodlEvent
|
|
|
|
loop:
|
|
|
|
for {
|
2019-08-14 22:11:34 +03:00
|
|
|
// Lookup all hodl htlcs that can be failed or settled with this event.
|
|
|
|
// The hodl htlc must be present in the map.
|
|
|
|
circuitKey := hodlEvent.CircuitKey
|
|
|
|
hodlHtlc, ok := l.hodlMap[circuitKey]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("hodl htlc not found: %v", circuitKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := l.processHodlEvent(hodlEvent, hodlHtlc); err != nil {
|
2019-02-11 14:01:05 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-08-14 22:11:34 +03:00
|
|
|
// Clean up hodl map.
|
|
|
|
delete(l.hodlMap, circuitKey)
|
|
|
|
|
2019-02-11 14:01:05 +03:00
|
|
|
select {
|
|
|
|
case item := <-l.hodlQueue.ChanOut():
|
|
|
|
hodlEvent = item.(invoices.HodlEvent)
|
|
|
|
default:
|
|
|
|
break loop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the commitment tx.
|
|
|
|
if err := l.updateCommitTx(); err != nil {
|
|
|
|
return fmt.Errorf("unable to update commitment: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-02-20 14:11:15 +03:00
|
|
|
// processHodlEvent applies a received hodl event to the provided htlc. When
|
|
|
|
// this function returns without an error, the commit tx should be updated.
|
|
|
|
func (l *channelLink) processHodlEvent(hodlEvent invoices.HodlEvent,
|
2019-08-14 22:11:34 +03:00
|
|
|
htlc hodlHtlc) error {
|
|
|
|
|
|
|
|
circuitKey := hodlEvent.CircuitKey
|
2019-02-20 14:11:15 +03:00
|
|
|
|
|
|
|
// Determine required action for the resolution.
|
|
|
|
if hodlEvent.Preimage != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Debugf("received hodl settle event for %v", circuitKey)
|
2019-04-16 13:11:20 +03:00
|
|
|
|
2019-08-14 22:11:34 +03:00
|
|
|
return l.settleHTLC(
|
|
|
|
*hodlEvent.Preimage, htlc.pd.HtlcIndex,
|
|
|
|
htlc.pd.SourceRef,
|
|
|
|
)
|
2019-02-20 14:11:15 +03:00
|
|
|
}
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Debugf("received hodl cancel event for %v", circuitKey)
|
2019-04-09 17:22:50 +03:00
|
|
|
|
2019-08-14 22:11:34 +03:00
|
|
|
// In case of a cancel, always return
|
|
|
|
// incorrect_or_unknown_payment_details in order to avoid leaking info.
|
|
|
|
failure := lnwire.NewFailIncorrectDetails(
|
2019-06-12 13:18:58 +03:00
|
|
|
htlc.pd.Amount, uint32(hodlEvent.AcceptHeight),
|
2019-08-14 22:11:34 +03:00
|
|
|
)
|
2019-02-20 14:11:15 +03:00
|
|
|
|
2019-08-14 22:11:34 +03:00
|
|
|
l.sendHTLCError(
|
|
|
|
htlc.pd.HtlcIndex, failure, htlc.obfuscator,
|
|
|
|
htlc.pd.SourceRef,
|
|
|
|
)
|
2019-02-20 14:11:15 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-05-11 00:40:29 +03:00
|
|
|
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
|
|
|
|
// within the link's configuration that will be used to determine when the link
|
|
|
|
// should propose an update to its commitment fee rate.
|
|
|
|
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
|
|
|
|
lower := int64(l.cfg.MinFeeUpdateTimeout)
|
|
|
|
upper := int64(l.cfg.MaxFeeUpdateTimeout)
|
2018-06-30 04:22:08 +03:00
|
|
|
return time.Duration(prand.Int63n(upper-lower) + lower)
|
2018-05-11 00:40:29 +03:00
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// handleDownStreamPkt processes an HTLC packet sent from the downstream HTLC
|
|
|
|
// Switch. Possible messages sent by the switch include requests to forward new
|
|
|
|
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
|
|
|
|
// cleared HTLCs with the upstream peer.
|
2017-09-26 02:09:48 +03:00
|
|
|
//
|
|
|
|
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
|
2017-09-25 22:31:52 +03:00
|
|
|
func (l *channelLink) handleDownStreamPkt(pkt *htlcPacket, isReProcess bool) {
|
2017-05-01 20:03:41 +03:00
|
|
|
var isSettle bool
|
2017-05-04 00:03:47 +03:00
|
|
|
switch htlc := pkt.htlc.(type) {
|
2017-05-01 20:03:41 +03:00
|
|
|
case *lnwire.UpdateAddHTLC:
|
2018-04-27 12:51:13 +03:00
|
|
|
// If hodl.AddOutgoing mode is active, we exit early to simulate
|
|
|
|
// arbitrary delays between the switch adding an ADD to the
|
|
|
|
// mailbox, and the HTLC being added to the commitment state.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.AddOutgoing.Warning())
|
2018-07-27 13:21:12 +03:00
|
|
|
l.mailBox.AckPacket(pkt.inKey())
|
2018-04-27 12:51:13 +03:00
|
|
|
return
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// A new payment has been initiated via the downstream channel,
|
|
|
|
// so we add the new HTLC to our local log, then update the
|
|
|
|
// commitment chains.
|
2017-05-04 00:03:47 +03:00
|
|
|
htlc.ChanID = l.ChanID()
|
2017-11-27 10:20:17 +03:00
|
|
|
openCircuitRef := pkt.inKey()
|
|
|
|
index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
|
2017-06-29 16:40:45 +03:00
|
|
|
if err != nil {
|
|
|
|
switch err {
|
2017-07-15 06:08:29 +03:00
|
|
|
|
|
|
|
// The channels spare bandwidth is fully allocated, so
|
|
|
|
// we'll put this HTLC into the overflow queue.
|
2017-06-29 16:40:45 +03:00
|
|
|
case lnwallet.ErrMaxHTLCNumber:
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Infof("downstream htlc add update with "+
|
2017-06-29 16:40:45 +03:00
|
|
|
"payment hash(%x) have been added to "+
|
2019-04-10 16:28:55 +03:00
|
|
|
"reprocessing queue, pend_updates: %v",
|
2017-06-29 16:40:45 +03:00
|
|
|
htlc.PaymentHash[:],
|
2019-04-10 16:28:55 +03:00
|
|
|
l.channel.PendingLocalUpdateCount())
|
2017-09-25 22:31:52 +03:00
|
|
|
|
2017-09-23 01:54:10 +03:00
|
|
|
l.overflowQueue.AddPkt(pkt)
|
2017-06-29 16:40:45 +03:00
|
|
|
return
|
|
|
|
|
2017-07-15 06:08:29 +03:00
|
|
|
// The HTLC was unable to be added to the state
|
|
|
|
// machine, as a result, we'll signal the switch to
|
|
|
|
// cancel the pending payment.
|
2017-06-29 16:40:45 +03:00
|
|
|
default:
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Warnf("unable to handle downstream add "+
|
2019-10-01 12:06:56 +03:00
|
|
|
"HTLC: %v", err)
|
2017-12-05 04:28:16 +03:00
|
|
|
|
2017-06-29 16:40:45 +03:00
|
|
|
var (
|
2017-12-05 04:28:16 +03:00
|
|
|
localFailure = false
|
2017-06-29 16:40:45 +03:00
|
|
|
reason lnwire.OpaqueReason
|
|
|
|
)
|
|
|
|
|
2019-09-27 17:01:18 +03:00
|
|
|
failure := l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewTemporaryChannelFailure(
|
|
|
|
upd,
|
|
|
|
)
|
|
|
|
},
|
2018-05-08 06:00:32 +03:00
|
|
|
)
|
2017-07-15 06:08:29 +03:00
|
|
|
|
2018-05-08 06:00:32 +03:00
|
|
|
// Encrypt the error back to the source unless
|
|
|
|
// the payment was generated locally.
|
2017-12-05 04:28:16 +03:00
|
|
|
if pkt.obfuscator == nil {
|
2017-06-29 16:40:45 +03:00
|
|
|
var b bytes.Buffer
|
|
|
|
err := lnwire.EncodeFailure(&b, failure, 0)
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to encode failure: %v", err)
|
2018-07-27 13:21:12 +03:00
|
|
|
l.mailBox.AckPacket(pkt.inKey())
|
2017-06-29 16:40:45 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
reason = lnwire.OpaqueReason(b.Bytes())
|
2017-12-05 04:28:16 +03:00
|
|
|
localFailure = true
|
|
|
|
} else {
|
|
|
|
var err error
|
|
|
|
reason, err = pkt.obfuscator.EncryptFirstHop(failure)
|
2017-06-29 16:40:45 +03:00
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to obfuscate error: %v", err)
|
2018-07-27 13:21:12 +03:00
|
|
|
l.mailBox.AckPacket(pkt.inKey())
|
2017-06-29 16:40:45 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-24 09:18:26 +03:00
|
|
|
failPkt := &htlcPacket{
|
2017-10-30 21:56:51 +03:00
|
|
|
incomingChanID: pkt.incomingChanID,
|
|
|
|
incomingHTLCID: pkt.incomingHTLCID,
|
2017-11-27 10:20:17 +03:00
|
|
|
circuit: pkt.circuit,
|
|
|
|
sourceRef: pkt.sourceRef,
|
|
|
|
hasSource: true,
|
2017-12-05 04:28:16 +03:00
|
|
|
localFailure: localFailure,
|
2017-10-24 09:18:26 +03:00
|
|
|
htlc: &lnwire.UpdateFailHTLC{
|
|
|
|
Reason: reason,
|
|
|
|
},
|
2017-07-15 06:08:29 +03:00
|
|
|
}
|
2017-06-29 16:40:45 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
go l.forwardBatch(failPkt)
|
|
|
|
|
|
|
|
// Remove this packet from the link's mailbox,
|
|
|
|
// this prevents it from being reprocessed if
|
|
|
|
// the link restarts and resets it mailbox. If
|
|
|
|
// this response doesn't make it back to the
|
|
|
|
// originating link, it will be rejected upon
|
|
|
|
// attempting to reforward the Add to the
|
|
|
|
// switch, since the circuit was never fully
|
|
|
|
// opened, and the forwarding package shows it
|
|
|
|
// as unacknowledged.
|
|
|
|
l.mailBox.AckPacket(pkt.inKey())
|
|
|
|
|
2017-06-29 16:40:45 +03:00
|
|
|
return
|
|
|
|
}
|
2017-05-01 20:03:41 +03:00
|
|
|
}
|
2017-06-17 00:58:02 +03:00
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Tracef("received downstream htlc: payment_hash=%x, "+
|
2019-04-10 16:28:55 +03:00
|
|
|
"local_log_index=%v, pend_updates=%v",
|
|
|
|
htlc.PaymentHash[:], index,
|
|
|
|
l.channel.PendingLocalUpdateCount())
|
2017-06-17 00:58:02 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
pkt.outgoingChanID = l.ShortChanID()
|
|
|
|
pkt.outgoingHTLCID = index
|
2017-05-04 00:03:47 +03:00
|
|
|
htlc.ID = index
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Debugf("queueing keystone of ADD open circuit: %s->%s",
|
2017-11-27 10:20:17 +03:00
|
|
|
pkt.inKey(), pkt.outKey())
|
|
|
|
|
|
|
|
l.openedCircuits = append(l.openedCircuits, pkt.inKey())
|
|
|
|
l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
|
|
|
|
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, htlc)
|
2017-05-01 20:03:41 +03:00
|
|
|
|
2018-02-07 06:11:11 +03:00
|
|
|
case *lnwire.UpdateFulfillHTLC:
|
2018-04-27 12:51:13 +03:00
|
|
|
// If hodl.SettleOutgoing mode is active, we exit early to
|
|
|
|
// simulate arbitrary delays between the switch adding the
|
|
|
|
// SETTLE to the mailbox, and the HTLC being added to the
|
|
|
|
// commitment state.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.SettleOutgoing.Warning())
|
2018-07-27 13:21:12 +03:00
|
|
|
l.mailBox.AckPacket(pkt.inKey())
|
2018-04-27 12:51:13 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// An HTLC we forward to the switch has just settled somewhere
|
|
|
|
// upstream. Therefore we settle the HTLC within the our local
|
|
|
|
// state machine.
|
2018-07-27 13:21:12 +03:00
|
|
|
inKey := pkt.inKey()
|
|
|
|
err := l.channel.SettleHTLC(
|
2018-02-24 09:40:55 +03:00
|
|
|
htlc.PaymentPreimage,
|
|
|
|
pkt.incomingHTLCID,
|
2017-11-27 10:20:17 +03:00
|
|
|
pkt.sourceRef,
|
|
|
|
pkt.destRef,
|
2018-07-27 13:21:12 +03:00
|
|
|
&inKey,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to settle incoming HTLC for "+
|
2018-07-27 13:21:12 +03:00
|
|
|
"circuit-key=%v: %v", inKey, err)
|
|
|
|
|
|
|
|
// If the HTLC index for Settle response was not known
|
|
|
|
// to our commitment state, it has already been
|
|
|
|
// cleaned up by a prior response. We'll thus try to
|
|
|
|
// clean up any lingering state to ensure we don't
|
|
|
|
// continue reforwarding.
|
|
|
|
if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
|
|
|
|
l.cleanupSpuriousResponse(pkt)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove the packet from the link's mailbox to ensure
|
|
|
|
// it doesn't get replayed after a reconnection.
|
|
|
|
l.mailBox.AckPacket(inKey)
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Debugf("queueing removal of SETTLE closed circuit: "+
|
2019-10-01 12:06:56 +03:00
|
|
|
"%s->%s", pkt.inKey(), pkt.outKey())
|
2017-11-27 10:20:17 +03:00
|
|
|
|
|
|
|
l.closedCircuits = append(l.closedCircuits, pkt.inKey())
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// With the HTLC settled, we'll need to populate the wire
|
|
|
|
// message to target the specific channel and HTLC to be
|
2019-10-03 18:22:43 +03:00
|
|
|
// canceled.
|
2017-05-04 00:03:47 +03:00
|
|
|
htlc.ChanID = l.ChanID()
|
2017-10-30 21:56:51 +03:00
|
|
|
htlc.ID = pkt.incomingHTLCID
|
2017-05-01 20:03:41 +03:00
|
|
|
|
|
|
|
// Then we send the HTLC settle message to the connected peer
|
|
|
|
// so we can continue the propagation of the settle message.
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, htlc)
|
2017-05-01 20:03:41 +03:00
|
|
|
isSettle = true
|
|
|
|
|
|
|
|
case *lnwire.UpdateFailHTLC:
|
2018-04-27 12:51:13 +03:00
|
|
|
// If hodl.FailOutgoing mode is active, we exit early to
|
|
|
|
// simulate arbitrary delays between the switch adding a FAIL to
|
|
|
|
// the mailbox, and the HTLC being added to the commitment
|
|
|
|
// state.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.FailOutgoing.Warning())
|
2018-07-27 13:21:12 +03:00
|
|
|
l.mailBox.AckPacket(pkt.inKey())
|
2018-04-27 12:51:13 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// An HTLC cancellation has been triggered somewhere upstream,
|
|
|
|
// we'll remove then HTLC from our local state machine.
|
2018-07-27 13:21:12 +03:00
|
|
|
inKey := pkt.inKey()
|
|
|
|
err := l.channel.FailHTLC(
|
2018-02-24 09:40:55 +03:00
|
|
|
pkt.incomingHTLCID,
|
|
|
|
htlc.Reason,
|
2017-11-27 10:20:17 +03:00
|
|
|
pkt.sourceRef,
|
|
|
|
pkt.destRef,
|
2018-07-27 13:21:12 +03:00
|
|
|
&inKey,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to cancel incoming HTLC for "+
|
2018-07-27 13:21:12 +03:00
|
|
|
"circuit-key=%v: %v", inKey, err)
|
|
|
|
|
|
|
|
// If the HTLC index for Fail response was not known to
|
|
|
|
// our commitment state, it has already been cleaned up
|
|
|
|
// by a prior response. We'll thus try to clean up any
|
|
|
|
// lingering state to ensure we don't continue
|
|
|
|
// reforwarding.
|
|
|
|
if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
|
|
|
|
l.cleanupSpuriousResponse(pkt)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove the packet from the link's mailbox to ensure
|
|
|
|
// it doesn't get replayed after a reconnection.
|
|
|
|
l.mailBox.AckPacket(inKey)
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Debugf("queueing removal of FAIL closed circuit: %s->%s",
|
2017-11-27 10:20:17 +03:00
|
|
|
pkt.inKey(), pkt.outKey())
|
|
|
|
|
|
|
|
l.closedCircuits = append(l.closedCircuits, pkt.inKey())
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// With the HTLC removed, we'll need to populate the wire
|
|
|
|
// message to target the specific channel and HTLC to be
|
2019-10-03 18:22:43 +03:00
|
|
|
// canceled. The "Reason" field will have already been set
|
2017-05-01 20:03:41 +03:00
|
|
|
// within the switch.
|
2017-05-04 00:03:47 +03:00
|
|
|
htlc.ChanID = l.ChanID()
|
2017-10-30 21:56:51 +03:00
|
|
|
htlc.ID = pkt.incomingHTLCID
|
2017-05-01 20:03:41 +03:00
|
|
|
|
|
|
|
// Finally, we send the HTLC message to the peer which
|
|
|
|
// initially created the HTLC.
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, htlc)
|
2017-05-01 20:03:41 +03:00
|
|
|
isSettle = true
|
|
|
|
}
|
|
|
|
|
|
|
|
// If this newly added update exceeds the min batch size for adds, or
|
|
|
|
// this is a settle request, then initiate an update.
|
2019-04-10 16:28:55 +03:00
|
|
|
if l.channel.PendingLocalUpdateCount() >= uint64(l.cfg.BatchSize) ||
|
|
|
|
isSettle {
|
|
|
|
|
2017-05-04 00:03:47 +03:00
|
|
|
if err := l.updateCommitTx(); err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to update commitment: %v", err)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-27 13:21:12 +03:00
|
|
|
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
|
|
|
|
// associated with this packet. If successful in doing so, it will also purge
|
|
|
|
// the open circuit from the circuit map and remove the packet from the link's
|
|
|
|
// mailbox.
|
|
|
|
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
|
|
|
|
inKey := pkt.inKey()
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Debugf("cleaning up spurious response for incoming "+
|
2019-10-01 12:06:56 +03:00
|
|
|
"circuit-key=%v", inKey)
|
2018-07-27 13:21:12 +03:00
|
|
|
|
|
|
|
// If the htlc packet doesn't have a source reference, it is unsafe to
|
|
|
|
// proceed, as skipping this ack may cause the htlc to be reforwarded.
|
|
|
|
if pkt.sourceRef == nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("uanble to cleanup response for incoming "+
|
2018-07-27 13:21:12 +03:00
|
|
|
"circuit-key=%v, does not contain source reference",
|
|
|
|
inKey)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the source reference is present, we will try to prevent this link
|
|
|
|
// from resending the packet to the switch. To do so, we ack the AddRef
|
|
|
|
// of the incoming HTLC belonging to this link.
|
|
|
|
err := l.channel.AckAddHtlcs(*pkt.sourceRef)
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to ack AddRef for incoming "+
|
2018-07-27 13:21:12 +03:00
|
|
|
"circuit-key=%v: %v", inKey, err)
|
|
|
|
|
|
|
|
// If this operation failed, it is unsafe to attempt removal of
|
|
|
|
// the destination reference or circuit, so we exit early. The
|
|
|
|
// cleanup may proceed with a different packet in the future
|
|
|
|
// that succeeds on this step.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that we know this link will stop retransmitting Adds to the
|
|
|
|
// switch, we can begin to teardown the response reference and circuit
|
|
|
|
// map.
|
|
|
|
//
|
|
|
|
// If the packet includes a destination reference, then a response for
|
|
|
|
// this HTLC was locked into the outgoing channel. Attempt to remove
|
|
|
|
// this reference, so we stop retransmitting the response internally.
|
|
|
|
// Even if this fails, we will proceed in trying to delete the circuit.
|
|
|
|
// When retransmitting responses, the destination references will be
|
|
|
|
// cleaned up if an open circuit is not found in the circuit map.
|
|
|
|
if pkt.destRef != nil {
|
|
|
|
err := l.channel.AckSettleFails(*pkt.destRef)
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to ack SettleFailRef "+
|
2018-07-27 13:21:12 +03:00
|
|
|
"for incoming circuit-key=%v: %v",
|
|
|
|
inKey, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Debugf("deleting circuit for incoming circuit-key=%x", inKey)
|
2018-07-27 13:21:12 +03:00
|
|
|
|
|
|
|
// With all known references acked, we can now safely delete the circuit
|
|
|
|
// from the switch's circuit map, as the state is no longer needed.
|
|
|
|
err = l.cfg.Circuits.DeleteCircuits(inKey)
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to delete circuit for "+
|
2018-07-27 13:21:12 +03:00
|
|
|
"circuit-key=%v: %v", inKey, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// handleUpstreamMsg processes wire messages related to commitment state
|
|
|
|
// updates from the upstream peer. The upstream peer is the peer whom we have a
|
|
|
|
// direct channel with, updating our respective commitment chains.
|
2017-05-04 00:03:47 +03:00
|
|
|
func (l *channelLink) handleUpstreamMsg(msg lnwire.Message) {
|
|
|
|
switch msg := msg.(type) {
|
2017-07-09 02:30:20 +03:00
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
case *lnwire.UpdateAddHTLC:
|
|
|
|
// We just received an add request from an upstream peer, so we
|
|
|
|
// add it to our state machine, then add the HTLC to our
|
2017-06-01 02:43:37 +03:00
|
|
|
// "settle" list in the event that we know the preimage.
|
2017-05-04 00:03:47 +03:00
|
|
|
index, err := l.channel.ReceiveHTLC(msg)
|
2017-05-01 20:03:41 +03:00
|
|
|
if err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInvalidUpdate},
|
|
|
|
"unable to handle upstream add HTLC: %v", err)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
2017-11-11 01:57:59 +03:00
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Tracef("receive upstream htlc with payment hash(%x), "+
|
2017-06-17 00:58:02 +03:00
|
|
|
"assigning index: %v", msg.PaymentHash[:], index)
|
2017-05-01 20:03:41 +03:00
|
|
|
|
2018-02-07 06:11:11 +03:00
|
|
|
case *lnwire.UpdateFulfillHTLC:
|
2017-05-04 00:03:47 +03:00
|
|
|
pre := msg.PaymentPreimage
|
|
|
|
idx := msg.ID
|
|
|
|
if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(
|
|
|
|
LinkFailureError{
|
|
|
|
code: ErrInvalidUpdate,
|
|
|
|
ForceClose: true,
|
|
|
|
},
|
|
|
|
"unable to handle upstream settle HTLC: %v", err,
|
|
|
|
)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-30 19:26:24 +03:00
|
|
|
settlePacket := &htlcPacket{
|
|
|
|
outgoingChanID: l.ShortChanID(),
|
|
|
|
outgoingHTLCID: idx,
|
|
|
|
htlc: &lnwire.UpdateFulfillHTLC{
|
|
|
|
PaymentPreimage: pre,
|
|
|
|
},
|
|
|
|
}
|
2018-01-17 07:13:16 +03:00
|
|
|
|
2019-02-20 04:06:15 +03:00
|
|
|
// Add the newly discovered preimage to our growing list of
|
|
|
|
// uncommitted preimage. These will be written to the witness
|
|
|
|
// cache just before accepting the next commitment signature
|
|
|
|
// from the remote peer.
|
|
|
|
l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
|
2017-06-29 16:40:45 +03:00
|
|
|
|
2019-05-30 19:26:24 +03:00
|
|
|
// Pipeline this settle, send it to the switch.
|
|
|
|
go l.forwardBatch(settlePacket)
|
|
|
|
|
2017-06-29 16:40:45 +03:00
|
|
|
case *lnwire.UpdateFailMalformedHTLC:
|
2017-07-15 06:08:29 +03:00
|
|
|
// Convert the failure type encoded within the HTLC fail
|
|
|
|
// message to the proper generic lnwire error code.
|
2017-06-29 16:40:45 +03:00
|
|
|
var failure lnwire.FailureMessage
|
|
|
|
switch msg.FailureCode {
|
|
|
|
case lnwire.CodeInvalidOnionVersion:
|
|
|
|
failure = &lnwire.FailInvalidOnionVersion{
|
|
|
|
OnionSHA256: msg.ShaOnionBlob,
|
|
|
|
}
|
|
|
|
case lnwire.CodeInvalidOnionHmac:
|
|
|
|
failure = &lnwire.FailInvalidOnionHmac{
|
|
|
|
OnionSHA256: msg.ShaOnionBlob,
|
|
|
|
}
|
|
|
|
|
|
|
|
case lnwire.CodeInvalidOnionKey:
|
|
|
|
failure = &lnwire.FailInvalidOnionKey{
|
|
|
|
OnionSHA256: msg.ShaOnionBlob,
|
|
|
|
}
|
|
|
|
default:
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Warnf("unexpected failure code received in "+
|
2019-08-16 20:46:51 +03:00
|
|
|
"UpdateFailMailformedHTLC: %v", msg.FailureCode)
|
|
|
|
|
|
|
|
// We don't just pass back the error we received from
|
|
|
|
// our successor. Otherwise we might report a failure
|
|
|
|
// that penalizes us more than needed. If the onion that
|
|
|
|
// we forwarded was correct, the node should have been
|
|
|
|
// able to send back its own failure. The node did not
|
|
|
|
// send back its own failure, so we assume there was a
|
|
|
|
// problem with the onion and report that back. We reuse
|
|
|
|
// the invalid onion key failure because there is no
|
|
|
|
// specific error for this case.
|
|
|
|
failure = &lnwire.FailInvalidOnionKey{
|
|
|
|
OnionSHA256: msg.ShaOnionBlob,
|
|
|
|
}
|
2017-06-29 16:40:45 +03:00
|
|
|
}
|
|
|
|
|
2017-07-15 06:08:29 +03:00
|
|
|
// With the error parsed, we'll convert the into it's opaque
|
|
|
|
// form.
|
2017-06-29 16:40:45 +03:00
|
|
|
var b bytes.Buffer
|
|
|
|
if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to encode malformed error: %v", err)
|
2017-06-29 16:40:45 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-10 13:48:43 +03:00
|
|
|
// If remote side have been unable to parse the onion blob we
|
|
|
|
// have sent to it, than we should transform the malformed HTLC
|
|
|
|
// message to the usual HTLC fail message.
|
2017-10-24 10:48:52 +03:00
|
|
|
err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
|
2017-07-10 13:48:43 +03:00
|
|
|
if err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInvalidUpdate},
|
|
|
|
"unable to handle upstream fail HTLC: %v", err)
|
2017-07-10 13:48:43 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
case *lnwire.UpdateFailHTLC:
|
2017-05-04 00:03:47 +03:00
|
|
|
idx := msg.ID
|
2017-10-24 10:48:52 +03:00
|
|
|
err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
|
2017-09-25 22:31:52 +03:00
|
|
|
if err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInvalidUpdate},
|
|
|
|
"unable to handle upstream fail HTLC: %v", err)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
case *lnwire.CommitSig:
|
2019-02-20 04:06:15 +03:00
|
|
|
// Since we may have learned new preimages for the first time,
|
|
|
|
// we'll add them to our preimage cache. By doing this, we
|
|
|
|
// ensure any contested contracts watched by any on-chain
|
|
|
|
// arbitrators can now sweep this HTLC on-chain. We delay
|
|
|
|
// committing the preimages until just before accepting the new
|
|
|
|
// remote commitment, as afterwards the peer won't resend the
|
|
|
|
// Settle messages on the next channel reestablishment. Doing so
|
|
|
|
// allows us to more effectively batch this operation, instead
|
|
|
|
// of doing a single write per preimage.
|
|
|
|
err := l.cfg.PreimageCache.AddPreimages(
|
|
|
|
l.uncommittedPreimages...,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
l.fail(
|
|
|
|
LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to add preimages=%v to cache: %v",
|
|
|
|
l.uncommittedPreimages, err,
|
|
|
|
)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Instead of truncating the slice to conserve memory
|
|
|
|
// allocations, we simply set the uncommitted preimage slice to
|
|
|
|
// nil so that a new one will be initialized if any more
|
|
|
|
// witnesses are discovered. We do this maximum size of the
|
|
|
|
// slice can occupy 15KB, and want to ensure we release that
|
|
|
|
// memory back to the runtime.
|
|
|
|
l.uncommittedPreimages = nil
|
|
|
|
|
2018-01-09 05:56:52 +03:00
|
|
|
// We just received a new updates to our local commitment
|
|
|
|
// chain, validate this new commitment, closing the link if
|
|
|
|
// invalid.
|
2019-02-20 04:06:15 +03:00
|
|
|
err = l.channel.ReceiveNewCommitment(msg.CommitSig, msg.HtlcSigs)
|
2017-07-31 00:08:25 +03:00
|
|
|
if err != nil {
|
2018-01-09 05:56:52 +03:00
|
|
|
// If we were unable to reconstruct their proposed
|
|
|
|
// commitment, then we'll examine the type of error. If
|
|
|
|
// it's an InvalidCommitSigError, then we'll send a
|
|
|
|
// direct error.
|
2018-05-09 16:49:58 +03:00
|
|
|
var sendData []byte
|
2018-04-05 03:41:40 +03:00
|
|
|
switch err.(type) {
|
|
|
|
case *lnwallet.InvalidCommitSigError:
|
2018-05-09 16:49:58 +03:00
|
|
|
sendData = []byte(err.Error())
|
2018-04-05 03:41:40 +03:00
|
|
|
case *lnwallet.InvalidHtlcSigError:
|
2018-05-09 16:49:58 +03:00
|
|
|
sendData = []byte(err.Error())
|
2018-01-09 05:56:52 +03:00
|
|
|
}
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(
|
|
|
|
LinkFailureError{
|
|
|
|
code: ErrInvalidCommitment,
|
|
|
|
ForceClose: true,
|
|
|
|
SendData: sendData,
|
|
|
|
},
|
|
|
|
"ChannelPoint(%v): unable to accept new "+
|
|
|
|
"commitment: %v",
|
|
|
|
l.channel.ChannelPoint(), err,
|
|
|
|
)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-04-18 05:03:27 +03:00
|
|
|
// As we've just accepted a new state, we'll now
|
2017-05-01 20:03:41 +03:00
|
|
|
// immediately send the remote peer a revocation for our prior
|
|
|
|
// state.
|
2018-01-17 07:13:16 +03:00
|
|
|
nextRevocation, currentHtlcs, err := l.channel.RevokeCurrentCommitment()
|
2017-05-01 20:03:41 +03:00
|
|
|
if err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to revoke commitment: %v", err)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, nextRevocation)
|
2017-05-01 20:03:41 +03:00
|
|
|
|
2018-01-17 07:15:08 +03:00
|
|
|
// Since we just revoked our commitment, we may have a new set
|
|
|
|
// of HTLC's on our commitment, so we'll send them over our
|
|
|
|
// HTLC update channel so any callers can be notified.
|
|
|
|
select {
|
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-17 03:23:26 +03:00
|
|
|
case l.htlcUpdates <- &contractcourt.ContractUpdate{
|
|
|
|
HtlcKey: contractcourt.LocalHtlcSet,
|
|
|
|
Htlcs: currentHtlcs,
|
|
|
|
}:
|
2018-01-17 07:15:08 +03:00
|
|
|
case <-l.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// If both commitment chains are fully synced from our PoV,
|
|
|
|
// then we don't need to reply with a signature as both sides
|
2018-04-05 03:38:23 +03:00
|
|
|
// already have a commitment with the latest accepted.
|
2019-09-23 15:27:06 +03:00
|
|
|
if !l.channel.OweCommitment(true) {
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, the remote party initiated the state transition,
|
|
|
|
// so we'll reply with a signature to provide them with their
|
2017-11-11 01:57:59 +03:00
|
|
|
// version of the latest commitment.
|
2017-05-04 00:03:47 +03:00
|
|
|
if err := l.updateCommitTx(); err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to update commitment: %v", err)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
case *lnwire.RevokeAndAck:
|
|
|
|
// We've received a revocation from the remote chain, if valid,
|
|
|
|
// this moves the remote chain forward, and expands our
|
|
|
|
// revocation window.
|
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-17 03:23:26 +03:00
|
|
|
fwdPkg, adds, settleFails, remoteHTLCs, err := l.channel.ReceiveRevocation(
|
|
|
|
msg,
|
|
|
|
)
|
2017-05-01 20:03:41 +03:00
|
|
|
if err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
// TODO(halseth): force close?
|
|
|
|
l.fail(LinkFailureError{code: ErrInvalidRevocation},
|
|
|
|
"unable to accept revocation: %v", err)
|
2017-05-01 20:03:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
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-17 03:23:26 +03:00
|
|
|
// The remote party now has a new primary commitment, so we'll
|
|
|
|
// update the contract court to be aware of this new set (the
|
|
|
|
// prior old remote pending).
|
|
|
|
select {
|
|
|
|
case l.htlcUpdates <- &contractcourt.ContractUpdate{
|
|
|
|
HtlcKey: contractcourt.RemoteHtlcSet,
|
|
|
|
Htlcs: remoteHTLCs,
|
|
|
|
}:
|
|
|
|
case <-l.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-06-14 03:28:14 +03:00
|
|
|
// If we have a tower client, we'll proceed in backing up the
|
|
|
|
// state that was just revoked.
|
|
|
|
if l.cfg.TowerClient != nil {
|
|
|
|
state := l.channel.State()
|
|
|
|
breachInfo, err := lnwallet.NewBreachRetribution(
|
|
|
|
state, state.RemoteCommitment.CommitHeight-1, 0,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"failed to load breach info: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-08-08 05:49:59 +03:00
|
|
|
chanType := l.channel.State().ChanType
|
2019-06-14 03:28:14 +03:00
|
|
|
chanID := l.ChanID()
|
2019-08-08 05:49:59 +03:00
|
|
|
err = l.cfg.TowerClient.BackupState(
|
2019-10-31 05:24:49 +03:00
|
|
|
&chanID, breachInfo, chanType.IsTweakless(),
|
2019-08-08 05:49:59 +03:00
|
|
|
)
|
2019-06-14 03:28:14 +03:00
|
|
|
if err != nil {
|
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to queue breach backup: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
l.processRemoteSettleFails(fwdPkg, settleFails)
|
2019-04-10 14:10:25 +03:00
|
|
|
l.processRemoteAdds(fwdPkg, adds)
|
2018-05-23 16:14:46 +03:00
|
|
|
|
|
|
|
// If the link failed during processing the adds, we must
|
|
|
|
// return to ensure we won't attempted to update the state
|
|
|
|
// further.
|
|
|
|
if l.failed {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-04-10 17:05:09 +03:00
|
|
|
// The revocation window opened up. If there are pending local
|
|
|
|
// updates, try to update the commit tx. Pending updates could
|
|
|
|
// already have been present because of a previously failed
|
|
|
|
// update to the commit tx or freshly added in by
|
|
|
|
// processRemoteAdds. Also in case there are no local updates,
|
|
|
|
// but there are still remote updates that are not in the remote
|
|
|
|
// commit tx yet, send out an update.
|
|
|
|
if l.channel.OweCommitment(true) {
|
2017-11-27 10:20:17 +03:00
|
|
|
if err := l.updateCommitTx(); err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to update commitment: %v", err)
|
2017-11-27 10:20:17 +03:00
|
|
|
return
|
2017-05-01 20:03:41 +03:00
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
2017-08-15 20:09:16 +03:00
|
|
|
|
2017-07-14 21:40:42 +03:00
|
|
|
case *lnwire.UpdateFee:
|
2017-11-11 01:57:59 +03:00
|
|
|
// We received fee update from peer. If we are the initiator we
|
2017-08-03 07:10:35 +03:00
|
|
|
// will fail the channel, if not we will apply the update.
|
2019-10-31 05:43:05 +03:00
|
|
|
fee := chainfee.SatPerKWeight(msg.FeePerKw)
|
2017-07-14 21:40:42 +03:00
|
|
|
if err := l.channel.ReceiveUpdateFee(fee); err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInvalidUpdate},
|
|
|
|
"error receiving fee update: %v", err)
|
2017-07-14 21:40:42 +03:00
|
|
|
return
|
|
|
|
}
|
2018-03-01 02:39:26 +03:00
|
|
|
case *lnwire.Error:
|
|
|
|
// Error received from remote, MUST fail channel, but should
|
|
|
|
// only print the contents of the error message if all
|
|
|
|
// characters are printable ASCII.
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrRemoteError},
|
|
|
|
"ChannelPoint(%v): received error from peer: %v",
|
2019-09-20 11:55:21 +03:00
|
|
|
l.channel.ChannelPoint(), msg.Error())
|
2018-03-01 02:39:26 +03:00
|
|
|
default:
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Warnf("received unknown message of type %T", msg)
|
2017-05-01 20:03:41 +03:00
|
|
|
}
|
2018-03-01 02:39:26 +03:00
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
}
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
|
|
|
|
// for packets delivered from server, and cleaning up any circuits closed by
|
|
|
|
// signing a previous commitment txn. This method ensures that the circuits are
|
|
|
|
// removed from the circuit map before removing them from the link's mailbox,
|
|
|
|
// otherwise it could be possible for some circuit to be missed if this link
|
|
|
|
// flaps.
|
2018-08-19 05:35:20 +03:00
|
|
|
func (l *channelLink) ackDownStreamPackets() error {
|
2017-11-27 10:20:17 +03:00
|
|
|
// First, remove the downstream Add packets that were included in the
|
|
|
|
// previous commitment signature. This will prevent the Adds from being
|
|
|
|
// replayed if this link disconnects.
|
|
|
|
for _, inKey := range l.openedCircuits {
|
2018-03-13 04:52:52 +03:00
|
|
|
// In order to test the sphinx replay logic of the remote
|
|
|
|
// party, unsafe replay does not acknowledge the packets from
|
|
|
|
// the mailbox. We can then force a replay of any Add packets
|
|
|
|
// held in memory by disconnecting and reconnecting the link.
|
2017-11-27 10:20:17 +03:00
|
|
|
if l.cfg.UnsafeReplay {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Debugf("removing Add packet %s from mailbox", inKey)
|
2017-11-27 10:20:17 +03:00
|
|
|
l.mailBox.AckPacket(inKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now, we will delete all circuits closed by the previous commitment
|
|
|
|
// signature, which is the result of downstream Settle/Fail packets. We
|
|
|
|
// batch them here to ensure circuits are closed atomically and for
|
|
|
|
// performance.
|
|
|
|
err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
|
|
|
|
switch err {
|
|
|
|
case nil:
|
|
|
|
// Successful deletion.
|
|
|
|
|
|
|
|
default:
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to delete %d circuits: %v",
|
2017-11-27 10:20:17 +03:00
|
|
|
len(l.closedCircuits), err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// With the circuits removed from memory and disk, we now ack any
|
|
|
|
// Settle/Fails in the mailbox to ensure they do not get redelivered
|
|
|
|
// after startup. If forgive is enabled and we've reached this point,
|
|
|
|
// the circuits must have been removed at some point, so it is now safe
|
2018-03-13 04:52:52 +03:00
|
|
|
// to un-queue the corresponding Settle/Fails.
|
2017-11-27 10:20:17 +03:00
|
|
|
for _, inKey := range l.closedCircuits {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Debugf("removing Fail/Settle packet %s from mailbox",
|
|
|
|
inKey)
|
2017-11-27 10:20:17 +03:00
|
|
|
l.mailBox.AckPacket(inKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lastly, reset our buffers to be empty while keeping any acquired
|
|
|
|
// growth in the backing array.
|
|
|
|
l.openedCircuits = l.openedCircuits[:0]
|
|
|
|
l.closedCircuits = l.closedCircuits[:0]
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
// updateCommitTx signs, then sends an update to the remote peer adding a new
|
|
|
|
// commitment to their commitment chain which includes all the latest updates
|
|
|
|
// we've received+processed up to this point.
|
2017-05-04 00:03:47 +03:00
|
|
|
func (l *channelLink) updateCommitTx() error {
|
2017-11-27 10:20:17 +03:00
|
|
|
// Preemptively write all pending keystones to disk, just in case the
|
|
|
|
// HTLCs we have in memory are included in the subsequent attempt to
|
|
|
|
// sign a commitment state.
|
|
|
|
err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset the batch, but keep the backing buffer to avoid reallocating.
|
|
|
|
l.keystoneBatch = l.keystoneBatch[:0]
|
|
|
|
|
2018-04-27 12:51:13 +03:00
|
|
|
// If hodl.Commit mode is active, we will refrain from attempting to
|
|
|
|
// commit any in-memory modifications to the channel state. Exiting here
|
|
|
|
// permits testing of either the switch or link's ability to trim
|
|
|
|
// circuits that have been opened, but unsuccessfully committed.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.Commit) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.Commit.Warning())
|
2018-04-27 12:51:13 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
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-17 03:23:26 +03:00
|
|
|
theirCommitSig, htlcSigs, pendingHTLCs, err := l.channel.SignNextCommitment()
|
2017-05-01 20:03:41 +03:00
|
|
|
if err == lnwallet.ErrNoWindow {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Tracef("revocation window exhausted, unable to send: "+
|
2019-04-10 16:28:55 +03:00
|
|
|
"%v, pend_updates=%v, dangling_closes%v",
|
|
|
|
l.channel.PendingLocalUpdateCount(),
|
|
|
|
newLogClosure(func() string {
|
2018-07-01 01:14:59 +03:00
|
|
|
return spew.Sdump(l.openedCircuits)
|
|
|
|
}),
|
|
|
|
newLogClosure(func() string {
|
|
|
|
return spew.Sdump(l.closedCircuits)
|
|
|
|
}),
|
|
|
|
)
|
2017-05-01 20:03:41 +03:00
|
|
|
return nil
|
|
|
|
} else if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
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-17 03:23:26 +03:00
|
|
|
// The remote party now has a new pending commitment, so we'll update
|
|
|
|
// the contract court to be aware of this new set (the prior old remote
|
|
|
|
// pending).
|
|
|
|
select {
|
|
|
|
case l.htlcUpdates <- &contractcourt.ContractUpdate{
|
|
|
|
HtlcKey: contractcourt.RemotePendingHtlcSet,
|
|
|
|
Htlcs: pendingHTLCs,
|
|
|
|
}:
|
|
|
|
case <-l.quit:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-08-19 05:35:20 +03:00
|
|
|
if err := l.ackDownStreamPackets(); err != nil {
|
2017-11-27 10:20:17 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-05-01 20:03:41 +03:00
|
|
|
commitSig := &lnwire.CommitSig{
|
2017-05-04 00:03:47 +03:00
|
|
|
ChanID: l.ChanID(),
|
2017-07-31 00:08:25 +03:00
|
|
|
CommitSig: theirCommitSig,
|
|
|
|
HtlcSigs: htlcSigs,
|
2017-05-01 20:03:41 +03:00
|
|
|
}
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, commitSig)
|
2017-05-01 20:03:41 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// Peer returns the representation of remote peer with which we have the
|
|
|
|
// channel link opened.
|
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
2018-06-08 06:17:15 +03:00
|
|
|
func (l *channelLink) Peer() lnpeer.Peer {
|
2017-05-03 17:07:55 +03:00
|
|
|
return l.cfg.Peer
|
|
|
|
}
|
|
|
|
|
2018-10-30 12:36:27 +03:00
|
|
|
// ChannelPoint returns the channel outpoint for the channel link.
|
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) ChannelPoint() *wire.OutPoint {
|
|
|
|
return l.channel.ChannelPoint()
|
|
|
|
}
|
|
|
|
|
2017-06-17 00:32:41 +03:00
|
|
|
// ShortChanID returns the short channel ID for the channel link. The short
|
|
|
|
// channel ID encodes the exact location in the main chain that the original
|
|
|
|
// funding output can be found.
|
|
|
|
//
|
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
l.RLock()
|
|
|
|
defer l.RUnlock()
|
|
|
|
|
2018-02-04 05:14:09 +03:00
|
|
|
return l.shortChanID
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateShortChanID updates the short channel ID for a link. This may be
|
|
|
|
// required in the event that a link is created before the short chan ID for it
|
|
|
|
// is known, or a re-org occurs, and the funding transaction changes location
|
|
|
|
// within the chain.
|
|
|
|
//
|
|
|
|
// NOTE: Part of the ChannelLink interface.
|
2018-05-02 02:29:47 +03:00
|
|
|
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
|
|
|
|
chanID := l.ChanID()
|
2018-02-04 05:14:09 +03:00
|
|
|
|
2018-05-02 02:29:47 +03:00
|
|
|
// Refresh the channel state's short channel ID by loading it from disk.
|
|
|
|
// This ensures that the channel state accurately reflects the updated
|
|
|
|
// short channel ID.
|
|
|
|
err := l.channel.State().RefreshShortChanID()
|
|
|
|
if err != nil {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
|
|
|
|
"%v", chanID, err)
|
2019-08-31 00:11:38 +03:00
|
|
|
return hop.Source, err
|
2018-05-02 02:29:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
sid := l.channel.ShortChanID()
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Infof("updating to short_chan_id=%v for chan_id=%v", sid, chanID)
|
2018-02-04 05:14:09 +03:00
|
|
|
|
2018-05-02 02:29:47 +03:00
|
|
|
l.Lock()
|
2018-02-04 05:14:09 +03:00
|
|
|
l.shortChanID = sid
|
2018-05-02 02:29:47 +03:00
|
|
|
l.Unlock()
|
2018-02-04 05:14:09 +03:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
err := l.cfg.UpdateContractSignals(&contractcourt.ContractSignals{
|
|
|
|
HtlcUpdates: l.htlcUpdates,
|
2018-05-02 02:29:47 +03:00
|
|
|
ShortChanID: sid,
|
2018-02-04 05:14:09 +03:00
|
|
|
})
|
|
|
|
if err != nil {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to update signals")
|
2018-02-04 05:14:09 +03:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2018-08-22 04:47:52 +03:00
|
|
|
// Now that the short channel ID has been properly updated, we can begin
|
|
|
|
// garbage collecting any forwarding packages we create.
|
|
|
|
l.wg.Add(1)
|
|
|
|
go l.fwdPkgGarbager()
|
|
|
|
|
2018-05-02 02:29:47 +03:00
|
|
|
return sid, nil
|
2017-06-17 00:32:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ChanID returns the channel ID for the channel link. The channel ID is a more
|
|
|
|
// compact representation of a channel's full outpoint.
|
2017-06-01 02:43:37 +03:00
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) ChanID() lnwire.ChannelID {
|
|
|
|
return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
|
|
|
|
}
|
|
|
|
|
2017-09-25 22:31:52 +03:00
|
|
|
// Bandwidth returns the total amount that can flow through the channel link at
|
2017-11-11 01:57:59 +03:00
|
|
|
// this given instance. The value returned is expressed in millisatoshi and can
|
|
|
|
// be used by callers when making forwarding decisions to determine if a link
|
|
|
|
// can accept an HTLC.
|
2017-06-01 02:43:37 +03:00
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
2017-08-22 09:36:43 +03:00
|
|
|
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
|
2017-11-11 01:52:27 +03:00
|
|
|
channelBandwidth := l.channel.AvailableBalance()
|
|
|
|
overflowBandwidth := l.overflowQueue.TotalHtlcAmount()
|
2018-03-13 04:52:52 +03:00
|
|
|
|
|
|
|
// To compute the total bandwidth, we'll take the current available
|
|
|
|
// bandwidth, then subtract the overflow bandwidth as we'll eventually
|
|
|
|
// also need to evaluate those HTLC's once space on the commitment
|
|
|
|
// transaction is free.
|
2017-11-29 15:57:41 +03:00
|
|
|
linkBandwidth := channelBandwidth - overflowBandwidth
|
2017-11-11 01:52:27 +03:00
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// If the channel reserve is greater than the total available balance
|
|
|
|
// of the link, just return 0.
|
|
|
|
reserve := lnwire.NewMSatFromSatoshis(l.channel.LocalChanReserve())
|
2017-11-29 15:57:41 +03:00
|
|
|
if linkBandwidth < reserve {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// Else the amount that is available to flow through the link at this
|
|
|
|
// point is the available balance minus the reserve amount we are
|
|
|
|
// required to keep as collateral.
|
2017-11-29 15:57:41 +03:00
|
|
|
return linkBandwidth - reserve
|
2017-05-03 17:07:55 +03:00
|
|
|
}
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// AttachMailBox updates the current mailbox used by this link, and hooks up
|
|
|
|
// the mailbox's message and packet outboxes to the link's upstream and
|
|
|
|
// downstream chans, respectively.
|
2017-11-27 10:20:17 +03:00
|
|
|
func (l *channelLink) AttachMailBox(mailbox MailBox) {
|
|
|
|
l.Lock()
|
|
|
|
l.mailBox = mailbox
|
|
|
|
l.upstream = mailbox.MessageOutBox()
|
|
|
|
l.downstream = mailbox.PacketOutBox()
|
|
|
|
l.Unlock()
|
|
|
|
}
|
|
|
|
|
2017-06-17 01:01:00 +03:00
|
|
|
// UpdateForwardingPolicy updates the forwarding policy for the target
|
|
|
|
// ChannelLink. Once updated, the link will use the new forwarding policy to
|
2019-08-30 03:54:08 +03:00
|
|
|
// govern if it an incoming HTLC should be forwarded or not. We assume that
|
|
|
|
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
|
|
|
|
// update all of the link's FwrdingPolicy's values.
|
2017-06-17 01:01:00 +03:00
|
|
|
//
|
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) UpdateForwardingPolicy(newPolicy ForwardingPolicy) {
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
l.Lock()
|
|
|
|
defer l.Unlock()
|
|
|
|
|
2019-08-30 03:54:08 +03:00
|
|
|
l.cfg.FwrdingPolicy = newPolicy
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
}
|
2017-06-17 01:01:00 +03:00
|
|
|
|
2019-09-27 17:21:34 +03:00
|
|
|
// CheckHtlcForward should return a nil error if the passed HTLC details satisfy
|
|
|
|
// the current forwarding policy fo the target link. Otherwise, a valid
|
|
|
|
// protocol failure message should be returned in order to signal to the source
|
|
|
|
// of the HTLC, the policy consistency issue.
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
//
|
|
|
|
// NOTE: Part of the ChannelLink interface.
|
2019-09-27 17:21:34 +03:00
|
|
|
func (l *channelLink) CheckHtlcForward(payHash [32]byte,
|
2018-06-26 06:15:46 +03:00
|
|
|
incomingHtlcAmt, amtToForward lnwire.MilliSatoshi,
|
|
|
|
incomingTimeout, outgoingTimeout uint32,
|
|
|
|
heightNow uint32) lnwire.FailureMessage {
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
|
|
|
|
l.RLock()
|
2018-06-07 04:07:20 +03:00
|
|
|
policy := l.cfg.FwrdingPolicy
|
|
|
|
l.RUnlock()
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
|
2019-04-19 12:11:16 +03:00
|
|
|
// First check whether the outgoing htlc satisfies the channel policy.
|
2019-09-27 17:21:34 +03:00
|
|
|
err := l.canSendHtlc(
|
2019-04-19 12:11:16 +03:00
|
|
|
policy, payHash, amtToForward, outgoingTimeout, heightNow,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Next, using the amount of the incoming HTLC, we'll calculate the
|
|
|
|
// expected fee this incoming HTLC must carry in order to satisfy the
|
|
|
|
// constraints of the outgoing link.
|
|
|
|
expectedFee := ExpectedFee(policy, amtToForward)
|
|
|
|
|
|
|
|
// If the actual fee is less than our expected fee, then we'll reject
|
|
|
|
// this HTLC as it didn't provide a sufficient amount of fees, or the
|
|
|
|
// values have been tampered with, or the send used incorrect/dated
|
|
|
|
// information to construct the forwarding information for this hop. In
|
|
|
|
// any case, we'll cancel this HTLC.
|
|
|
|
actualFee := incomingHtlcAmt - amtToForward
|
|
|
|
if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("outgoing htlc(%x) has insufficient fee: "+
|
|
|
|
"expected %v, got %v",
|
|
|
|
payHash[:], int64(expectedFee), int64(actualFee))
|
2019-04-19 12:11:16 +03:00
|
|
|
|
|
|
|
// As part of the returned error, we'll send our latest routing
|
|
|
|
// policy so the sending node obtains the most up to date data.
|
|
|
|
|
2019-09-27 17:01:18 +03:00
|
|
|
return l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewFeeInsufficient(
|
|
|
|
amtToForward, *upd,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
)
|
2019-04-19 12:11:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll ensure that the time-lock on the outgoing HTLC meets
|
|
|
|
// the following constraint: the incoming time-lock minus our time-lock
|
|
|
|
// delta should equal the outgoing time lock. Otherwise, whether the
|
|
|
|
// sender messed up, or an intermediate node tampered with the HTLC.
|
|
|
|
timeDelta := policy.TimeLockDelta
|
|
|
|
if incomingTimeout < outgoingTimeout+timeDelta {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("incoming htlc(%x) has incorrect time-lock value: "+
|
2019-04-19 12:11:16 +03:00
|
|
|
"expected at least %v block delta, got %v block delta",
|
|
|
|
payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
|
|
|
|
|
|
|
|
// Grab the latest routing policy so the sending node is up to
|
|
|
|
// date with our current policy.
|
2019-09-27 17:01:18 +03:00
|
|
|
return l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewIncorrectCltvExpiry(
|
|
|
|
incomingTimeout, *upd,
|
|
|
|
)
|
|
|
|
},
|
2019-04-19 12:11:16 +03:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-09-27 17:21:34 +03:00
|
|
|
// CheckHtlcTransit should return a nil error if the passed HTLC details satisfy the
|
|
|
|
// current channel policy. Otherwise, a valid protocol failure message should
|
|
|
|
// be returned in order to signal the violation. This call is intended to be
|
|
|
|
// used for locally initiated payments for which there is no corresponding
|
|
|
|
// incoming htlc.
|
|
|
|
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
|
2019-04-19 12:11:16 +03:00
|
|
|
amt lnwire.MilliSatoshi, timeout uint32,
|
|
|
|
heightNow uint32) lnwire.FailureMessage {
|
|
|
|
|
|
|
|
l.RLock()
|
|
|
|
policy := l.cfg.FwrdingPolicy
|
|
|
|
l.RUnlock()
|
|
|
|
|
2019-09-27 17:21:34 +03:00
|
|
|
return l.canSendHtlc(
|
2019-04-19 12:11:16 +03:00
|
|
|
policy, payHash, amt, timeout, heightNow,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// htlcSatifiesPolicyOutgoing checks whether the given htlc parameters satisfy
|
|
|
|
// the channel's amount and time lock constraints.
|
2019-09-27 17:21:34 +03:00
|
|
|
func (l *channelLink) canSendHtlc(policy ForwardingPolicy,
|
2019-04-19 12:11:16 +03:00
|
|
|
payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
|
|
|
|
heightNow uint32) lnwire.FailureMessage {
|
|
|
|
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
// As our first sanity check, we'll ensure that the passed HTLC isn't
|
|
|
|
// too small for the next hop. If so, then we'll cancel the HTLC
|
|
|
|
// directly.
|
2019-11-15 12:09:27 +03:00
|
|
|
if amt < policy.MinHTLCOut {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("outgoing htlc(%x) is too small: min_htlc=%v, "+
|
2019-11-15 12:09:27 +03:00
|
|
|
"htlc_value=%v", payHash[:], policy.MinHTLCOut,
|
2019-04-19 12:11:16 +03:00
|
|
|
amt)
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
|
|
|
|
// As part of the returned error, we'll send our latest routing
|
|
|
|
// policy so the sending node obtains the most up to date data.
|
2019-09-27 17:01:18 +03:00
|
|
|
return l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewAmountBelowMinimum(
|
|
|
|
amt, *upd,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
)
|
2017-06-17 01:01:00 +03:00
|
|
|
}
|
|
|
|
|
2019-09-27 17:01:18 +03:00
|
|
|
// Next, ensure that the passed HTLC isn't too large. If so, we'll
|
|
|
|
// cancel the HTLC directly.
|
2019-04-19 12:11:16 +03:00
|
|
|
if policy.MaxHTLC != 0 && amt > policy.MaxHTLC {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("outgoing htlc(%x) is too large: max_htlc=%v, "+
|
2019-04-19 12:11:16 +03:00
|
|
|
"htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
|
2018-12-09 05:21:18 +03:00
|
|
|
|
2019-09-27 17:01:18 +03:00
|
|
|
// As part of the returned error, we'll send our latest routing
|
|
|
|
// policy so the sending node obtains the most up-to-date data.
|
|
|
|
return l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewTemporaryChannelFailure(upd)
|
|
|
|
},
|
|
|
|
)
|
2018-12-09 05:21:18 +03:00
|
|
|
}
|
|
|
|
|
2019-03-26 13:54:08 +03:00
|
|
|
// We want to avoid offering an HTLC which will expire in the near
|
2019-04-05 11:50:00 +03:00
|
|
|
// future, so we'll reject an HTLC if the outgoing expiration time is
|
|
|
|
// too close to the current height.
|
2019-04-19 12:11:16 +03:00
|
|
|
if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("htlc(%x) has an expiry that's too soon: "+
|
2018-06-26 06:23:10 +03:00
|
|
|
"outgoing_expiry=%v, best_height=%v", payHash[:],
|
2019-04-19 12:11:16 +03:00
|
|
|
timeout, heightNow)
|
2018-06-26 06:23:10 +03:00
|
|
|
|
2019-09-27 17:01:18 +03:00
|
|
|
return l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewExpiryTooSoon(*upd)
|
|
|
|
},
|
2018-06-26 06:23:10 +03:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2019-04-05 11:50:00 +03:00
|
|
|
// Check absolute max delta.
|
2019-07-27 04:05:58 +03:00
|
|
|
if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("outgoing htlc(%x) has a time lock too far in "+
|
|
|
|
"the future: got %v, but maximum is %v", payHash[:],
|
2019-07-27 04:05:58 +03:00
|
|
|
timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
|
2018-10-15 09:41:56 +03:00
|
|
|
|
|
|
|
return &lnwire.FailExpiryTooFar{}
|
|
|
|
}
|
|
|
|
|
2019-09-27 17:49:16 +03:00
|
|
|
// Check to see if there is enough balance in this channel.
|
|
|
|
if amt > l.Bandwidth() {
|
|
|
|
return l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewTemporaryChannelFailure(upd)
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
return nil
|
2017-06-17 01:01:00 +03:00
|
|
|
}
|
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// Stats returns the statistics of channel link.
|
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
2017-08-22 09:36:43 +03:00
|
|
|
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
|
2017-05-03 17:07:55 +03:00
|
|
|
snapshot := l.channel.StateSnapshot()
|
2017-08-22 09:50:12 +03:00
|
|
|
|
2017-11-11 01:58:28 +03:00
|
|
|
return snapshot.ChannelCommitment.CommitHeight,
|
|
|
|
snapshot.TotalMSatSent,
|
|
|
|
snapshot.TotalMSatReceived
|
2017-05-03 17:07:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// String returns the string representation of channel link.
|
2017-06-01 02:43:37 +03:00
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) String() string {
|
|
|
|
return l.channel.ChannelPoint().String()
|
|
|
|
}
|
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// HandleSwitchPacket handles the switch packets. This packets which might be
|
|
|
|
// forwarded to us from another channel link in case the htlc update came from
|
|
|
|
// another peer or if the update was created by user
|
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
2017-11-27 10:20:17 +03:00
|
|
|
func (l *channelLink) HandleSwitchPacket(pkt *htlcPacket) error {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Tracef("received switch packet inkey=%v, outkey=%v",
|
2017-11-27 10:20:17 +03:00
|
|
|
pkt.inKey(), pkt.outKey())
|
2018-03-13 04:52:52 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
l.mailBox.AddPacket(pkt)
|
|
|
|
return nil
|
2017-05-03 17:07:55 +03:00
|
|
|
}
|
|
|
|
|
2017-06-01 02:43:37 +03:00
|
|
|
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
|
|
|
|
// to us from remote peer we have a channel with.
|
|
|
|
//
|
2017-05-03 17:07:55 +03:00
|
|
|
// NOTE: Part of the ChannelLink interface.
|
|
|
|
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
|
2017-11-11 01:48:23 +03:00
|
|
|
l.mailBox.AddMessage(message)
|
2017-05-03 17:07:55 +03:00
|
|
|
}
|
2017-05-03 18:57:13 +03:00
|
|
|
|
2017-07-14 21:40:42 +03:00
|
|
|
// updateChannelFee updates the commitment fee-per-kw on this channel by
|
|
|
|
// committing to an update_fee message.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (l *channelLink) updateChannelFee(feePerKw chainfee.SatPerKWeight) error {
|
2017-11-24 07:31:45 +03:00
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Infof("updating commit fee to %v sat/kw", feePerKw)
|
2017-11-24 07:31:45 +03:00
|
|
|
|
2017-12-11 03:19:13 +03:00
|
|
|
// We skip sending the UpdateFee message if the channel is not
|
2018-02-07 06:11:11 +03:00
|
|
|
// currently eligible to forward messages.
|
2017-12-11 03:19:13 +03:00
|
|
|
if !l.EligibleToForward() {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Debugf("skipping fee update for inactive channel")
|
2017-12-11 03:19:13 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-11-24 07:31:45 +03:00
|
|
|
// First, we'll update the local fee on our commitment.
|
2017-07-14 21:40:42 +03:00
|
|
|
if err := l.channel.UpdateFee(feePerKw); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-11-24 07:31:45 +03:00
|
|
|
// We'll then attempt to send a new UpdateFee message, and also lock it
|
|
|
|
// in immediately by triggering a commitment update.
|
2017-12-01 09:17:48 +03:00
|
|
|
msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
|
2018-06-08 06:17:15 +03:00
|
|
|
if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
|
2017-11-24 07:31:45 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return l.updateCommitTx()
|
2017-07-14 21:40:42 +03:00
|
|
|
}
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
|
|
|
|
// after receiving a revocation from the remote party, and reprocesses them in
|
|
|
|
// the context of the provided forwarding package. Any settles or fails that
|
|
|
|
// have already been acknowledged in the forwarding package will not be sent to
|
|
|
|
// the switch.
|
|
|
|
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg,
|
|
|
|
settleFails []*lnwallet.PaymentDescriptor) {
|
2017-05-03 18:57:13 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
if len(settleFails) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Debugf("settle-fail-filter %v", fwdPkg.SettleFailFilter)
|
2017-11-27 10:20:17 +03:00
|
|
|
|
|
|
|
var switchPackets []*htlcPacket
|
|
|
|
for i, pd := range settleFails {
|
2018-03-13 04:52:52 +03:00
|
|
|
// Skip any settles or fails that have already been
|
|
|
|
// acknowledged by the incoming link that originated the
|
|
|
|
// forwarded Add.
|
2017-11-27 10:20:17 +03:00
|
|
|
if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
|
|
|
|
continue
|
|
|
|
}
|
2017-05-03 18:57:13 +03:00
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// TODO(roasbeef): rework log entries to a shared
|
|
|
|
// interface.
|
|
|
|
|
2017-05-03 18:57:13 +03:00
|
|
|
switch pd.EntryType {
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// A settle for an HTLC we previously forwarded HTLC has been
|
2018-02-28 09:14:44 +03:00
|
|
|
// received. So we'll forward the HTLC to the switch which will
|
|
|
|
// handle propagating the settle to the prior hop.
|
2017-05-03 18:57:13 +03:00
|
|
|
case lnwallet.Settle:
|
2018-04-27 12:51:13 +03:00
|
|
|
// If hodl.SettleIncoming is requested, we will not
|
|
|
|
// forward the SETTLE to the switch and will not signal
|
|
|
|
// a free slot on the commitment transaction.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.SettleIncoming.Warning())
|
2018-04-27 12:51:13 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-10-24 09:18:26 +03:00
|
|
|
settlePacket := &htlcPacket{
|
2017-10-30 21:56:51 +03:00
|
|
|
outgoingChanID: l.ShortChanID(),
|
|
|
|
outgoingHTLCID: pd.ParentIndex,
|
2017-11-27 10:20:17 +03:00
|
|
|
destRef: pd.DestRef,
|
2018-02-07 06:11:11 +03:00
|
|
|
htlc: &lnwire.UpdateFulfillHTLC{
|
2017-10-24 09:18:26 +03:00
|
|
|
PaymentPreimage: pd.RPreimage,
|
|
|
|
},
|
2017-06-17 00:58:02 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add the packet to the batch to be forwarded, and
|
|
|
|
// notify the overflow queue that a spare spot has been
|
|
|
|
// freed up within the commitment state.
|
2017-11-27 10:20:17 +03:00
|
|
|
switchPackets = append(switchPackets, settlePacket)
|
2017-09-25 22:47:28 +03:00
|
|
|
l.overflowQueue.SignalFreeSlot()
|
2017-05-03 18:57:13 +03:00
|
|
|
|
2018-02-28 09:14:44 +03:00
|
|
|
// A failureCode message for a previously forwarded HTLC has
|
|
|
|
// been received. As a result a new slot will be freed up in
|
|
|
|
// our commitment state, so we'll forward this to the switch so
|
|
|
|
// the backwards undo can continue.
|
2017-05-03 18:57:13 +03:00
|
|
|
case lnwallet.Fail:
|
2018-04-27 12:51:13 +03:00
|
|
|
// If hodl.SettleIncoming is requested, we will not
|
|
|
|
// forward the FAIL to the switch and will not signal a
|
|
|
|
// free slot on the commitment transaction.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.FailIncoming) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.FailIncoming.Warning())
|
2018-04-27 12:51:13 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-10-03 18:22:43 +03:00
|
|
|
// Fetch the reason the HTLC was canceled so we can
|
2017-06-17 00:58:02 +03:00
|
|
|
// continue to propagate it.
|
2017-10-24 09:18:26 +03:00
|
|
|
failPacket := &htlcPacket{
|
2017-10-30 21:56:51 +03:00
|
|
|
outgoingChanID: l.ShortChanID(),
|
|
|
|
outgoingHTLCID: pd.ParentIndex,
|
2017-11-27 10:20:17 +03:00
|
|
|
destRef: pd.DestRef,
|
2017-10-24 09:18:26 +03:00
|
|
|
htlc: &lnwire.UpdateFailHTLC{
|
2019-05-01 04:20:23 +03:00
|
|
|
Reason: lnwire.OpaqueReason(
|
|
|
|
pd.FailReason,
|
|
|
|
),
|
2017-10-24 09:18:26 +03:00
|
|
|
},
|
2017-06-17 00:58:02 +03:00
|
|
|
}
|
|
|
|
|
2019-05-01 04:20:23 +03:00
|
|
|
// If the failure message lacks an HMAC (but includes
|
|
|
|
// the 4 bytes for encoding the message and padding
|
|
|
|
// lengths, then this means that we received it as an
|
|
|
|
// UpdateFailMalformedHTLC. As a result, we'll signal
|
|
|
|
// that we need to convert this error within the switch
|
|
|
|
// to an actual error, by encrypting it as if we were
|
|
|
|
// the originating hop.
|
|
|
|
convertedErrorSize := lnwire.FailureMessageLength + 4
|
|
|
|
if len(pd.FailReason) == convertedErrorSize {
|
|
|
|
failPacket.convertedError = true
|
|
|
|
}
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// Add the packet to the batch to be forwarded, and
|
|
|
|
// notify the overflow queue that a spare spot has been
|
|
|
|
// freed up within the commitment state.
|
2017-11-27 10:20:17 +03:00
|
|
|
switchPackets = append(switchPackets, failPacket)
|
2017-09-25 22:47:28 +03:00
|
|
|
l.overflowQueue.SignalFreeSlot()
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-08 06:55:07 +03:00
|
|
|
// Only spawn the task forward packets we have a non-zero number.
|
|
|
|
if len(switchPackets) > 0 {
|
|
|
|
go l.forwardBatch(switchPackets...)
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// processRemoteAdds serially processes each of the Add payment descriptors
|
|
|
|
// which have been "locked-in" by receiving a revocation from the remote party.
|
|
|
|
// The forwarding package provided instructs how to process this batch,
|
|
|
|
// indicating whether this is the first time these Adds are being processed, or
|
|
|
|
// whether we are reprocessing as a result of a failure or restart. Adds that
|
|
|
|
// have already been acknowledged in the forwarding package will be ignored.
|
|
|
|
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg,
|
2019-04-10 14:10:25 +03:00
|
|
|
lockedInHtlcs []*lnwallet.PaymentDescriptor) {
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Tracef("processing %d remote adds for height %d",
|
2017-11-27 10:20:17 +03:00
|
|
|
len(lockedInHtlcs), fwdPkg.Height)
|
|
|
|
|
2019-09-05 14:35:39 +03:00
|
|
|
decodeReqs := make(
|
|
|
|
[]hop.DecodeHopIteratorRequest, 0, len(lockedInHtlcs),
|
|
|
|
)
|
2017-11-27 10:20:17 +03:00
|
|
|
for _, pd := range lockedInHtlcs {
|
|
|
|
switch pd.EntryType {
|
|
|
|
|
|
|
|
// TODO(conner): remove type switch?
|
|
|
|
case lnwallet.Add:
|
|
|
|
// Before adding the new htlc to the state machine,
|
|
|
|
// parse the onion object in order to obtain the
|
|
|
|
// routing information with DecodeHopIterator function
|
|
|
|
// which process the Sphinx packet.
|
|
|
|
onionReader := bytes.NewReader(pd.OnionBlob)
|
|
|
|
|
2019-09-05 14:35:39 +03:00
|
|
|
req := hop.DecodeHopIteratorRequest{
|
2017-11-27 10:20:17 +03:00
|
|
|
OnionReader: onionReader,
|
|
|
|
RHash: pd.RHash[:],
|
|
|
|
IncomingCltv: pd.Timeout,
|
|
|
|
}
|
|
|
|
|
|
|
|
decodeReqs = append(decodeReqs, req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Atomically decode the incoming htlcs, simultaneously checking for
|
|
|
|
// replay attempts. A particular index in the returned, spare list of
|
2018-03-13 04:52:52 +03:00
|
|
|
// channel iterators should only be used if the failure code at the
|
|
|
|
// same index is lnwire.FailCodeNone.
|
2017-11-27 10:20:17 +03:00
|
|
|
decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
|
|
|
|
fwdPkg.ID(), decodeReqs,
|
|
|
|
)
|
|
|
|
if sphinxErr != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to decode hop iterators: %v", sphinxErr)
|
2019-04-10 14:10:25 +03:00
|
|
|
return
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
var switchPackets []*htlcPacket
|
2017-11-27 10:20:17 +03:00
|
|
|
|
|
|
|
for i, pd := range lockedInHtlcs {
|
|
|
|
idx := uint16(i)
|
|
|
|
|
|
|
|
if fwdPkg.State == channeldb.FwdStateProcessed &&
|
|
|
|
fwdPkg.AckFilter.Contains(idx) {
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// If this index is already found in the ack filter,
|
|
|
|
// the response to this forwarding decision has already
|
|
|
|
// been committed by one of our commitment txns. ADDs
|
|
|
|
// in this state are waiting for the rest of the fwding
|
|
|
|
// package to get acked before being garbage collected.
|
2017-11-27 10:20:17 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-06-17 00:58:02 +03:00
|
|
|
// An incoming HTLC add has been full-locked in. As a result we
|
2017-10-19 03:36:28 +03:00
|
|
|
// can now examine the forwarding details of the HTLC, and the
|
2017-07-15 06:08:29 +03:00
|
|
|
// HTLC itself to decide if: we should forward it, cancel it,
|
2017-06-17 00:58:02 +03:00
|
|
|
// or are able to settle it (and it adheres to our fee related
|
|
|
|
// constraints).
|
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
// Fetch the onion blob that was included within this processed
|
|
|
|
// payment descriptor.
|
|
|
|
var onionBlob [lnwire.OnionPacketSize]byte
|
|
|
|
copy(onionBlob[:], pd.OnionBlob)
|
|
|
|
|
|
|
|
// Before adding the new htlc to the state machine, parse the
|
|
|
|
// onion object in order to obtain the routing information with
|
|
|
|
// DecodeHopIterator function which process the Sphinx packet.
|
|
|
|
chanIterator, failureCode := decodeResps[i].Result()
|
|
|
|
if failureCode != lnwire.CodeNone {
|
|
|
|
// If we're unable to process the onion blob than we
|
|
|
|
// should send the malformed htlc error to payment
|
|
|
|
// sender.
|
|
|
|
l.sendMalformedHTLCError(pd.HtlcIndex, failureCode,
|
|
|
|
onionBlob[:], pd.SourceRef)
|
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to decode onion hop "+
|
2018-03-13 04:55:04 +03:00
|
|
|
"iterator: %v", failureCode)
|
|
|
|
continue
|
|
|
|
}
|
2017-07-15 06:08:29 +03:00
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
// Retrieve onion obfuscator from onion blob in order to
|
|
|
|
// produce initial obfuscation of the onion failureCode.
|
|
|
|
obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
|
2018-03-12 22:39:13 +03:00
|
|
|
l.cfg.ExtractErrorEncrypter,
|
2018-03-13 04:55:04 +03:00
|
|
|
)
|
|
|
|
if failureCode != lnwire.CodeNone {
|
|
|
|
// If we're unable to process the onion blob than we
|
|
|
|
// should send the malformed htlc error to payment
|
|
|
|
// sender.
|
2019-07-31 07:52:17 +03:00
|
|
|
l.sendMalformedHTLCError(
|
|
|
|
pd.HtlcIndex, failureCode, onionBlob[:], pd.SourceRef,
|
|
|
|
)
|
2018-03-13 04:55:04 +03:00
|
|
|
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to decode onion "+
|
2018-03-13 04:55:04 +03:00
|
|
|
"obfuscator: %v", failureCode)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-06-01 06:31:40 +03:00
|
|
|
heightNow := l.cfg.Switch.BestHeight()
|
2018-03-13 04:55:04 +03:00
|
|
|
|
2019-11-05 02:10:15 +03:00
|
|
|
pld, err := chanIterator.HopPayload()
|
2019-07-31 07:52:17 +03:00
|
|
|
if err != nil {
|
|
|
|
// If we're unable to process the onion payload, or we
|
2019-10-31 07:19:53 +03:00
|
|
|
// received invalid onion payload failure, then we
|
|
|
|
// should send an error back to the caller so the HTLC
|
|
|
|
// can be canceled.
|
|
|
|
var failedType uint64
|
|
|
|
if e, ok := err.(hop.ErrInvalidPayload); ok {
|
|
|
|
failedType = uint64(e.Type)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: currently none of the test unit infrastructure
|
|
|
|
// is setup to handle TLV payloads, so testing this
|
|
|
|
// would require implementing a separate mock iterator
|
|
|
|
// for TLV payloads that also supports injecting invalid
|
|
|
|
// payloads. Deferring this non-trival effort till a
|
|
|
|
// later date
|
2019-07-31 07:52:17 +03:00
|
|
|
l.sendHTLCError(
|
|
|
|
pd.HtlcIndex,
|
2019-10-31 07:19:53 +03:00
|
|
|
lnwire.NewInvalidOnionPayload(failedType, 0),
|
2019-07-31 07:52:17 +03:00
|
|
|
obfuscator, pd.SourceRef,
|
|
|
|
)
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("unable to decode forwarding "+
|
2019-07-31 07:52:17 +03:00
|
|
|
"instructions: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-11-05 02:10:15 +03:00
|
|
|
fwdInfo := pld.ForwardingInfo()
|
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
switch fwdInfo.NextHop {
|
2019-08-31 00:11:38 +03:00
|
|
|
case hop.Exit:
|
2019-04-10 14:10:25 +03:00
|
|
|
err := l.processExitHop(
|
2019-11-05 02:10:32 +03:00
|
|
|
pd, obfuscator, fwdInfo, heightNow, pld,
|
2018-04-25 06:43:55 +03:00
|
|
|
)
|
2018-03-13 04:55:04 +03:00
|
|
|
if err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
2019-02-08 12:01:54 +03:00
|
|
|
err.Error(),
|
|
|
|
)
|
2017-05-03 18:57:13 +03:00
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
return
|
2018-05-18 15:01:01 +03:00
|
|
|
}
|
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
// There are additional channels left within this route. So
|
2018-06-26 06:23:10 +03:00
|
|
|
// we'll simply do some forwarding package book-keeping.
|
2018-03-13 04:55:04 +03:00
|
|
|
default:
|
2018-04-27 12:51:13 +03:00
|
|
|
// If hodl.AddIncoming is requested, we will not
|
|
|
|
// validate the forwarded ADD, nor will we send the
|
|
|
|
// packet to the htlc switch.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.AddIncoming) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.AddIncoming.Warning())
|
2018-04-27 12:51:13 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
switch fwdPkg.State {
|
|
|
|
case channeldb.FwdStateProcessed:
|
|
|
|
// This add was not forwarded on the previous
|
|
|
|
// processing phase, run it through our
|
|
|
|
// validation pipeline to reproduce an error.
|
|
|
|
// This may trigger a different error due to
|
|
|
|
// expiring timelocks, but we expect that an
|
|
|
|
// error will be reproduced.
|
|
|
|
if !fwdPkg.FwdFilter.Contains(idx) {
|
|
|
|
break
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
// Otherwise, it was already processed, we can
|
|
|
|
// can collect it and continue.
|
|
|
|
addMsg := &lnwire.UpdateAddHTLC{
|
|
|
|
Expiry: fwdInfo.OutgoingCTLV,
|
|
|
|
Amount: fwdInfo.AmountToForward,
|
|
|
|
PaymentHash: pd.RHash,
|
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
// Finally, we'll encode the onion packet for
|
|
|
|
// the _next_ hop using the hop iterator
|
|
|
|
// decoded for the current hop.
|
|
|
|
buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
|
|
|
|
|
|
|
|
// We know this cannot fail, as this ADD
|
|
|
|
// was marked forwarded in a previous
|
|
|
|
// round of processing.
|
|
|
|
chanIterator.EncodeNextHop(buf)
|
|
|
|
|
|
|
|
updatePacket := &htlcPacket{
|
2018-06-26 06:25:21 +03:00
|
|
|
incomingChanID: l.ShortChanID(),
|
|
|
|
incomingHTLCID: pd.HtlcIndex,
|
|
|
|
outgoingChanID: fwdInfo.NextHop,
|
|
|
|
sourceRef: pd.SourceRef,
|
|
|
|
incomingAmount: pd.Amount,
|
|
|
|
amount: addMsg.Amount,
|
|
|
|
htlc: addMsg,
|
|
|
|
obfuscator: obfuscator,
|
|
|
|
incomingTimeout: pd.Timeout,
|
|
|
|
outgoingTimeout: fwdInfo.OutgoingCTLV,
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
htlcswitch: perform fee related checks at forwarding time
In this commit, we fix a very old, lingering bug within the link. When
accepting an HTLC we are meant to validate the fee against the
constraints of the *outgoing* link. This is due to the fact that we're
offering a payment transit service on our outgoing link. Before this
commit, we would use the policies of the *incoming* link. This would at
times lead to odd routing errors as we would go to route, get an error
update and then route again, repeating the process.
With this commit, we'll properly use the incoming link for timelock
related constraints, and the outgoing link for fee related constraints.
We do this by introducing a new HtlcSatisfiesPolicy method in the link.
This method should return a non-nil error if the link can carry the HTLC
as it satisfies its current forwarding policy. We'll use this method now
at *forwarding* time to ensure that we only forward to links that
actually accept the policy. This fixes a number of bugs that existed
before that could result in a link accepting an HTLC that actually
violated its policy. In the case that the policy is violated for *all*
links, we take care to return the error returned by the *target* link so
the caller can update their sending accordingly.
In this commit, we also remove the prior linkControl channel in the
channelLink. Instead, of sending a message to update the internal link
policy, we'll use a mutex in place. This simplifies the code, and also
adds some necessary refactoring in anticipation of the next follow up
commit.
2018-04-04 05:51:40 +03:00
|
|
|
switchPackets = append(
|
|
|
|
switchPackets, updatePacket,
|
|
|
|
)
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
continue
|
|
|
|
}
|
2017-08-03 07:10:35 +03:00
|
|
|
|
2018-06-26 06:23:10 +03:00
|
|
|
// TODO(roasbeef): ensure don't accept outrageous
|
|
|
|
// timeout for htlc
|
2017-06-29 16:40:45 +03:00
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
// With all our forwarding constraints met, we'll
|
|
|
|
// create the outgoing HTLC using the parameters as
|
|
|
|
// specified in the forwarding info.
|
|
|
|
addMsg := &lnwire.UpdateAddHTLC{
|
|
|
|
Expiry: fwdInfo.OutgoingCTLV,
|
|
|
|
Amount: fwdInfo.AmountToForward,
|
|
|
|
PaymentHash: pd.RHash,
|
|
|
|
}
|
2017-06-17 00:58:02 +03:00
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
// Finally, we'll encode the onion packet for the
|
|
|
|
// _next_ hop using the hop iterator decoded for the
|
|
|
|
// current hop.
|
|
|
|
buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
|
|
|
|
err := chanIterator.EncodeNextHop(buf)
|
|
|
|
if err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to encode the "+
|
2018-03-13 04:55:04 +03:00
|
|
|
"remaining route %v", err)
|
|
|
|
|
2019-09-27 17:01:18 +03:00
|
|
|
failure := l.createFailureWithUpdate(
|
|
|
|
func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
|
|
|
|
return lnwire.NewTemporaryChannelFailure(
|
|
|
|
upd,
|
|
|
|
)
|
|
|
|
},
|
2018-05-08 06:00:32 +03:00
|
|
|
)
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-03-13 04:55:04 +03:00
|
|
|
l.sendHTLCError(
|
|
|
|
pd.HtlcIndex, failure, obfuscator, pd.SourceRef,
|
|
|
|
)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that this add has been reprocessed, only append
|
|
|
|
// it to our list of packets to forward to the switch
|
|
|
|
// this is the first time processing the add. If the
|
|
|
|
// fwd pkg has already been processed, then we entered
|
|
|
|
// the above section to recreate a previous error. If
|
|
|
|
// the packet had previously been forwarded, it would
|
|
|
|
// have been added to switchPackets at the top of this
|
|
|
|
// section.
|
|
|
|
if fwdPkg.State == channeldb.FwdStateLockedIn {
|
|
|
|
updatePacket := &htlcPacket{
|
2018-06-26 06:25:21 +03:00
|
|
|
incomingChanID: l.ShortChanID(),
|
|
|
|
incomingHTLCID: pd.HtlcIndex,
|
|
|
|
outgoingChanID: fwdInfo.NextHop,
|
|
|
|
sourceRef: pd.SourceRef,
|
|
|
|
incomingAmount: pd.Amount,
|
|
|
|
amount: addMsg.Amount,
|
|
|
|
htlc: addMsg,
|
|
|
|
obfuscator: obfuscator,
|
|
|
|
incomingTimeout: pd.Timeout,
|
|
|
|
outgoingTimeout: fwdInfo.OutgoingCTLV,
|
2017-10-24 09:18:26 +03:00
|
|
|
}
|
2018-03-13 04:55:04 +03:00
|
|
|
|
|
|
|
fwdPkg.FwdFilter.Set(idx)
|
|
|
|
switchPackets = append(switchPackets,
|
|
|
|
updatePacket)
|
2017-05-03 18:57:13 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// Commit the htlcs we are intending to forward if this package has not
|
|
|
|
// been fully processed.
|
|
|
|
if fwdPkg.State == channeldb.FwdStateLockedIn {
|
|
|
|
err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
|
|
|
|
if err != nil {
|
2018-05-09 16:49:58 +03:00
|
|
|
l.fail(LinkFailureError{code: ErrInternalError},
|
|
|
|
"unable to set fwd filter: %v", err)
|
2019-04-10 14:10:25 +03:00
|
|
|
return
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(switchPackets) == 0 {
|
2019-04-10 14:10:25 +03:00
|
|
|
return
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Debugf("forwarding %d packets to switch", len(switchPackets))
|
2017-11-27 10:20:17 +03:00
|
|
|
|
2018-05-08 06:55:07 +03:00
|
|
|
// NOTE: This call is made synchronous so that we ensure all circuits
|
|
|
|
// are committed in the exact order that they are processed in the link.
|
|
|
|
// Failing to do this could cause reorderings/gaps in the range of
|
|
|
|
// opened circuits, which violates assumptions made by the circuit
|
|
|
|
// trimming.
|
|
|
|
l.forwardBatch(switchPackets...)
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
2019-02-08 12:01:54 +03:00
|
|
|
// processExitHop handles an htlc for which this link is the exit hop. It
|
|
|
|
// returns a boolean indicating whether the commitment tx needs an update.
|
|
|
|
func (l *channelLink) processExitHop(pd *lnwallet.PaymentDescriptor,
|
2019-09-05 14:35:39 +03:00
|
|
|
obfuscator hop.ErrorEncrypter, fwdInfo hop.ForwardingInfo,
|
2019-04-10 14:10:25 +03:00
|
|
|
heightNow uint32, payload invoices.Payload) error {
|
2019-02-08 12:01:54 +03:00
|
|
|
|
|
|
|
// If hodl.ExitSettle is requested, we will not validate the final hop's
|
|
|
|
// ADD, nor will we settle the corresponding invoice or respond with the
|
|
|
|
// preimage.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.ExitSettle) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.ExitSettle.Warning())
|
2019-02-08 12:01:54 +03:00
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
return nil
|
2019-02-08 12:01:54 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// As we're the exit hop, we'll double check the hop-payload included in
|
|
|
|
// the HTLC to ensure that it was crafted correctly by the sender and
|
|
|
|
// matches the HTLC we were extended.
|
2019-08-14 20:57:31 +03:00
|
|
|
if pd.Amount != fwdInfo.AmountToForward {
|
2019-02-08 12:01:54 +03:00
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("onion payload of incoming htlc(%x) has incorrect "+
|
2019-02-08 12:01:54 +03:00
|
|
|
"value: expected %v, got %v", pd.RHash,
|
2019-04-16 13:11:20 +03:00
|
|
|
pd.Amount, fwdInfo.AmountToForward)
|
2019-02-08 12:01:54 +03:00
|
|
|
|
2019-06-12 14:23:21 +03:00
|
|
|
failure := lnwire.NewFinalIncorrectHtlcAmount(pd.Amount)
|
2019-02-08 12:01:54 +03:00
|
|
|
l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)
|
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
return nil
|
2019-02-08 12:01:54 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// We'll also ensure that our time-lock value has been computed
|
2019-04-16 13:11:20 +03:00
|
|
|
// correctly.
|
2019-08-14 20:57:31 +03:00
|
|
|
if pd.Timeout != fwdInfo.OutgoingCTLV {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("onion payload of incoming htlc(%x) has incorrect "+
|
2019-04-16 13:11:20 +03:00
|
|
|
"time-lock: expected %v, got %v",
|
|
|
|
pd.RHash[:], pd.Timeout, fwdInfo.OutgoingCTLV)
|
2019-02-08 12:01:54 +03:00
|
|
|
|
2019-06-25 15:55:23 +03:00
|
|
|
failure := lnwire.NewFinalIncorrectCltvExpiry(pd.Timeout)
|
2019-02-08 12:01:54 +03:00
|
|
|
l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)
|
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
return nil
|
2019-02-08 12:01:54 +03:00
|
|
|
}
|
|
|
|
|
2019-02-20 14:11:15 +03:00
|
|
|
// Notify the invoiceRegistry of the exit hop htlc. If we crash right
|
|
|
|
// after this, this code will be re-executed after restart. We will
|
|
|
|
// receive back a resolution event.
|
2019-04-16 13:11:20 +03:00
|
|
|
invoiceHash := lntypes.Hash(pd.RHash)
|
|
|
|
|
2019-08-08 16:48:31 +03:00
|
|
|
circuitKey := channeldb.CircuitKey{
|
|
|
|
ChanID: l.ShortChanID(),
|
|
|
|
HtlcID: pd.HtlcIndex,
|
|
|
|
}
|
|
|
|
|
2019-02-20 14:11:15 +03:00
|
|
|
event, err := l.cfg.Registry.NotifyExitHopHtlc(
|
2019-04-16 13:11:20 +03:00
|
|
|
invoiceHash, pd.Amount, pd.Timeout, int32(heightNow),
|
2019-11-05 02:10:32 +03:00
|
|
|
circuitKey, l.hodlQueue.ChanIn(), payload,
|
2019-02-20 14:11:15 +03:00
|
|
|
)
|
2019-04-16 13:11:20 +03:00
|
|
|
|
|
|
|
switch err {
|
|
|
|
|
|
|
|
// Cancel htlc if we don't have an invoice for it.
|
|
|
|
case channeldb.ErrInvoiceNotFound:
|
2019-06-12 13:18:58 +03:00
|
|
|
failure := lnwire.NewFailIncorrectDetails(pd.Amount, heightNow)
|
2019-04-16 13:11:20 +03:00
|
|
|
l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)
|
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
return nil
|
2019-04-16 13:11:20 +03:00
|
|
|
|
|
|
|
// No error.
|
|
|
|
case nil:
|
|
|
|
|
|
|
|
// Pass error to caller.
|
|
|
|
default:
|
2019-04-10 14:10:25 +03:00
|
|
|
return err
|
2019-02-08 12:01:54 +03:00
|
|
|
}
|
|
|
|
|
2019-02-11 14:01:05 +03:00
|
|
|
// Create a hodlHtlc struct and decide either resolved now or later.
|
2019-02-20 14:11:15 +03:00
|
|
|
htlc := hodlHtlc{
|
|
|
|
pd: pd,
|
|
|
|
obfuscator: obfuscator,
|
|
|
|
}
|
2019-02-11 14:01:05 +03:00
|
|
|
|
|
|
|
if event == nil {
|
|
|
|
// Save payment descriptor for future reference.
|
2019-08-14 22:11:34 +03:00
|
|
|
l.hodlMap[circuitKey] = htlc
|
2019-02-11 14:01:05 +03:00
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
return nil
|
2019-02-11 14:01:05 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Process the received resolution.
|
2019-04-10 14:10:25 +03:00
|
|
|
return l.processHodlEvent(*event, htlc)
|
2019-02-08 12:57:50 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// settleHTLC settles the HTLC on the channel.
|
|
|
|
func (l *channelLink) settleHTLC(preimage lntypes.Preimage, htlcIndex uint64,
|
|
|
|
sourceRef *channeldb.AddRef) error {
|
|
|
|
|
|
|
|
hash := preimage.Hash()
|
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Infof("settling htlc %v as exit hop", hash)
|
2019-02-08 12:57:50 +03:00
|
|
|
|
|
|
|
err := l.channel.SettleHTLC(
|
|
|
|
preimage, htlcIndex, sourceRef, nil, nil,
|
2019-02-18 23:27:54 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
2019-02-08 12:57:50 +03:00
|
|
|
return fmt.Errorf("unable to settle htlc: %v", err)
|
2019-02-18 23:27:54 +03:00
|
|
|
}
|
|
|
|
|
2019-02-08 12:01:54 +03:00
|
|
|
// If the link is in hodl.BogusSettle mode, replace the preimage with a
|
|
|
|
// fake one before sending it to the peer.
|
2019-08-14 20:57:31 +03:00
|
|
|
if l.cfg.HodlMask.Active(hodl.BogusSettle) {
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Warnf(hodl.BogusSettle.Warning())
|
2019-02-08 12:01:54 +03:00
|
|
|
preimage = [32]byte{}
|
|
|
|
copy(preimage[:], bytes.Repeat([]byte{2}, 32))
|
|
|
|
}
|
|
|
|
|
|
|
|
// HTLC was successfully settled locally send notification about it
|
|
|
|
// remote peer.
|
|
|
|
l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
|
|
|
|
ChanID: l.ChanID(),
|
2019-02-08 12:57:50 +03:00
|
|
|
ID: htlcIndex,
|
2019-02-08 12:01:54 +03:00
|
|
|
PaymentPreimage: preimage,
|
|
|
|
})
|
|
|
|
|
2019-02-08 12:57:50 +03:00
|
|
|
return nil
|
2019-02-08 12:01:54 +03:00
|
|
|
}
|
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
|
|
|
|
// err chan for the individual responses. This method is intended to be spawned
|
|
|
|
// as a goroutine so the responses can be handled in the background.
|
|
|
|
func (l *channelLink) forwardBatch(packets ...*htlcPacket) {
|
|
|
|
// Don't forward packets for which we already have a response in our
|
|
|
|
// mailbox. This could happen if a packet fails and is buffered in the
|
|
|
|
// mailbox, and the incoming link flaps.
|
|
|
|
var filteredPkts = make([]*htlcPacket, 0, len(packets))
|
|
|
|
for _, pkt := range packets {
|
|
|
|
if l.mailBox.HasPacket(pkt.inKey()) {
|
|
|
|
continue
|
2017-05-03 18:57:13 +03:00
|
|
|
}
|
2017-11-27 10:20:17 +03:00
|
|
|
|
|
|
|
filteredPkts = append(filteredPkts, pkt)
|
2017-05-03 18:57:13 +03:00
|
|
|
}
|
|
|
|
|
2018-07-30 23:11:11 +03:00
|
|
|
errChan := l.cfg.ForwardPackets(l.quit, filteredPkts...)
|
2018-05-08 06:55:07 +03:00
|
|
|
go l.handleBatchFwdErrs(errChan)
|
2017-11-27 10:20:17 +03:00
|
|
|
}
|
|
|
|
|
2018-03-13 04:52:52 +03:00
|
|
|
// handleBatchFwdErrs waits on the given errChan until it is closed, logging
|
|
|
|
// the errors returned from any unsuccessful forwarding attempts.
|
2017-11-27 10:20:17 +03:00
|
|
|
func (l *channelLink) handleBatchFwdErrs(errChan chan error) {
|
|
|
|
for {
|
|
|
|
err, ok := <-errChan
|
|
|
|
if !ok {
|
2018-03-13 04:52:52 +03:00
|
|
|
// Err chan has been drained or switch is shutting
|
|
|
|
// down. Either way, return.
|
2017-11-27 10:20:17 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-10-01 12:06:56 +03:00
|
|
|
l.log.Errorf("unhandled error while forwarding htlc packet over "+
|
2017-11-27 10:20:17 +03:00
|
|
|
"htlcswitch: %v", err)
|
|
|
|
}
|
2017-05-03 18:57:13 +03:00
|
|
|
}
|
|
|
|
|
2017-07-15 06:08:29 +03:00
|
|
|
// sendHTLCError functions cancels HTLC and send cancel message back to the
|
|
|
|
// peer from which HTLC was received.
|
2018-03-13 04:52:52 +03:00
|
|
|
func (l *channelLink) sendHTLCError(htlcIndex uint64, failure lnwire.FailureMessage,
|
2019-09-05 14:35:39 +03:00
|
|
|
e hop.ErrorEncrypter, sourceRef *channeldb.AddRef) {
|
2017-10-11 05:36:52 +03:00
|
|
|
|
|
|
|
reason, err := e.EncryptFirstHop(failure)
|
2017-06-29 16:40:45 +03:00
|
|
|
if err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable to obfuscate error: %v", err)
|
2017-06-29 16:40:45 +03:00
|
|
|
return
|
|
|
|
}
|
2017-05-03 18:57:13 +03:00
|
|
|
|
2017-11-27 10:20:17 +03:00
|
|
|
err = l.channel.FailHTLC(htlcIndex, reason, sourceRef, nil, nil)
|
2017-05-03 18:57:13 +03:00
|
|
|
if err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable cancel htlc: %v", err)
|
2017-05-03 18:57:13 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailHTLC{
|
2017-05-03 18:57:13 +03:00
|
|
|
ChanID: l.ChanID(),
|
2017-10-24 10:48:52 +03:00
|
|
|
ID: htlcIndex,
|
2017-05-03 18:57:13 +03:00
|
|
|
Reason: reason,
|
2018-06-08 06:17:15 +03:00
|
|
|
})
|
2017-05-03 18:57:13 +03:00
|
|
|
}
|
2017-07-12 16:44:17 +03:00
|
|
|
|
2017-07-15 06:08:29 +03:00
|
|
|
// sendMalformedHTLCError helper function which sends the malformed HTLC update
|
2017-06-29 16:40:45 +03:00
|
|
|
// to the payment sender.
|
2017-10-24 10:48:52 +03:00
|
|
|
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
|
2017-11-27 10:20:17 +03:00
|
|
|
code lnwire.FailCode, onionBlob []byte, sourceRef *channeldb.AddRef) {
|
2017-08-14 14:21:57 +03:00
|
|
|
|
|
|
|
shaOnionBlob := sha256.Sum256(onionBlob)
|
2017-11-27 10:20:17 +03:00
|
|
|
err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
|
2017-06-29 16:40:45 +03:00
|
|
|
if err != nil {
|
2019-10-01 12:16:24 +03:00
|
|
|
l.log.Errorf("unable cancel htlc: %v", err)
|
2017-06-29 16:40:45 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-06-08 06:17:15 +03:00
|
|
|
l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
|
2017-06-29 16:40:45 +03:00
|
|
|
ChanID: l.ChanID(),
|
2017-10-24 10:48:52 +03:00
|
|
|
ID: htlcIndex,
|
2017-08-14 14:21:57 +03:00
|
|
|
ShaOnionBlob: shaOnionBlob,
|
2017-06-29 16:40:45 +03:00
|
|
|
FailureCode: code,
|
2018-06-08 06:17:15 +03:00
|
|
|
})
|
2017-06-29 16:40:45 +03:00
|
|
|
}
|
|
|
|
|
2018-05-09 16:49:58 +03:00
|
|
|
// fail is a function which is used to encapsulate the action necessary for
|
|
|
|
// properly failing the link. It takes a LinkFailureError, which will be passed
|
|
|
|
// to the OnChannelFailure closure, in order for it to determine if we should
|
|
|
|
// force close the channel, and if we should send an error message to the
|
|
|
|
// remote peer.
|
|
|
|
func (l *channelLink) fail(linkErr LinkFailureError,
|
|
|
|
format string, a ...interface{}) {
|
2017-07-12 16:44:17 +03:00
|
|
|
reason := errors.Errorf(format, a...)
|
2018-05-23 16:14:46 +03:00
|
|
|
|
|
|
|
// Return if we have already notified about a failure.
|
|
|
|
if l.failed {
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Warnf("ignoring link failure (%v), as link already "+
|
2019-10-01 12:06:56 +03:00
|
|
|
"failed", reason)
|
2018-05-23 16:14:46 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-02 16:53:29 +03:00
|
|
|
l.log.Errorf("failing link: %s", reason)
|
2018-05-23 16:14:46 +03:00
|
|
|
|
|
|
|
// Set failed, such that we won't process any more updates, and notify
|
|
|
|
// the peer about the failure.
|
|
|
|
l.failed = true
|
2018-05-09 16:49:58 +03:00
|
|
|
l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
|
2017-06-29 16:40:45 +03:00
|
|
|
}
|