2015-12-20 09:00:50 +03:00
|
|
|
package lnwallet
|
2015-12-03 03:49:41 +03:00
|
|
|
|
2015-12-16 23:40:11 +03:00
|
|
|
import (
|
2016-01-06 00:01:42 +03:00
|
|
|
"bytes"
|
2016-07-06 03:01:55 +03:00
|
|
|
"container/list"
|
2017-03-16 04:56:25 +03:00
|
|
|
"crypto/sha256"
|
2020-01-03 17:53:51 +03:00
|
|
|
"errors"
|
2016-01-06 00:01:42 +03:00
|
|
|
"fmt"
|
2019-10-04 00:10:18 +03:00
|
|
|
"math"
|
2017-07-30 23:11:33 +03:00
|
|
|
"sort"
|
2015-12-16 23:40:11 +03:00
|
|
|
"sync"
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
"github.com/btcsuite/btcd/blockchain"
|
2018-06-05 04:34:16 +03:00
|
|
|
"github.com/btcsuite/btcd/btcec"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
2018-06-05 04:34:16 +03:00
|
|
|
"github.com/btcsuite/btcd/txscript"
|
|
|
|
"github.com/btcsuite/btcd/wire"
|
2019-09-24 14:12:53 +03:00
|
|
|
"github.com/btcsuite/btclog"
|
2018-06-05 04:34:16 +03:00
|
|
|
"github.com/btcsuite/btcutil"
|
|
|
|
"github.com/btcsuite/btcutil/txsort"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/davecgh/go-spew/spew"
|
2019-09-24 14:12:53 +03:00
|
|
|
"github.com/lightningnetwork/lnd/build"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/lightningnetwork/lnd/chainntnfs"
|
|
|
|
"github.com/lightningnetwork/lnd/channeldb"
|
|
|
|
"github.com/lightningnetwork/lnd/input"
|
2019-10-31 05:43:05 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwire"
|
2015-12-16 23:40:11 +03:00
|
|
|
)
|
|
|
|
|
2017-01-06 00:56:27 +03:00
|
|
|
var zeroHash chainhash.Hash
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2016-06-21 07:56:54 +03:00
|
|
|
var (
|
2017-02-24 16:32:33 +03:00
|
|
|
// ErrChanClosing is returned when a caller attempts to close a channel
|
|
|
|
// that has already been closed or is in the process of being closed.
|
2016-06-21 07:56:54 +03:00
|
|
|
ErrChanClosing = fmt.Errorf("channel is being closed, operation disallowed")
|
2017-02-24 16:32:33 +03:00
|
|
|
|
2018-02-07 06:11:11 +03:00
|
|
|
// ErrNoWindow is returned when revocation window is exhausted.
|
2017-02-24 16:32:33 +03:00
|
|
|
ErrNoWindow = fmt.Errorf("unable to sign new commitment, the current" +
|
2016-07-22 02:50:20 +03:00
|
|
|
" revocation window is exhausted")
|
2017-02-24 16:32:33 +03:00
|
|
|
|
|
|
|
// ErrMaxWeightCost is returned when the cost/weight (see segwit)
|
|
|
|
// exceeds the widely used maximum allowed policy weight limit. In this
|
|
|
|
// case the commitment transaction can't be propagated through the
|
|
|
|
// network.
|
2016-11-23 11:29:05 +03:00
|
|
|
ErrMaxWeightCost = fmt.Errorf("commitment transaction exceed max " +
|
2017-02-24 16:32:33 +03:00
|
|
|
"available cost")
|
|
|
|
|
|
|
|
// ErrMaxHTLCNumber is returned when a proposed HTLC would exceed the
|
|
|
|
// maximum number of allowed HTLC's if committed in a state transition
|
2016-11-23 11:29:05 +03:00
|
|
|
ErrMaxHTLCNumber = fmt.Errorf("commitment transaction exceed max " +
|
|
|
|
"htlc number")
|
2017-05-19 18:35:28 +03:00
|
|
|
|
2017-11-29 16:20:02 +03:00
|
|
|
// ErrMaxPendingAmount is returned when a proposed HTLC would exceed
|
|
|
|
// the overall maximum pending value of all HTLCs if committed in a
|
|
|
|
// state transition.
|
|
|
|
ErrMaxPendingAmount = fmt.Errorf("commitment transaction exceed max" +
|
|
|
|
"overall pending htlc value")
|
|
|
|
|
|
|
|
// ErrBelowChanReserve is returned when a proposed HTLC would cause
|
|
|
|
// one of the peer's funds to dip below the channel reserve limit.
|
|
|
|
ErrBelowChanReserve = fmt.Errorf("commitment transaction dips peer " +
|
|
|
|
"below chan reserve")
|
|
|
|
|
|
|
|
// ErrBelowMinHTLC is returned when a proposed HTLC has a value that
|
|
|
|
// is below the minimum HTLC value constraint for either us or our
|
|
|
|
// peer depending on which flags are set.
|
|
|
|
ErrBelowMinHTLC = fmt.Errorf("proposed HTLC value is below minimum " +
|
|
|
|
"allowed HTLC value")
|
2017-11-10 10:06:10 +03:00
|
|
|
|
|
|
|
// ErrCannotSyncCommitChains is returned if, upon receiving a ChanSync
|
|
|
|
// message, the state machine deems that is unable to properly
|
2018-07-12 12:02:53 +03:00
|
|
|
// synchronize states with the remote peer. In this case we should fail
|
|
|
|
// the channel, but we won't automatically force close.
|
2017-11-10 10:06:10 +03:00
|
|
|
ErrCannotSyncCommitChains = fmt.Errorf("unable to sync commit chains")
|
2017-11-14 09:45:57 +03:00
|
|
|
|
|
|
|
// ErrInvalidLastCommitSecret is returned in the case that the
|
|
|
|
// commitment secret sent by the remote party in their
|
|
|
|
// ChannelReestablish message doesn't match the last secret we sent.
|
|
|
|
ErrInvalidLastCommitSecret = fmt.Errorf("commit secret is incorrect")
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
// ErrInvalidLocalUnrevokedCommitPoint is returned in the case that the
|
|
|
|
// commitment point sent by the remote party in their
|
|
|
|
// ChannelReestablish message doesn't match the last unrevoked commit
|
|
|
|
// point they sent us.
|
|
|
|
ErrInvalidLocalUnrevokedCommitPoint = fmt.Errorf("unrevoked commit " +
|
|
|
|
"point is invalid")
|
|
|
|
|
|
|
|
// ErrCommitSyncRemoteDataLoss is returned in the case that we receive
|
|
|
|
// a ChannelReestablish message from the remote that advertises a
|
|
|
|
// NextLocalCommitHeight that is lower than what they have already
|
|
|
|
// ACKed, or a RemoteCommitTailHeight that is lower than our revoked
|
|
|
|
// height. In this case we should force close the channel such that
|
|
|
|
// both parties can retrieve their funds.
|
|
|
|
ErrCommitSyncRemoteDataLoss = fmt.Errorf("possible remote commitment " +
|
|
|
|
"state data loss")
|
2016-06-21 07:56:54 +03:00
|
|
|
)
|
|
|
|
|
2019-09-06 14:14:39 +03:00
|
|
|
// ErrCommitSyncLocalDataLoss is returned in the case that we receive a valid
|
|
|
|
// commit secret within the ChannelReestablish message from the remote node AND
|
|
|
|
// they advertise a RemoteCommitTailHeight higher than our current known
|
|
|
|
// height. This means we have lost some critical data, and must fail the
|
|
|
|
// channel and MUST NOT force close it. Instead we should wait for the remote
|
|
|
|
// to force close it, such that we can attempt to sweep our funds. The
|
|
|
|
// commitment point needed to sweep the remote's force close is encapsuled.
|
|
|
|
type ErrCommitSyncLocalDataLoss struct {
|
|
|
|
// ChannelPoint is the identifier for the channel that experienced data
|
|
|
|
// loss.
|
|
|
|
ChannelPoint wire.OutPoint
|
|
|
|
|
|
|
|
// CommitPoint is the last unrevoked commit point, sent to us by the
|
|
|
|
// remote when we determined we had lost state.
|
|
|
|
CommitPoint *btcec.PublicKey
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error returns a string representation of the local data loss error.
|
|
|
|
func (e *ErrCommitSyncLocalDataLoss) Error() string {
|
|
|
|
return fmt.Sprintf("ChannelPoint(%v) with CommitPoint(%x) had "+
|
|
|
|
"possible local commitment state data loss", e.ChannelPoint,
|
|
|
|
e.CommitPoint.SerializeCompressed())
|
|
|
|
}
|
|
|
|
|
2016-06-21 07:56:54 +03:00
|
|
|
// channelState is an enum like type which represents the current state of a
|
|
|
|
// particular channel.
|
2016-07-06 03:01:55 +03:00
|
|
|
// TODO(roasbeef): actually update state
|
2016-06-21 07:56:54 +03:00
|
|
|
type channelState uint8
|
|
|
|
|
|
|
|
const (
|
|
|
|
// channelPending indicates this channel is still going through the
|
|
|
|
// funding workflow, and isn't yet open.
|
2019-09-10 13:27:39 +03:00
|
|
|
channelPending channelState = iota // nolint: unused
|
2016-06-21 07:56:54 +03:00
|
|
|
|
|
|
|
// channelOpen represents an open, active channel capable of
|
|
|
|
// sending/receiving HTLCs.
|
|
|
|
channelOpen
|
|
|
|
|
|
|
|
// channelClosing represents a channel which is in the process of being
|
|
|
|
// closed.
|
|
|
|
channelClosing
|
|
|
|
|
|
|
|
// channelClosed represents a channel which has been fully closed. Note
|
2017-01-13 08:01:50 +03:00
|
|
|
// that before a channel can be closed, ALL pending HTLCs must be
|
2016-06-21 07:56:54 +03:00
|
|
|
// settled/removed.
|
|
|
|
channelClosed
|
|
|
|
|
|
|
|
// channelDispute indicates that an un-cooperative closure has been
|
|
|
|
// detected within the channel.
|
|
|
|
channelDispute
|
|
|
|
|
|
|
|
// channelPendingPayment indicates that there a currently outstanding
|
2017-01-13 08:01:50 +03:00
|
|
|
// HTLCs within the channel.
|
2019-09-10 13:27:39 +03:00
|
|
|
channelPendingPayment // nolint:unused
|
2016-06-21 07:56:54 +03:00
|
|
|
)
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// PaymentHash represents the sha256 of a random value. This hash is used to
|
2016-01-06 00:01:42 +03:00
|
|
|
// uniquely track incoming/outgoing payments within this channel, as well as
|
|
|
|
// payments requested by the wallet/daemon.
|
2016-06-27 09:03:26 +03:00
|
|
|
type PaymentHash [32]byte
|
2015-12-31 09:36:01 +03:00
|
|
|
|
2017-11-10 09:23:17 +03:00
|
|
|
// updateType is the exact type of an entry within the shared HTLC log.
|
2016-07-06 03:01:55 +03:00
|
|
|
type updateType uint8
|
|
|
|
|
|
|
|
const (
|
2017-02-21 03:47:12 +03:00
|
|
|
// Add is an update type that adds a new HTLC entry into the log.
|
2017-04-12 07:27:44 +03:00
|
|
|
// Either side can add a new pending HTLC by adding a new Add entry
|
2017-02-21 03:47:12 +03:00
|
|
|
// into their update log.
|
2016-07-06 03:01:55 +03:00
|
|
|
Add updateType = iota
|
2017-02-21 03:47:12 +03:00
|
|
|
|
|
|
|
// Fail is an update type which removes a prior HTLC entry from the
|
|
|
|
// log. Adding a Fail entry to ones log will modify the _remote_
|
|
|
|
// parties update log once a new commitment view has been evaluated
|
|
|
|
// which contains the Fail entry.
|
|
|
|
Fail
|
|
|
|
|
2017-11-10 09:23:17 +03:00
|
|
|
// MalformedFail is an update type which removes a prior HTLC entry
|
|
|
|
// from the log. Adding a MalformedFail entry to ones log will modify
|
|
|
|
// the _remote_ parties update log once a new commitment view has been
|
|
|
|
// evaluated which contains the MalformedFail entry. The difference
|
2018-05-04 14:18:31 +03:00
|
|
|
// from Fail type lie in the different data we have to store.
|
2017-08-14 14:21:57 +03:00
|
|
|
MalformedFail
|
|
|
|
|
2017-02-21 03:47:12 +03:00
|
|
|
// Settle is an update type which settles a prior HTLC crediting the
|
|
|
|
// balance of the receiving node. Adding a Settle entry to a log will
|
|
|
|
// result in the settle entry being removed on the log as well as the
|
|
|
|
// original add entry from the remote party's log after the next state
|
|
|
|
// transition.
|
2016-07-06 03:01:55 +03:00
|
|
|
Settle
|
2019-01-10 14:23:56 +03:00
|
|
|
|
|
|
|
// FeeUpdate is an update type sent by the channel initiator that
|
|
|
|
// updates the fee rate used when signing the commitment transaction.
|
|
|
|
FeeUpdate
|
2016-07-06 03:01:55 +03:00
|
|
|
)
|
|
|
|
|
2017-08-01 06:37:44 +03:00
|
|
|
// String returns a human readable string that uniquely identifies the target
|
|
|
|
// update type.
|
|
|
|
func (u updateType) String() string {
|
|
|
|
switch u {
|
|
|
|
case Add:
|
|
|
|
return "Add"
|
|
|
|
case Fail:
|
|
|
|
return "Fail"
|
2017-08-14 14:21:57 +03:00
|
|
|
case MalformedFail:
|
|
|
|
return "MalformedFail"
|
2017-08-01 06:37:44 +03:00
|
|
|
case Settle:
|
|
|
|
return "Settle"
|
2019-01-10 14:23:56 +03:00
|
|
|
case FeeUpdate:
|
|
|
|
return "FeeUpdate"
|
2017-08-01 06:37:44 +03:00
|
|
|
default:
|
|
|
|
return "<unknown type>"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// PaymentDescriptor represents a commitment state update which either adds,
|
|
|
|
// settles, or removes an HTLC. PaymentDescriptors encapsulate all necessary
|
2017-01-13 08:01:50 +03:00
|
|
|
// metadata w.r.t to an HTLC, and additional data pairing a settle message to
|
2016-07-06 03:01:55 +03:00
|
|
|
// the original added HTLC.
|
2017-07-30 22:46:55 +03:00
|
|
|
//
|
2016-09-22 04:27:46 +03:00
|
|
|
// TODO(roasbeef): LogEntry interface??
|
2019-01-10 14:23:56 +03:00
|
|
|
// * need to separate attrs for cancel/add/settle/feeupdate
|
2016-07-06 03:01:55 +03:00
|
|
|
type PaymentDescriptor struct {
|
|
|
|
// RHash is the payment hash for this HTLC. The HTLC can be settled iff
|
|
|
|
// the preimage to this hash is presented.
|
|
|
|
RHash PaymentHash
|
|
|
|
|
2017-12-18 05:40:05 +03:00
|
|
|
// RPreimage is the preimage that settles the HTLC pointed to within the
|
2016-09-22 04:27:46 +03:00
|
|
|
// log by the ParentIndex.
|
|
|
|
RPreimage PaymentHash
|
|
|
|
|
2016-11-21 08:54:18 +03:00
|
|
|
// Timeout is the absolute timeout in blocks, after which this HTLC
|
2016-07-06 03:01:55 +03:00
|
|
|
// expires.
|
|
|
|
Timeout uint32
|
|
|
|
|
2017-08-22 09:20:29 +03:00
|
|
|
// Amount is the HTLC amount in milli-satoshis.
|
|
|
|
Amount lnwire.MilliSatoshi
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
// LogIndex is the log entry number that his HTLC update has within the
|
2016-07-06 03:01:55 +03:00
|
|
|
// log. Depending on if IsIncoming is true, this is either an entry the
|
|
|
|
// remote party added, or one that we added locally.
|
2017-10-23 02:28:30 +03:00
|
|
|
LogIndex uint64
|
|
|
|
|
|
|
|
// HtlcIndex is the index within the main update log for this HTLC.
|
2017-10-19 03:36:28 +03:00
|
|
|
// Entries within the log of type Add will have this field populated,
|
2017-10-23 02:28:30 +03:00
|
|
|
// as other entries will point to the entry via this counter.
|
|
|
|
//
|
|
|
|
// NOTE: This field will only be populate if EntryType is Add.
|
|
|
|
HtlcIndex uint64
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2017-10-19 03:36:28 +03:00
|
|
|
// ParentIndex is the HTLC index of the entry that this update settles or
|
|
|
|
// times out.
|
2017-10-23 02:28:30 +03:00
|
|
|
//
|
|
|
|
// NOTE: This field will only be populate if EntryType is Fail or
|
|
|
|
// Settle.
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
ParentIndex uint64
|
2016-07-17 04:12:36 +03:00
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// SourceRef points to an Add update in a forwarding package owned by
|
|
|
|
// this channel.
|
|
|
|
//
|
|
|
|
// NOTE: This field will only be populated if EntryType is Fail or
|
|
|
|
// Settle.
|
|
|
|
SourceRef *channeldb.AddRef
|
|
|
|
|
|
|
|
// DestRef points to a Fail/Settle update in another link's forwarding
|
|
|
|
// package.
|
|
|
|
//
|
|
|
|
// NOTE: This field will only be populated if EntryType is Fail or
|
|
|
|
// Settle, and the forwarded Add successfully included in an outgoing
|
|
|
|
// link's commitment txn.
|
|
|
|
DestRef *channeldb.SettleFailRef
|
|
|
|
|
2018-02-28 07:04:41 +03:00
|
|
|
// OpenCircuitKey references the incoming Chan/HTLC ID of an Add HTLC
|
2018-02-28 07:01:41 +03:00
|
|
|
// packet delivered by the switch.
|
|
|
|
//
|
|
|
|
// NOTE: This field is only populated for payment descriptors in the
|
|
|
|
// *local* update log, and if the Add packet was delivered by the
|
|
|
|
// switch.
|
2018-02-28 07:04:41 +03:00
|
|
|
OpenCircuitKey *channeldb.CircuitKey
|
2018-02-28 07:01:41 +03:00
|
|
|
|
2018-02-28 07:04:41 +03:00
|
|
|
// ClosedCircuitKey references the incoming Chan/HTLC ID of the Add HTLC
|
2018-02-28 07:01:41 +03:00
|
|
|
// that opened the circuit.
|
|
|
|
//
|
|
|
|
// NOTE: This field is only populated for payment descriptors in the
|
|
|
|
// *local* update log, and if settle/fails have a committed circuit in
|
|
|
|
// the circuit map.
|
2018-02-28 07:04:41 +03:00
|
|
|
ClosedCircuitKey *channeldb.CircuitKey
|
2018-02-28 07:01:41 +03:00
|
|
|
|
2017-07-30 22:46:55 +03:00
|
|
|
// localOutputIndex is the output index of this HTLc output in the
|
|
|
|
// commitment transaction of the local node.
|
|
|
|
//
|
2017-11-10 09:23:17 +03:00
|
|
|
// NOTE: If the output is dust from the PoV of the local commitment
|
2017-07-30 22:46:55 +03:00
|
|
|
// chain, then this value will be -1.
|
|
|
|
localOutputIndex int32
|
|
|
|
|
2017-09-25 21:25:58 +03:00
|
|
|
// remoteOutputIndex is the output index of this HTLC output in the
|
2017-07-30 22:46:55 +03:00
|
|
|
// commitment transaction of the remote node.
|
|
|
|
//
|
|
|
|
// NOTE: If the output is dust from the PoV of the remote commitment
|
|
|
|
// chain, then this value will be -1.
|
|
|
|
remoteOutputIndex int32
|
|
|
|
|
|
|
|
// sig is the signature for the second-level HTLC transaction that
|
|
|
|
// spends the version of this HTLC on the commitment transaction of the
|
|
|
|
// local node. This signature is generated by the remote node and
|
|
|
|
// stored by the local node in the case that local node needs to
|
|
|
|
// broadcast their commitment transaction.
|
|
|
|
sig *btcec.Signature
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// addCommitHeight[Remote|Local] encodes the height of the commitment
|
|
|
|
// which included this HTLC on either the remote or local commitment
|
|
|
|
// chain. This value is used to determine when an HTLC is fully
|
|
|
|
// "locked-in".
|
|
|
|
addCommitHeightRemote uint64
|
|
|
|
addCommitHeightLocal uint64
|
|
|
|
|
2016-07-17 04:12:36 +03:00
|
|
|
// removeCommitHeight[Remote|Local] encodes the height of the
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
// commitment which removed the parent pointer of this
|
|
|
|
// PaymentDescriptor either due to a timeout or a settle. Once both
|
2017-10-19 03:36:28 +03:00
|
|
|
// these heights are below the tail of both chains, the log entries can
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
// safely be removed.
|
2016-07-06 03:01:55 +03:00
|
|
|
removeCommitHeightRemote uint64
|
|
|
|
removeCommitHeightLocal uint64
|
|
|
|
|
2017-07-09 02:38:50 +03:00
|
|
|
// OnionBlob is an opaque blob which is used to complete multi-hop
|
2017-04-12 07:27:44 +03:00
|
|
|
// routing.
|
2017-07-09 02:38:50 +03:00
|
|
|
//
|
|
|
|
// NOTE: Populated only on add payment descriptor entry types.
|
|
|
|
OnionBlob []byte
|
2016-11-21 08:54:18 +03:00
|
|
|
|
2017-08-14 14:21:57 +03:00
|
|
|
// ShaOnionBlob is a sha of the onion blob.
|
|
|
|
//
|
2019-01-06 22:39:12 +03:00
|
|
|
// NOTE: Populated only in payment descriptor with MalformedFail type.
|
2017-08-14 14:21:57 +03:00
|
|
|
ShaOnionBlob [sha256.Size]byte
|
|
|
|
|
2019-10-03 18:22:43 +03:00
|
|
|
// FailReason stores the reason why a particular payment was canceled.
|
2017-07-10 13:48:43 +03:00
|
|
|
//
|
|
|
|
// NOTE: Populate only in fail payment descriptor entry types.
|
|
|
|
FailReason []byte
|
|
|
|
|
2019-10-03 18:22:43 +03:00
|
|
|
// FailCode stores the code why a particular payment was canceled.
|
2017-08-14 14:21:57 +03:00
|
|
|
//
|
2019-01-06 22:39:12 +03:00
|
|
|
// NOTE: Populated only in payment descriptor with MalformedFail type.
|
2017-08-14 14:21:57 +03:00
|
|
|
FailCode lnwire.FailCode
|
|
|
|
|
2017-04-12 07:27:44 +03:00
|
|
|
// [our|their|]PkScript are the raw public key scripts that encodes the
|
|
|
|
// redemption rules for this particular HTLC. These fields will only be
|
|
|
|
// populated iff the EntryType of this PaymentDescriptor is Add.
|
|
|
|
// ourPkScript is the ourPkScript from the context of our local
|
|
|
|
// commitment chain. theirPkScript is the latest pkScript from the
|
|
|
|
// context of the remote commitment chain.
|
|
|
|
//
|
|
|
|
// NOTE: These values may change within the logs themselves, however,
|
|
|
|
// they'll stay consistent within the commitment chain entries
|
|
|
|
// themselves.
|
2017-07-30 23:07:38 +03:00
|
|
|
ourPkScript []byte
|
|
|
|
ourWitnessScript []byte
|
|
|
|
theirPkScript []byte
|
|
|
|
theirWitnessScript []byte
|
2017-04-12 07:27:44 +03:00
|
|
|
|
|
|
|
// EntryType denotes the exact type of the PaymentDescriptor. In the
|
|
|
|
// case of a Timeout, or Settle type, then the Parent field will point
|
|
|
|
// into the log to the HTLC being modified.
|
|
|
|
EntryType updateType
|
2017-01-20 16:39:15 +03:00
|
|
|
|
2017-04-12 07:27:44 +03:00
|
|
|
// isForwarded denotes if an incoming HTLC has been forwarded to any
|
|
|
|
// possible upstream peers in the route.
|
|
|
|
isForwarded bool
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// PayDescsFromRemoteLogUpdates converts a slice of LogUpdates received from the
|
|
|
|
// remote peer into PaymentDescriptors to inform a link's forwarding decisions.
|
|
|
|
//
|
|
|
|
// NOTE: The provided `logUpdates` MUST corresponding exactly to either the Adds
|
|
|
|
// or SettleFails in this channel's forwarding package at `height`.
|
2018-02-28 07:04:41 +03:00
|
|
|
func PayDescsFromRemoteLogUpdates(chanID lnwire.ShortChannelID, height uint64,
|
2019-01-10 14:23:56 +03:00
|
|
|
logUpdates []channeldb.LogUpdate) ([]*PaymentDescriptor, error) {
|
2018-02-28 07:01:41 +03:00
|
|
|
|
|
|
|
// Allocate enough space to hold all of the payment descriptors we will
|
|
|
|
// reconstruct, and also the list of pointers that will be returned to
|
|
|
|
// the caller.
|
|
|
|
payDescs := make([]PaymentDescriptor, 0, len(logUpdates))
|
|
|
|
payDescPtrs := make([]*PaymentDescriptor, 0, len(logUpdates))
|
|
|
|
|
|
|
|
// Iterate over the log updates we loaded from disk, and reconstruct the
|
|
|
|
// payment descriptor corresponding to one of the four types of htlcs we
|
|
|
|
// can receive from the remote peer. We only repopulate the information
|
|
|
|
// necessary to process the packets and, if necessary, forward them to
|
|
|
|
// the switch.
|
|
|
|
//
|
|
|
|
// For each log update, we include either an AddRef or a SettleFailRef
|
|
|
|
// so that they can be ACK'd and garbage collected.
|
|
|
|
for i, logUpdate := range logUpdates {
|
|
|
|
var pd PaymentDescriptor
|
|
|
|
switch wireMsg := logUpdate.UpdateMsg.(type) {
|
|
|
|
|
|
|
|
case *lnwire.UpdateAddHTLC:
|
|
|
|
pd = PaymentDescriptor{
|
|
|
|
RHash: wireMsg.PaymentHash,
|
|
|
|
Timeout: wireMsg.Expiry,
|
|
|
|
Amount: wireMsg.Amount,
|
|
|
|
EntryType: Add,
|
|
|
|
HtlcIndex: wireMsg.ID,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
SourceRef: &channeldb.AddRef{
|
|
|
|
Height: height,
|
|
|
|
Index: uint16(i),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
pd.OnionBlob = make([]byte, len(wireMsg.OnionBlob))
|
|
|
|
copy(pd.OnionBlob[:], wireMsg.OnionBlob[:])
|
|
|
|
|
|
|
|
case *lnwire.UpdateFulfillHTLC:
|
|
|
|
pd = PaymentDescriptor{
|
|
|
|
RPreimage: wireMsg.PaymentPreimage,
|
|
|
|
ParentIndex: wireMsg.ID,
|
|
|
|
EntryType: Settle,
|
|
|
|
DestRef: &channeldb.SettleFailRef{
|
2018-02-28 07:04:41 +03:00
|
|
|
Source: chanID,
|
2018-02-28 07:01:41 +03:00
|
|
|
Height: height,
|
|
|
|
Index: uint16(i),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
case *lnwire.UpdateFailHTLC:
|
|
|
|
pd = PaymentDescriptor{
|
|
|
|
ParentIndex: wireMsg.ID,
|
|
|
|
EntryType: Fail,
|
|
|
|
FailReason: wireMsg.Reason[:],
|
|
|
|
DestRef: &channeldb.SettleFailRef{
|
2018-02-28 07:04:41 +03:00
|
|
|
Source: chanID,
|
2018-02-28 07:01:41 +03:00
|
|
|
Height: height,
|
|
|
|
Index: uint16(i),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
case *lnwire.UpdateFailMalformedHTLC:
|
|
|
|
pd = PaymentDescriptor{
|
|
|
|
ParentIndex: wireMsg.ID,
|
|
|
|
EntryType: MalformedFail,
|
|
|
|
FailCode: wireMsg.FailureCode,
|
|
|
|
ShaOnionBlob: wireMsg.ShaOnionBlob,
|
|
|
|
DestRef: &channeldb.SettleFailRef{
|
2018-02-28 07:04:41 +03:00
|
|
|
Source: chanID,
|
2018-02-28 07:01:41 +03:00
|
|
|
Height: height,
|
|
|
|
Index: uint16(i),
|
|
|
|
},
|
|
|
|
}
|
2019-01-10 14:23:56 +03:00
|
|
|
|
|
|
|
// NOTE: UpdateFee is not expected since they are not forwarded.
|
|
|
|
case *lnwire.UpdateFee:
|
|
|
|
return nil, fmt.Errorf("unexpected update fee")
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
payDescs = append(payDescs, pd)
|
|
|
|
payDescPtrs = append(payDescPtrs, &payDescs[i])
|
|
|
|
}
|
|
|
|
|
2019-01-10 14:23:56 +03:00
|
|
|
return payDescPtrs, nil
|
2018-02-28 07:01:41 +03:00
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// commitment represents a commitment to a new state within an active channel.
|
|
|
|
// New commitments can be initiated by either side. Commitments are ordered
|
|
|
|
// into a commitment chain, with one existing for both parties. Each side can
|
2016-10-15 16:18:38 +03:00
|
|
|
// independently extend the other side's commitment chain, up to a certain
|
|
|
|
// "revocation window", which once reached, disallows new commitments until
|
2016-07-06 03:01:55 +03:00
|
|
|
// the local nodes receives the revocation for the remote node's chain tail.
|
|
|
|
type commitment struct {
|
|
|
|
// height represents the commitment height of this commitment, or the
|
|
|
|
// update number of this commitment.
|
|
|
|
height uint64
|
|
|
|
|
2017-11-10 09:23:17 +03:00
|
|
|
// isOurs indicates whether this is the local or remote node's version
|
|
|
|
// of the commitment.
|
2017-09-25 23:05:49 +03:00
|
|
|
isOurs bool
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// [our|their]MessageIndex are indexes into the HTLC log, up to which
|
|
|
|
// this commitment transaction includes. These indexes allow both sides
|
2016-10-15 16:18:38 +03:00
|
|
|
// to independently, and concurrent send create new commitments. Each
|
2016-07-06 03:01:55 +03:00
|
|
|
// new commitment sent to the remote party includes an index in the
|
|
|
|
// shared log which details which of their updates we're including in
|
|
|
|
// this new commitment.
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
ourMessageIndex uint64
|
|
|
|
theirMessageIndex uint64
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2017-11-10 09:23:17 +03:00
|
|
|
// [our|their]HtlcIndex are the current running counters for the HTLC's
|
|
|
|
// offered by either party. This value is incremented each time a party
|
|
|
|
// offers a new HTLC. The log update methods that consume HTLC's will
|
|
|
|
// reference these counters, rather than the running cumulative message
|
|
|
|
// counters.
|
|
|
|
ourHtlcIndex uint64
|
|
|
|
theirHtlcIndex uint64
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// txn is the commitment transaction generated by including any HTLC
|
|
|
|
// updates whose index are below the two indexes listed above. If this
|
|
|
|
// commitment is being added to the remote chain, then this txn is
|
|
|
|
// their version of the commitment transactions. If the local commit
|
|
|
|
// chain is being modified, the opposite is true.
|
|
|
|
txn *wire.MsgTx
|
|
|
|
|
|
|
|
// sig is a signature for the above commitment transaction.
|
|
|
|
sig []byte
|
|
|
|
|
|
|
|
// [our|their]Balance represents the settled balances at this point
|
|
|
|
// within the commitment chain. This balance is computed by properly
|
|
|
|
// evaluating all the add/remove/settle log entries before the listed
|
|
|
|
// indexes.
|
2017-11-29 16:20:02 +03:00
|
|
|
//
|
2020-03-06 18:11:46 +03:00
|
|
|
// NOTE: This is the balance *after* subtracting any commitment fee,
|
|
|
|
// AND anchor output values.
|
2017-08-22 09:20:29 +03:00
|
|
|
ourBalance lnwire.MilliSatoshi
|
|
|
|
theirBalance lnwire.MilliSatoshi
|
2016-09-07 20:45:27 +03:00
|
|
|
|
2017-05-01 08:53:54 +03:00
|
|
|
// fee is the amount that will be paid as fees for this commitment
|
2017-11-10 09:23:17 +03:00
|
|
|
// transaction. The fee is recorded here so that it can be added back
|
|
|
|
// and recalculated for each new update to the channel state.
|
2017-05-01 08:53:54 +03:00
|
|
|
fee btcutil.Amount
|
|
|
|
|
2017-07-14 21:38:35 +03:00
|
|
|
// feePerKw is the fee per kw used to calculate this commitment
|
|
|
|
// transaction's fee.
|
2019-10-31 05:43:05 +03:00
|
|
|
feePerKw chainfee.SatPerKWeight
|
2017-07-14 21:38:35 +03:00
|
|
|
|
2017-11-10 09:23:17 +03:00
|
|
|
// dustLimit is the limit on the commitment transaction such that no
|
|
|
|
// output values should be below this amount.
|
2017-09-25 23:05:49 +03:00
|
|
|
dustLimit btcutil.Amount
|
|
|
|
|
2017-07-30 22:46:55 +03:00
|
|
|
// outgoingHTLCs is a slice of all the outgoing HTLC's (from our PoV)
|
|
|
|
// on this commitment transaction.
|
2017-04-12 07:31:22 +03:00
|
|
|
outgoingHTLCs []PaymentDescriptor
|
2016-09-07 20:45:27 +03:00
|
|
|
|
2017-07-30 22:46:55 +03:00
|
|
|
// incomingHTLCs is a slice of all the incoming HTLC's (from our PoV)
|
|
|
|
// on this commitment transaction.
|
|
|
|
incomingHTLCs []PaymentDescriptor
|
2017-01-20 13:51:48 +03:00
|
|
|
|
2017-07-30 22:46:55 +03:00
|
|
|
// [outgoing|incoming]HTLCIndex is an index that maps an output index
|
|
|
|
// on the commitment transaction to the payment descriptor that
|
2017-11-10 09:23:17 +03:00
|
|
|
// represents the HTLC output.
|
|
|
|
//
|
|
|
|
// NOTE: that these fields are only populated if this commitment state
|
|
|
|
// belongs to the local node. These maps are used when validating any
|
|
|
|
// HTLC signatures which are part of the local commitment state. We use
|
|
|
|
// this map in order to locate the details needed to validate an HTLC
|
|
|
|
// signature while iterating of the outputs in the local commitment
|
|
|
|
// view.
|
2017-09-25 21:25:58 +03:00
|
|
|
outgoingHTLCIndex map[int32]*PaymentDescriptor
|
2017-07-30 22:46:55 +03:00
|
|
|
incomingHTLCIndex map[int32]*PaymentDescriptor
|
|
|
|
}
|
|
|
|
|
|
|
|
// locateOutputIndex is a small helper function to locate the output index of a
|
|
|
|
// particular HTLC within the current commitment transaction. The duplicate map
|
|
|
|
// massed in is to be retained for each output within the commitment
|
|
|
|
// transition. This ensures that we don't assign multiple HTLC's to the same
|
|
|
|
// index within the commitment transaction.
|
|
|
|
func locateOutputIndex(p *PaymentDescriptor, tx *wire.MsgTx, ourCommit bool,
|
|
|
|
dups map[PaymentHash][]int32) (int32, error) {
|
2016-09-07 20:45:27 +03:00
|
|
|
|
2017-07-30 22:46:55 +03:00
|
|
|
// Checks to see if element (e) exists in slice (s).
|
|
|
|
contains := func(s []int32, e int32) bool {
|
2017-01-20 13:51:48 +03:00
|
|
|
for _, a := range s {
|
|
|
|
if a == e {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2017-07-30 22:46:55 +03:00
|
|
|
// If this their commitment transaction, we'll be trying to locate
|
|
|
|
// their pkScripts, otherwise we'll be looking for ours. This is
|
|
|
|
// required as the commitment states are asymmetric in order to ascribe
|
|
|
|
// blame in the case of a contract breach.
|
|
|
|
pkScript := p.theirPkScript
|
|
|
|
if ourCommit {
|
|
|
|
pkScript = p.ourPkScript
|
|
|
|
}
|
|
|
|
|
|
|
|
for i, txOut := range tx.TxOut {
|
|
|
|
if bytes.Equal(txOut.PkScript, pkScript) &&
|
2017-08-31 01:25:01 +03:00
|
|
|
txOut.Value == int64(p.Amount.ToSatoshis()) {
|
2017-07-30 22:46:55 +03:00
|
|
|
|
|
|
|
// If this payment hash and index has already been
|
|
|
|
// found, then we'll continue in order to avoid any
|
|
|
|
// duplicate indexes.
|
|
|
|
if contains(dups[p.RHash], int32(i)) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
idx := int32(i)
|
|
|
|
dups[p.RHash] = append(dups[p.RHash], idx)
|
|
|
|
return idx, nil
|
2017-01-20 14:37:30 +03:00
|
|
|
}
|
2017-07-30 22:46:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0, fmt.Errorf("unable to find htlc: script=%x, value=%v",
|
|
|
|
pkScript, p.Amount)
|
|
|
|
}
|
|
|
|
|
|
|
|
// populateHtlcIndexes modifies the set of HTLC's locked-into the target view
|
|
|
|
// to have full indexing information populated. This information is required as
|
|
|
|
// we need to keep track of the indexes of each HTLC in order to properly write
|
|
|
|
// the current state to disk, and also to locate the PaymentDescriptor
|
|
|
|
// corresponding to HTLC outputs in the commitment transaction.
|
2020-03-06 18:11:49 +03:00
|
|
|
func (c *commitment) populateHtlcIndexes(chanType channeldb.ChannelType) error {
|
2017-07-30 22:46:55 +03:00
|
|
|
// First, we'll set up some state to allow us to locate the output
|
|
|
|
// index of the all the HTLC's within the commitment transaction. We
|
|
|
|
// must keep this index so we can validate the HTLC signatures sent to
|
|
|
|
// us.
|
|
|
|
dups := make(map[PaymentHash][]int32)
|
2017-09-25 21:25:58 +03:00
|
|
|
c.outgoingHTLCIndex = make(map[int32]*PaymentDescriptor)
|
2017-07-30 22:46:55 +03:00
|
|
|
c.incomingHTLCIndex = make(map[int32]*PaymentDescriptor)
|
|
|
|
|
|
|
|
// populateIndex is a helper function that populates the necessary
|
|
|
|
// indexes within the commitment view for a particular HTLC.
|
|
|
|
populateIndex := func(htlc *PaymentDescriptor, incoming bool) error {
|
2020-03-06 18:11:49 +03:00
|
|
|
isDust := htlcIsDust(
|
|
|
|
chanType, incoming, c.isOurs, c.feePerKw,
|
|
|
|
htlc.Amount.ToSatoshis(), c.dustLimit,
|
|
|
|
)
|
2017-07-30 22:46:55 +03:00
|
|
|
|
|
|
|
var err error
|
|
|
|
switch {
|
|
|
|
|
|
|
|
// If this is our commitment transaction, and this is a dust
|
|
|
|
// output then we mark it as such using a -1 index.
|
2017-11-10 09:28:35 +03:00
|
|
|
case c.isOurs && isDust:
|
2017-07-30 22:46:55 +03:00
|
|
|
htlc.localOutputIndex = -1
|
|
|
|
|
|
|
|
// If this is the commitment transaction of the remote party,
|
|
|
|
// and this is a dust output then we mark it as such using a -1
|
|
|
|
// index.
|
2017-11-10 09:28:35 +03:00
|
|
|
case !c.isOurs && isDust:
|
2017-07-30 22:46:55 +03:00
|
|
|
htlc.remoteOutputIndex = -1
|
|
|
|
|
|
|
|
// If this is our commitment transaction, then we'll need to
|
|
|
|
// locate the output and the index so we can verify an HTLC
|
|
|
|
// signatures.
|
2017-11-10 09:28:35 +03:00
|
|
|
case c.isOurs:
|
|
|
|
htlc.localOutputIndex, err = locateOutputIndex(
|
|
|
|
htlc, c.txn, c.isOurs, dups,
|
|
|
|
)
|
2017-07-30 22:46:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// As this is our commitment transactions, we need to
|
|
|
|
// keep track of the locations of each output on the
|
|
|
|
// transaction so we can verify any HTLC signatures
|
|
|
|
// sent to us after we construct the HTLC view.
|
|
|
|
if incoming {
|
|
|
|
c.incomingHTLCIndex[htlc.localOutputIndex] = htlc
|
|
|
|
} else {
|
2017-09-25 21:25:58 +03:00
|
|
|
c.outgoingHTLCIndex[htlc.localOutputIndex] = htlc
|
2017-07-30 22:46:55 +03:00
|
|
|
}
|
2017-03-25 02:25:59 +03:00
|
|
|
|
2017-07-30 22:46:55 +03:00
|
|
|
// Otherwise, this is there remote party's commitment
|
|
|
|
// transaction and we only need to populate the remote output
|
|
|
|
// index within the HTLC index.
|
2017-11-10 09:28:35 +03:00
|
|
|
case !c.isOurs:
|
|
|
|
htlc.remoteOutputIndex, err = locateOutputIndex(
|
|
|
|
htlc, c.txn, c.isOurs, dups,
|
|
|
|
)
|
2017-07-30 22:46:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-11-21 08:54:18 +03:00
|
|
|
}
|
2017-07-30 22:46:55 +03:00
|
|
|
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("invalid commitment configuration")
|
2016-11-21 08:54:18 +03:00
|
|
|
}
|
2017-07-30 22:46:55 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll need to locate the index within the commitment
|
|
|
|
// transaction of all the HTLC outputs. This index will be required
|
|
|
|
// later when we write the commitment state to disk, and also when
|
|
|
|
// generating signatures for each of the HTLC transactions.
|
|
|
|
for i := 0; i < len(c.outgoingHTLCs); i++ {
|
|
|
|
htlc := &c.outgoingHTLCs[i]
|
|
|
|
if err := populateIndex(htlc, false); err != nil {
|
2018-05-04 14:18:31 +03:00
|
|
|
return err
|
2017-01-20 15:20:02 +03:00
|
|
|
}
|
2017-07-30 22:46:55 +03:00
|
|
|
}
|
|
|
|
for i := 0; i < len(c.incomingHTLCs); i++ {
|
|
|
|
htlc := &c.incomingHTLCs[i]
|
|
|
|
if err := populateIndex(htlc, true); err != nil {
|
2018-05-04 14:18:31 +03:00
|
|
|
return err
|
2017-07-30 22:46:55 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
// toDiskCommit converts the target commitment into a format suitable to be
|
2017-07-30 22:46:55 +03:00
|
|
|
// written to disk after an accepted state transition.
|
2017-11-10 09:51:03 +03:00
|
|
|
func (c *commitment) toDiskCommit(ourCommit bool) *channeldb.ChannelCommitment {
|
2017-08-15 20:09:16 +03:00
|
|
|
numHtlcs := len(c.outgoingHTLCs) + len(c.incomingHTLCs)
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
commit := &channeldb.ChannelCommitment{
|
|
|
|
CommitHeight: c.height,
|
|
|
|
LocalLogIndex: c.ourMessageIndex,
|
|
|
|
LocalHtlcIndex: c.ourHtlcIndex,
|
|
|
|
RemoteLogIndex: c.theirMessageIndex,
|
|
|
|
RemoteHtlcIndex: c.theirHtlcIndex,
|
|
|
|
LocalBalance: c.ourBalance,
|
|
|
|
RemoteBalance: c.theirBalance,
|
|
|
|
CommitFee: c.fee,
|
2018-02-13 16:43:58 +03:00
|
|
|
FeePerKw: btcutil.Amount(c.feePerKw),
|
2017-11-10 09:51:03 +03:00
|
|
|
CommitTx: c.txn,
|
|
|
|
CommitSig: c.sig,
|
|
|
|
Htlcs: make([]channeldb.HTLC, 0, numHtlcs),
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, htlc := range c.outgoingHTLCs {
|
2017-07-30 22:46:55 +03:00
|
|
|
outputIndex := htlc.localOutputIndex
|
|
|
|
if !ourCommit {
|
|
|
|
outputIndex = htlc.remoteOutputIndex
|
2017-01-20 16:39:15 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
h := channeldb.HTLC{
|
|
|
|
RHash: htlc.RHash,
|
|
|
|
Amt: htlc.Amount,
|
|
|
|
RefundTimeout: htlc.Timeout,
|
|
|
|
OutputIndex: outputIndex,
|
|
|
|
HtlcIndex: htlc.HtlcIndex,
|
|
|
|
LogIndex: htlc.LogIndex,
|
|
|
|
Incoming: false,
|
|
|
|
}
|
|
|
|
h.OnionBlob = make([]byte, len(htlc.OnionBlob))
|
|
|
|
copy(h.OnionBlob[:], htlc.OnionBlob)
|
|
|
|
|
|
|
|
if ourCommit && htlc.sig != nil {
|
|
|
|
h.Signature = htlc.sig.Serialize()
|
|
|
|
}
|
|
|
|
|
|
|
|
commit.Htlcs = append(commit.Htlcs, h)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, htlc := range c.incomingHTLCs {
|
|
|
|
outputIndex := htlc.localOutputIndex
|
|
|
|
if !ourCommit {
|
|
|
|
outputIndex = htlc.remoteOutputIndex
|
2017-08-15 20:09:16 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
h := channeldb.HTLC{
|
|
|
|
RHash: htlc.RHash,
|
|
|
|
Amt: htlc.Amount,
|
|
|
|
RefundTimeout: htlc.Timeout,
|
|
|
|
OutputIndex: outputIndex,
|
|
|
|
HtlcIndex: htlc.HtlcIndex,
|
|
|
|
LogIndex: htlc.LogIndex,
|
|
|
|
Incoming: true,
|
|
|
|
}
|
|
|
|
h.OnionBlob = make([]byte, len(htlc.OnionBlob))
|
|
|
|
copy(h.OnionBlob[:], htlc.OnionBlob)
|
2017-07-30 22:46:55 +03:00
|
|
|
|
|
|
|
if ourCommit && htlc.sig != nil {
|
|
|
|
h.Signature = htlc.sig.Serialize()
|
2016-09-07 20:45:27 +03:00
|
|
|
}
|
2017-07-30 22:46:55 +03:00
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
commit.Htlcs = append(commit.Htlcs, h)
|
2016-09-07 20:45:27 +03:00
|
|
|
}
|
2017-03-25 02:25:59 +03:00
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
return commit
|
|
|
|
}
|
|
|
|
|
|
|
|
// diskHtlcToPayDesc converts an HTLC previously written to disk within a
|
|
|
|
// commitment state to the form required to manipulate in memory within the
|
|
|
|
// commitment struct and updateLog. This function is used when we need to
|
|
|
|
// restore commitment state written do disk back into memory once we need to
|
|
|
|
// restart a channel session.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (lc *LightningChannel) diskHtlcToPayDesc(feeRate chainfee.SatPerKWeight,
|
2018-05-28 23:09:24 +03:00
|
|
|
commitHeight uint64, htlc *channeldb.HTLC, localCommitKeys,
|
|
|
|
remoteCommitKeys *CommitmentKeyRing) (PaymentDescriptor, error) {
|
2017-11-10 09:51:03 +03:00
|
|
|
|
|
|
|
// The proper pkScripts for this PaymentDescriptor must be
|
|
|
|
// generated so we can easily locate them within the commitment
|
|
|
|
// transaction in the future.
|
|
|
|
var (
|
|
|
|
ourP2WSH, theirP2WSH []byte
|
|
|
|
ourWitnessScript, theirWitnessScript []byte
|
|
|
|
pd PaymentDescriptor
|
|
|
|
err error
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType = lc.channelState.ChanType
|
2017-11-10 09:51:03 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// If the either outputs is dust from the local or remote node's
|
|
|
|
// perspective, then we don't need to generate the scripts as we only
|
|
|
|
// generate them in order to locate the outputs within the commitment
|
|
|
|
// transaction. As we'll mark dust with a special output index in the
|
|
|
|
// on-disk state snapshot.
|
2020-03-06 18:11:49 +03:00
|
|
|
isDustLocal := htlcIsDust(
|
|
|
|
chanType, htlc.Incoming, true, feeRate,
|
|
|
|
htlc.Amt.ToSatoshis(), lc.channelState.LocalChanCfg.DustLimit,
|
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
if !isDustLocal && localCommitKeys != nil {
|
|
|
|
ourP2WSH, ourWitnessScript, err = genHtlcScript(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, htlc.Incoming, true, htlc.RefundTimeout,
|
|
|
|
htlc.RHash, localCommitKeys,
|
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
if err != nil {
|
|
|
|
return pd, err
|
|
|
|
}
|
|
|
|
}
|
2020-03-06 18:11:49 +03:00
|
|
|
isDustRemote := htlcIsDust(
|
|
|
|
chanType, htlc.Incoming, false, feeRate,
|
|
|
|
htlc.Amt.ToSatoshis(), lc.channelState.RemoteChanCfg.DustLimit,
|
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
if !isDustRemote && remoteCommitKeys != nil {
|
|
|
|
theirP2WSH, theirWitnessScript, err = genHtlcScript(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, htlc.Incoming, false, htlc.RefundTimeout,
|
|
|
|
htlc.RHash, remoteCommitKeys,
|
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
if err != nil {
|
|
|
|
return pd, err
|
|
|
|
}
|
2017-08-15 20:09:16 +03:00
|
|
|
}
|
2017-07-30 22:46:55 +03:00
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
// With the scripts reconstructed (depending on if this is our commit
|
|
|
|
// vs theirs or a pending commit for the remote party), we can now
|
|
|
|
// re-create the original payment descriptor.
|
|
|
|
pd = PaymentDescriptor{
|
|
|
|
RHash: htlc.RHash,
|
|
|
|
Timeout: htlc.RefundTimeout,
|
|
|
|
Amount: htlc.Amt,
|
|
|
|
EntryType: Add,
|
|
|
|
HtlcIndex: htlc.HtlcIndex,
|
|
|
|
LogIndex: htlc.LogIndex,
|
|
|
|
OnionBlob: htlc.OnionBlob,
|
|
|
|
ourPkScript: ourP2WSH,
|
|
|
|
ourWitnessScript: ourWitnessScript,
|
|
|
|
theirPkScript: theirP2WSH,
|
|
|
|
theirWitnessScript: theirWitnessScript,
|
|
|
|
}
|
|
|
|
|
|
|
|
return pd, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// extractPayDescs will convert all HTLC's present within a disk commit state
|
|
|
|
// to a set of incoming and outgoing payment descriptors. Once reconstructed,
|
|
|
|
// these payment descriptors can be re-inserted into the in-memory updateLog
|
|
|
|
// for each side.
|
|
|
|
func (lc *LightningChannel) extractPayDescs(commitHeight uint64,
|
2019-10-31 05:43:05 +03:00
|
|
|
feeRate chainfee.SatPerKWeight, htlcs []channeldb.HTLC, localCommitKeys,
|
2018-01-19 00:45:30 +03:00
|
|
|
remoteCommitKeys *CommitmentKeyRing) ([]PaymentDescriptor, []PaymentDescriptor, error) {
|
2017-11-10 09:51:03 +03:00
|
|
|
|
|
|
|
var (
|
|
|
|
incomingHtlcs []PaymentDescriptor
|
|
|
|
outgoingHtlcs []PaymentDescriptor
|
|
|
|
)
|
|
|
|
|
|
|
|
// For each included HTLC within this commitment state, we'll convert
|
|
|
|
// the disk format into our in memory PaymentDescriptor format,
|
|
|
|
// partitioning based on if we offered or received the HTLC.
|
|
|
|
for _, htlc := range htlcs {
|
|
|
|
// TODO(roasbeef): set isForwarded to false for all? need to
|
|
|
|
// persist state w.r.t to if forwarded or not, or can
|
|
|
|
// inadvertently trigger replays
|
|
|
|
|
|
|
|
payDesc, err := lc.diskHtlcToPayDesc(
|
2018-05-28 23:09:24 +03:00
|
|
|
feeRate, commitHeight, &htlc,
|
2017-11-10 09:51:03 +03:00
|
|
|
localCommitKeys, remoteCommitKeys,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return incomingHtlcs, outgoingHtlcs, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if htlc.Incoming {
|
|
|
|
incomingHtlcs = append(incomingHtlcs, payDesc)
|
|
|
|
} else {
|
|
|
|
outgoingHtlcs = append(outgoingHtlcs, payDesc)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return incomingHtlcs, outgoingHtlcs, nil
|
|
|
|
}
|
|
|
|
|
2018-05-26 04:37:45 +03:00
|
|
|
// diskCommitToMemCommit converts the on-disk commitment format to our
|
2017-11-10 09:51:03 +03:00
|
|
|
// in-memory commitment format which is needed in order to properly resume
|
|
|
|
// channel operations after a restart.
|
2018-05-28 23:09:24 +03:00
|
|
|
func (lc *LightningChannel) diskCommitToMemCommit(isLocal bool,
|
|
|
|
diskCommit *channeldb.ChannelCommitment, localCommitPoint,
|
|
|
|
remoteCommitPoint *btcec.PublicKey) (*commitment, error) {
|
2017-11-10 09:51:03 +03:00
|
|
|
|
|
|
|
// First, we'll need to re-derive the commitment key ring for each
|
|
|
|
// party used within this particular state. If this is a pending commit
|
|
|
|
// (we extended but weren't able to complete the commitment dance
|
|
|
|
// before shutdown), then the localCommitPoint won't be set as we
|
|
|
|
// haven't yet received a responding commitment from the remote party.
|
2018-01-19 00:45:30 +03:00
|
|
|
var localCommitKeys, remoteCommitKeys *CommitmentKeyRing
|
2017-11-10 09:51:03 +03:00
|
|
|
if localCommitPoint != nil {
|
2019-09-17 05:06:19 +03:00
|
|
|
localCommitKeys = DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
localCommitPoint, true, lc.channelState.ChanType,
|
2020-01-06 13:42:02 +03:00
|
|
|
&lc.channelState.LocalChanCfg,
|
|
|
|
&lc.channelState.RemoteChanCfg,
|
2019-03-11 02:38:45 +03:00
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
}
|
|
|
|
if remoteCommitPoint != nil {
|
2019-09-17 05:06:19 +03:00
|
|
|
remoteCommitKeys = DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
remoteCommitPoint, false, lc.channelState.ChanType,
|
2020-01-06 13:42:02 +03:00
|
|
|
&lc.channelState.LocalChanCfg,
|
|
|
|
&lc.channelState.RemoteChanCfg,
|
2019-03-11 02:38:45 +03:00
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// With the key rings re-created, we'll now convert all the on-disk
|
|
|
|
// HTLC"s into PaymentDescriptor's so we can re-insert them into our
|
|
|
|
// update log.
|
|
|
|
incomingHtlcs, outgoingHtlcs, err := lc.extractPayDescs(
|
2019-10-31 05:43:05 +03:00
|
|
|
diskCommit.CommitHeight,
|
|
|
|
chainfee.SatPerKWeight(diskCommit.FeePerKw),
|
2018-05-28 23:09:24 +03:00
|
|
|
diskCommit.Htlcs, localCommitKeys, remoteCommitKeys,
|
2017-11-10 09:51:03 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// With the necessary items generated, we'll now re-construct the
|
|
|
|
// commitment state as it was originally present in memory.
|
|
|
|
commit := &commitment{
|
|
|
|
height: diskCommit.CommitHeight,
|
|
|
|
isOurs: isLocal,
|
|
|
|
ourBalance: diskCommit.LocalBalance,
|
|
|
|
theirBalance: diskCommit.RemoteBalance,
|
|
|
|
ourMessageIndex: diskCommit.LocalLogIndex,
|
|
|
|
ourHtlcIndex: diskCommit.LocalHtlcIndex,
|
|
|
|
theirMessageIndex: diskCommit.RemoteLogIndex,
|
|
|
|
theirHtlcIndex: diskCommit.RemoteHtlcIndex,
|
|
|
|
txn: diskCommit.CommitTx,
|
|
|
|
sig: diskCommit.CommitSig,
|
|
|
|
fee: diskCommit.CommitFee,
|
2019-10-31 05:43:05 +03:00
|
|
|
feePerKw: chainfee.SatPerKWeight(diskCommit.FeePerKw),
|
2017-11-10 09:51:03 +03:00
|
|
|
incomingHTLCs: incomingHtlcs,
|
|
|
|
outgoingHTLCs: outgoingHtlcs,
|
|
|
|
}
|
|
|
|
if isLocal {
|
|
|
|
commit.dustLimit = lc.channelState.LocalChanCfg.DustLimit
|
|
|
|
} else {
|
|
|
|
commit.dustLimit = lc.channelState.RemoteChanCfg.DustLimit
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll re-populate the HTLC index for this state so we can
|
|
|
|
// properly locate each HTLC within the commitment transaction.
|
2020-03-06 18:11:49 +03:00
|
|
|
err = commit.populateHtlcIndexes(lc.channelState.ChanType)
|
|
|
|
if err != nil {
|
2017-11-10 09:51:03 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return commit, nil
|
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// commitmentChain represents a chain of unrevoked commitments. The tail of the
|
|
|
|
// chain is the latest fully signed, yet unrevoked commitment. Two chains are
|
|
|
|
// tracked, one for the local node, and another for the remote node. New
|
2016-10-15 16:18:38 +03:00
|
|
|
// commitments we create locally extend the remote node's chain, and vice
|
2016-07-06 03:01:55 +03:00
|
|
|
// versa. Commitment chains are allowed to grow to a bounded length, after
|
|
|
|
// which the tail needs to be "dropped" before new commitments can be received.
|
|
|
|
// The tail is "dropped" when the owner of the chain sends a revocation for the
|
|
|
|
// previous tail.
|
|
|
|
type commitmentChain struct {
|
|
|
|
// commitments is a linked list of commitments to new states. New
|
|
|
|
// commitments are added to the end of the chain with increase height.
|
|
|
|
// Once a commitment transaction is revoked, the tail is incremented,
|
|
|
|
// freeing up the revocation window for new commitments.
|
|
|
|
commitments *list.List
|
|
|
|
}
|
|
|
|
|
2018-11-20 17:09:45 +03:00
|
|
|
// newCommitmentChain creates a new commitment chain.
|
|
|
|
func newCommitmentChain() *commitmentChain {
|
2016-07-06 03:01:55 +03:00
|
|
|
return &commitmentChain{
|
2018-11-20 17:09:45 +03:00
|
|
|
commitments: list.New(),
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// addCommitment extends the commitment chain by a single commitment. This
|
2017-11-10 09:31:40 +03:00
|
|
|
// added commitment represents a state update proposed by either party. Once
|
|
|
|
// the commitment prior to this commitment is revoked, the commitment becomes
|
|
|
|
// the new defacto state within the channel.
|
2016-07-06 03:01:55 +03:00
|
|
|
func (s *commitmentChain) addCommitment(c *commitment) {
|
|
|
|
s.commitments.PushBack(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
// advanceTail reduces the length of the commitment chain by one. The tail of
|
|
|
|
// the chain should be advanced once a revocation for the lowest unrevoked
|
|
|
|
// commitment in the chain is received.
|
|
|
|
func (s *commitmentChain) advanceTail() {
|
|
|
|
s.commitments.Remove(s.commitments.Front())
|
|
|
|
}
|
|
|
|
|
|
|
|
// tip returns the latest commitment added to the chain.
|
|
|
|
func (s *commitmentChain) tip() *commitment {
|
|
|
|
return s.commitments.Back().Value.(*commitment)
|
|
|
|
}
|
|
|
|
|
|
|
|
// tail returns the lowest unrevoked commitment transaction in the chain.
|
|
|
|
func (s *commitmentChain) tail() *commitment {
|
|
|
|
return s.commitments.Front().Value.(*commitment)
|
|
|
|
}
|
|
|
|
|
2017-10-19 03:36:28 +03:00
|
|
|
// hasUnackedCommitment returns true if the commitment chain has more than one
|
|
|
|
// entry. The tail of the commitment chain has been ACKed by revoking all prior
|
|
|
|
// commitments, but any subsequent commitments have not yet been ACKed.
|
|
|
|
func (s *commitmentChain) hasUnackedCommitment() bool {
|
|
|
|
return s.commitments.Front() != s.commitments.Back()
|
|
|
|
}
|
|
|
|
|
2017-02-21 04:45:53 +03:00
|
|
|
// updateLog is an append-only log that stores updates to a node's commitment
|
|
|
|
// chain. This structure can be seen as the "mempool" within Lightning where
|
|
|
|
// changes are stored before they're committed to the chain. Once an entry has
|
|
|
|
// been committed in both the local and remote commitment chain, then it can be
|
|
|
|
// removed from this log.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): create lightning package, move commitment and update to
|
|
|
|
// package?
|
|
|
|
// * also move state machine, separate from lnwallet package
|
|
|
|
// * possible embed updateLog within commitmentChain.
|
|
|
|
type updateLog struct {
|
|
|
|
// logIndex is a monotonically increasing integer that tracks the total
|
|
|
|
// number of update entries ever applied to the log. When sending new
|
|
|
|
// commitment states, we include all updates up to this index.
|
|
|
|
logIndex uint64
|
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
// htlcCounter is a monotonically increasing integer that tracks the
|
|
|
|
// total number of offered HTLC's by the owner of this update log. We
|
|
|
|
// use a distinct index for this purpose, as update's that remove
|
2018-02-07 06:11:11 +03:00
|
|
|
// entries from the log will be indexed using this counter.
|
2017-10-23 02:28:30 +03:00
|
|
|
htlcCounter uint64
|
|
|
|
|
2017-02-21 04:45:53 +03:00
|
|
|
// List is the updatelog itself, we embed this value so updateLog has
|
|
|
|
// access to all the method of a list.List.
|
|
|
|
*list.List
|
|
|
|
|
|
|
|
// updateIndex is an index that maps a particular entries index to the
|
|
|
|
// list element within the list.List above.
|
|
|
|
updateIndex map[uint64]*list.Element
|
2017-10-23 02:28:30 +03:00
|
|
|
|
|
|
|
// offerIndex is an index that maps the counter for offered HTLC's to
|
2018-02-07 06:11:11 +03:00
|
|
|
// their list element within the main list.List.
|
2017-10-23 02:28:30 +03:00
|
|
|
htlcIndex map[uint64]*list.Element
|
2018-05-26 04:37:45 +03:00
|
|
|
|
|
|
|
// modifiedHtlcs is a set that keeps track of all the current modified
|
|
|
|
// htlcs. A modified HTLC is one that's present in the log, and has as
|
|
|
|
// a pending fail or settle that's attempting to consume it.
|
|
|
|
modifiedHtlcs map[uint64]struct{}
|
2017-02-21 04:45:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// newUpdateLog creates a new updateLog instance.
|
2017-11-10 09:31:40 +03:00
|
|
|
func newUpdateLog(logIndex, htlcCounter uint64) *updateLog {
|
2017-02-21 04:45:53 +03:00
|
|
|
return &updateLog{
|
2018-05-26 04:37:45 +03:00
|
|
|
List: list.New(),
|
|
|
|
updateIndex: make(map[uint64]*list.Element),
|
|
|
|
htlcIndex: make(map[uint64]*list.Element),
|
|
|
|
logIndex: logIndex,
|
|
|
|
htlcCounter: htlcCounter,
|
|
|
|
modifiedHtlcs: make(map[uint64]struct{}),
|
2017-11-10 09:31:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// restoreHtlc will "restore" a prior HTLC to the updateLog. We say restore as
|
|
|
|
// this method is intended to be used when re-covering a prior commitment
|
|
|
|
// state. This function differs from appendHtlc in that it won't increment
|
|
|
|
// either of log's counters. If the HTLC is already present, then it is
|
|
|
|
// ignored.
|
|
|
|
func (u *updateLog) restoreHtlc(pd *PaymentDescriptor) {
|
|
|
|
if _, ok := u.htlcIndex[pd.HtlcIndex]; ok {
|
|
|
|
return
|
2017-02-21 04:45:53 +03:00
|
|
|
}
|
2017-11-10 09:31:40 +03:00
|
|
|
|
|
|
|
u.htlcIndex[pd.HtlcIndex] = u.PushBack(pd)
|
2017-02-21 04:45:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// appendUpdate appends a new update to the tip of the updateLog. The entry is
|
|
|
|
// also added to index accordingly.
|
|
|
|
func (u *updateLog) appendUpdate(pd *PaymentDescriptor) {
|
2017-11-10 09:31:40 +03:00
|
|
|
u.updateIndex[u.logIndex] = u.PushBack(pd)
|
2017-02-21 04:45:53 +03:00
|
|
|
u.logIndex++
|
|
|
|
}
|
|
|
|
|
2020-01-03 17:53:51 +03:00
|
|
|
// restoreUpdate appends a new update to the tip of the updateLog. The entry is
|
|
|
|
// also added to index accordingly. This function differs from appendUpdate in
|
|
|
|
// that it won't increment the log index counter.
|
|
|
|
func (u *updateLog) restoreUpdate(pd *PaymentDescriptor) {
|
2020-02-10 15:52:19 +03:00
|
|
|
u.updateIndex[pd.LogIndex] = u.PushBack(pd)
|
2020-01-03 17:53:51 +03:00
|
|
|
}
|
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
// appendHtlc appends a new HTLC offer to the tip of the update log. The entry
|
|
|
|
// is also added to the offer index accordingly.
|
|
|
|
func (u *updateLog) appendHtlc(pd *PaymentDescriptor) {
|
|
|
|
u.htlcIndex[u.htlcCounter] = u.PushBack(pd)
|
|
|
|
u.htlcCounter++
|
|
|
|
|
|
|
|
u.logIndex++
|
|
|
|
}
|
|
|
|
|
2018-02-07 06:13:07 +03:00
|
|
|
// lookupHtlc attempts to look up an offered HTLC according to its offer
|
2017-10-23 02:28:30 +03:00
|
|
|
// index. If the entry isn't found, then a nil pointer is returned.
|
|
|
|
func (u *updateLog) lookupHtlc(i uint64) *PaymentDescriptor {
|
|
|
|
htlc, ok := u.htlcIndex[i]
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return htlc.Value.(*PaymentDescriptor)
|
2017-02-21 04:45:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// remove attempts to remove an entry from the update log. If the entry is
|
|
|
|
// found, then the entry will be removed from the update log and index.
|
2017-10-23 02:28:30 +03:00
|
|
|
func (u *updateLog) removeUpdate(i uint64) {
|
2017-02-21 04:45:53 +03:00
|
|
|
entry := u.updateIndex[i]
|
|
|
|
u.Remove(entry)
|
|
|
|
delete(u.updateIndex, i)
|
|
|
|
}
|
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
// removeHtlc attempts to remove an HTLC offer form the update log. If the
|
|
|
|
// entry is found, then the entry will be removed from both the main log and
|
|
|
|
// the offer index.
|
|
|
|
func (u *updateLog) removeHtlc(i uint64) {
|
|
|
|
entry := u.htlcIndex[i]
|
|
|
|
u.Remove(entry)
|
|
|
|
delete(u.htlcIndex, i)
|
2018-05-26 04:37:45 +03:00
|
|
|
|
2018-05-26 04:38:44 +03:00
|
|
|
delete(u.modifiedHtlcs, i)
|
|
|
|
}
|
|
|
|
|
2018-05-26 04:37:45 +03:00
|
|
|
// htlcHasModification returns true if the HTLC identified by the passed index
|
|
|
|
// has a pending modification within the log.
|
|
|
|
func (u *updateLog) htlcHasModification(i uint64) bool {
|
|
|
|
_, o := u.modifiedHtlcs[i]
|
|
|
|
return o
|
|
|
|
}
|
|
|
|
|
|
|
|
// markHtlcModified marks an HTLC as modified based on its HTLC index. After a
|
|
|
|
// call to this method, htlcHasModification will return true until the HTLC is
|
|
|
|
// removed.
|
|
|
|
func (u *updateLog) markHtlcModified(i uint64) {
|
|
|
|
u.modifiedHtlcs[i] = struct{}{}
|
2017-10-23 02:28:30 +03:00
|
|
|
}
|
|
|
|
|
2017-02-21 04:45:53 +03:00
|
|
|
// compactLogs performs garbage collection within the log removing HTLCs which
|
|
|
|
// have been removed from the point-of-view of the tail of both chains. The
|
|
|
|
// entries which timeout/settle HTLCs are also removed.
|
|
|
|
func compactLogs(ourLog, theirLog *updateLog,
|
|
|
|
localChainTail, remoteChainTail uint64) {
|
|
|
|
|
|
|
|
compactLog := func(logA, logB *updateLog) {
|
|
|
|
var nextA *list.Element
|
|
|
|
for e := logA.Front(); e != nil; e = nextA {
|
2017-11-10 09:31:40 +03:00
|
|
|
// Assign next iteration element at top of loop because
|
|
|
|
// we may remove the current element from the list,
|
|
|
|
// which can change the iterated sequence.
|
2017-02-21 04:45:53 +03:00
|
|
|
nextA = e.Next()
|
|
|
|
|
|
|
|
htlc := e.Value.(*PaymentDescriptor)
|
2019-01-10 14:23:57 +03:00
|
|
|
|
|
|
|
// We skip Adds, as they will be removed along with the
|
|
|
|
// fail/settles below.
|
2017-02-21 04:45:53 +03:00
|
|
|
if htlc.EntryType == Add {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the HTLC hasn't yet been removed from either
|
|
|
|
// chain, the skip it.
|
|
|
|
if htlc.removeCommitHeightRemote == 0 ||
|
|
|
|
htlc.removeCommitHeightLocal == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise if the height of the tail of both chains
|
|
|
|
// is at least the height in which the HTLC was
|
|
|
|
// removed, then evict the settle/timeout entry along
|
|
|
|
// with the original add entry.
|
|
|
|
if remoteChainTail >= htlc.removeCommitHeightRemote &&
|
|
|
|
localChainTail >= htlc.removeCommitHeightLocal {
|
|
|
|
|
2019-01-10 14:23:57 +03:00
|
|
|
// Fee updates have no parent htlcs, so we only
|
|
|
|
// remove the update itself.
|
|
|
|
if htlc.EntryType == FeeUpdate {
|
|
|
|
logA.removeUpdate(htlc.LogIndex)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// The other types (fail/settle) do have a
|
|
|
|
// parent HTLC, so we'll remove that HTLC from
|
|
|
|
// the other log.
|
2017-10-23 02:28:30 +03:00
|
|
|
logA.removeUpdate(htlc.LogIndex)
|
|
|
|
logB.removeHtlc(htlc.ParentIndex)
|
2017-02-21 04:45:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
compactLog(ourLog, theirLog)
|
|
|
|
compactLog(theirLog, ourLog)
|
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// LightningChannel implements the state machine which corresponds to the
|
|
|
|
// current commitment protocol wire spec. The state machine implemented allows
|
|
|
|
// for asynchronous fully desynchronized, batched+pipelined updates to
|
|
|
|
// commitment transactions allowing for a high degree of non-blocking
|
|
|
|
// bi-directional payment throughput.
|
|
|
|
//
|
|
|
|
// In order to allow updates to be fully non-blocking, either side is able to
|
|
|
|
// create multiple new commitment states up to a pre-determined window size.
|
|
|
|
// This window size is encoded within InitialRevocationWindow. Before the start
|
|
|
|
// of a session, both side should send out revocation messages with nil
|
|
|
|
// preimages in order to populate their revocation window for the remote party.
|
|
|
|
//
|
|
|
|
// The state machine has for main methods:
|
|
|
|
// * .SignNextCommitment()
|
|
|
|
// * Called one one wishes to sign the next commitment, either initiating a
|
|
|
|
// new state update, or responding to a received commitment.
|
2016-11-16 23:49:37 +03:00
|
|
|
// * .ReceiveNewCommitment()
|
2016-07-06 03:01:55 +03:00
|
|
|
// * Called upon receipt of a new commitment from the remote party. If the
|
|
|
|
// new commitment is valid, then a revocation should immediately be
|
|
|
|
// generated and sent.
|
|
|
|
// * .RevokeCurrentCommitment()
|
|
|
|
// * Revokes the current commitment. Should be called directly after
|
|
|
|
// receiving a new commitment.
|
|
|
|
// * .ReceiveRevocation()
|
|
|
|
// * Processes a revocation from the remote party. If successful creates a
|
|
|
|
// new defacto broadcastable state.
|
|
|
|
//
|
|
|
|
// See the individual comments within the above methods for further details.
|
2015-12-19 00:37:13 +03:00
|
|
|
type LightningChannel struct {
|
2018-04-30 01:40:59 +03:00
|
|
|
// Signer is the main signer instances that will be responsible for
|
2017-07-30 22:25:41 +03:00
|
|
|
// signing any HTLC and commitment transaction generated by the state
|
|
|
|
// machine.
|
2019-01-16 17:47:43 +03:00
|
|
|
Signer input.Signer
|
2017-07-30 22:25:41 +03:00
|
|
|
|
|
|
|
// signDesc is the primary sign descriptor that is capable of signing
|
|
|
|
// the commitment transaction that spends the multi-sig output.
|
2019-01-16 17:47:43 +03:00
|
|
|
signDesc *input.SignDescriptor
|
2016-08-13 01:50:47 +03:00
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
status channelState
|
|
|
|
|
2017-11-21 10:57:33 +03:00
|
|
|
// ChanPoint is the funding outpoint of this channel.
|
|
|
|
ChanPoint *wire.OutPoint
|
|
|
|
|
2017-07-30 22:50:57 +03:00
|
|
|
// sigPool is a pool of workers that are capable of signing and
|
|
|
|
// validating signatures in parallel. This is utilized as an
|
|
|
|
// optimization to void serially signing or validating the HTLC
|
|
|
|
// signatures, of which there may be hundreds.
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigPool *SigPool
|
2017-07-30 22:50:57 +03:00
|
|
|
|
2017-12-18 05:40:05 +03:00
|
|
|
// Capacity is the total capacity of this channel.
|
2016-08-13 01:50:47 +03:00
|
|
|
Capacity btcutil.Amount
|
2016-06-21 07:56:54 +03:00
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// currentHeight is the current height of our local commitment chain.
|
|
|
|
// This is also the same as the number of updates to the channel we've
|
|
|
|
// accepted.
|
|
|
|
currentHeight uint64
|
|
|
|
|
|
|
|
// remoteCommitChain is the remote node's commitment chain. Any new
|
|
|
|
// commitments we initiate are added to the tip of this chain.
|
|
|
|
remoteCommitChain *commitmentChain
|
|
|
|
|
|
|
|
// localCommitChain is our local commitment chain. Any new commitments
|
|
|
|
// received are added to the tip of this chain. The tail (or lowest
|
|
|
|
// height) in this chain is our current accepted state, which we are
|
|
|
|
// able to broadcast safely.
|
|
|
|
localCommitChain *commitmentChain
|
2015-12-17 07:58:01 +03:00
|
|
|
|
2016-01-07 03:17:18 +03:00
|
|
|
channelState *channeldb.OpenChannel
|
2015-12-17 07:58:01 +03:00
|
|
|
|
2020-01-06 13:42:03 +03:00
|
|
|
commitBuilder *CommitmentBuilder
|
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
// [local|remote]Log is a (mostly) append-only log storing all the HTLC
|
2016-07-06 03:01:55 +03:00
|
|
|
// updates to this channel. The log is walked backwards as HTLC updates
|
|
|
|
// are applied in order to re-construct a commitment transaction from a
|
|
|
|
// commitment. The log is compacted once a revocation is received.
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
localUpdateLog *updateLog
|
|
|
|
remoteUpdateLog *updateLog
|
2015-12-31 09:36:01 +03:00
|
|
|
|
2016-12-23 00:27:28 +03:00
|
|
|
// LocalFundingKey is the public key under control by the wallet that
|
|
|
|
// was used for the 2-of-2 funding output which created this channel.
|
|
|
|
LocalFundingKey *btcec.PublicKey
|
|
|
|
|
|
|
|
// RemoteFundingKey is the public key for the remote channel counter
|
|
|
|
// party which used for the 2-of-2 funding output which created this
|
|
|
|
// channel.
|
|
|
|
RemoteFundingKey *btcec.PublicKey
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
// log is a channel-specific logging instance.
|
|
|
|
log btclog.Logger
|
|
|
|
|
2017-07-30 22:25:41 +03:00
|
|
|
sync.RWMutex
|
2015-12-16 23:40:11 +03:00
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// NewLightningChannel creates a new, active payment channel given an
|
2016-09-12 22:33:22 +03:00
|
|
|
// implementation of the chain notifier, channel database, and the current
|
|
|
|
// settled channel state. Throughout state transitions, then channel will
|
|
|
|
// automatically persist pertinent state to the database in an efficient
|
|
|
|
// manner.
|
2019-04-15 15:24:43 +03:00
|
|
|
func NewLightningChannel(signer input.Signer,
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
state *channeldb.OpenChannel,
|
|
|
|
sigPool *SigPool) (*LightningChannel, error) {
|
2015-12-17 07:58:01 +03:00
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
localCommit := state.LocalCommitment
|
|
|
|
remoteCommit := state.RemoteCommitment
|
|
|
|
|
|
|
|
// First, initialize the update logs with their current counter values
|
|
|
|
// from the local and remote commitments.
|
|
|
|
localUpdateLog := newUpdateLog(
|
2018-05-16 14:40:43 +03:00
|
|
|
remoteCommit.LocalLogIndex, remoteCommit.LocalHtlcIndex,
|
2017-11-10 09:51:03 +03:00
|
|
|
)
|
|
|
|
remoteUpdateLog := newUpdateLog(
|
2018-05-16 14:40:43 +03:00
|
|
|
localCommit.RemoteLogIndex, localCommit.RemoteHtlcIndex,
|
2017-11-10 09:51:03 +03:00
|
|
|
)
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
logPrefix := fmt.Sprintf("ChannelPoint(%v):", state.FundingOutpoint)
|
|
|
|
|
2015-12-31 09:36:01 +03:00
|
|
|
lc := &LightningChannel{
|
2018-04-30 01:40:59 +03:00
|
|
|
Signer: signer,
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigPool: sigPool,
|
2017-09-26 07:47:39 +03:00
|
|
|
currentHeight: localCommit.CommitHeight,
|
2018-11-20 17:09:45 +03:00
|
|
|
remoteCommitChain: newCommitmentChain(),
|
|
|
|
localCommitChain: newCommitmentChain(),
|
2017-09-26 07:47:39 +03:00
|
|
|
channelState: state,
|
2020-01-06 13:42:03 +03:00
|
|
|
commitBuilder: NewCommitmentBuilder(state),
|
2017-09-26 07:47:39 +03:00
|
|
|
localUpdateLog: localUpdateLog,
|
|
|
|
remoteUpdateLog: remoteUpdateLog,
|
|
|
|
ChanPoint: &state.FundingOutpoint,
|
|
|
|
Capacity: state.Capacity,
|
2018-02-18 02:17:40 +03:00
|
|
|
LocalFundingKey: state.LocalChanCfg.MultiSigKey.PubKey,
|
|
|
|
RemoteFundingKey: state.RemoteChanCfg.MultiSigKey.PubKey,
|
2019-09-24 14:12:53 +03:00
|
|
|
log: build.NewPrefixLog(logPrefix, walletLog),
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
// With the main channel struct reconstructed, we'll now restore the
|
|
|
|
// commitment state in memory and also the update logs themselves.
|
2018-05-04 14:42:15 +03:00
|
|
|
err := lc.restoreCommitState(&localCommit, &remoteCommit)
|
2017-11-10 09:51:03 +03:00
|
|
|
if err != nil {
|
2017-03-25 02:25:59 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
2017-08-15 20:09:16 +03:00
|
|
|
|
2016-09-12 22:33:22 +03:00
|
|
|
// Create the sign descriptor which we'll be using very frequently to
|
|
|
|
// request a signature for the 2-of-2 multi-sig from the signer in
|
|
|
|
// order to complete channel state transitions.
|
2019-03-11 02:38:45 +03:00
|
|
|
if err := lc.createSignDesc(); err != nil {
|
2015-12-31 09:36:01 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
2017-09-26 07:47:39 +03:00
|
|
|
|
|
|
|
return lc, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// createSignDesc derives the SignDescriptor for commitment transactions from
|
|
|
|
// other fields on the LightningChannel.
|
|
|
|
func (lc *LightningChannel) createSignDesc() error {
|
2020-01-06 13:42:02 +03:00
|
|
|
localKey := lc.channelState.LocalChanCfg.MultiSigKey.PubKey.
|
|
|
|
SerializeCompressed()
|
|
|
|
remoteKey := lc.channelState.RemoteChanCfg.MultiSigKey.PubKey.
|
|
|
|
SerializeCompressed()
|
2017-09-26 07:47:39 +03:00
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
multiSigScript, err := input.GenMultiSigScript(localKey, remoteKey)
|
2017-09-26 07:47:39 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
fundingPkScript, err := input.WitnessScriptHash(multiSigScript)
|
2017-09-26 07:47:39 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
lc.signDesc = &input.SignDescriptor{
|
2020-01-06 13:42:02 +03:00
|
|
|
KeyDesc: lc.channelState.LocalChanCfg.MultiSigKey,
|
2017-07-30 22:25:41 +03:00
|
|
|
WitnessScript: multiSigScript,
|
2016-08-13 01:50:47 +03:00
|
|
|
Output: &wire.TxOut{
|
2017-09-26 07:47:39 +03:00
|
|
|
PkScript: fundingPkScript,
|
2016-08-13 01:50:47 +03:00
|
|
|
Value: int64(lc.channelState.Capacity),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
InputIndex: 0,
|
|
|
|
}
|
|
|
|
|
2017-09-26 07:47:39 +03:00
|
|
|
return nil
|
|
|
|
}
|
2017-07-30 22:50:57 +03:00
|
|
|
|
2017-11-23 22:49:48 +03:00
|
|
|
// ResetState resets the state of the channel back to the default state. This
|
|
|
|
// ensures that any active goroutines which need to act based on on-chain
|
|
|
|
// events do so properly.
|
|
|
|
func (lc *LightningChannel) ResetState() {
|
|
|
|
lc.Lock()
|
|
|
|
lc.status = channelOpen
|
|
|
|
lc.Unlock()
|
2017-07-30 22:50:57 +03:00
|
|
|
}
|
2017-07-30 23:11:33 +03:00
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
// logUpdateToPayDesc converts a LogUpdate into a matching PaymentDescriptor
|
|
|
|
// entry that can be re-inserted into the update log. This method is used when
|
|
|
|
// we extended a state to the remote party, but the connection was obstructed
|
|
|
|
// before we could finish the commitment dance. In this case, we need to
|
|
|
|
// re-insert the original entries back into the update log so we can resume as
|
|
|
|
// if nothing happened.
|
|
|
|
func (lc *LightningChannel) logUpdateToPayDesc(logUpdate *channeldb.LogUpdate,
|
|
|
|
remoteUpdateLog *updateLog, commitHeight uint64,
|
2019-10-31 05:43:05 +03:00
|
|
|
feeRate chainfee.SatPerKWeight, remoteCommitKeys *CommitmentKeyRing,
|
2017-11-10 09:51:03 +03:00
|
|
|
remoteDustLimit btcutil.Amount) (*PaymentDescriptor, error) {
|
|
|
|
|
|
|
|
// Depending on the type of update message we'll map that to a distinct
|
|
|
|
// PaymentDescriptor instance.
|
|
|
|
var pd *PaymentDescriptor
|
|
|
|
|
|
|
|
switch wireMsg := logUpdate.UpdateMsg.(type) {
|
|
|
|
|
|
|
|
// For offered HTLC's, we'll map that to a PaymentDescriptor with the
|
|
|
|
// type Add, ensuring we restore the necessary fields. From the PoV of
|
2017-12-18 05:40:05 +03:00
|
|
|
// the commitment chain, this HTLC was included in the remote chain,
|
2017-11-10 09:51:03 +03:00
|
|
|
// but not the local chain.
|
|
|
|
case *lnwire.UpdateAddHTLC:
|
|
|
|
// First, we'll map all the relevant fields in the
|
|
|
|
// UpdateAddHTLC message to their corresponding fields in the
|
|
|
|
// PaymentDescriptor struct. We also set addCommitHeightRemote
|
|
|
|
// as we've included this HTLC in our local commitment chain
|
|
|
|
// for the remote party.
|
|
|
|
pd = &PaymentDescriptor{
|
|
|
|
RHash: wireMsg.PaymentHash,
|
|
|
|
Timeout: wireMsg.Expiry,
|
|
|
|
Amount: wireMsg.Amount,
|
|
|
|
EntryType: Add,
|
|
|
|
HtlcIndex: wireMsg.ID,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
addCommitHeightRemote: commitHeight,
|
|
|
|
}
|
2017-12-11 03:14:33 +03:00
|
|
|
pd.OnionBlob = make([]byte, len(wireMsg.OnionBlob))
|
2017-11-10 09:51:03 +03:00
|
|
|
copy(pd.OnionBlob[:], wireMsg.OnionBlob[:])
|
|
|
|
|
2020-03-06 18:11:49 +03:00
|
|
|
isDustRemote := htlcIsDust(
|
|
|
|
lc.channelState.ChanType, false, false, feeRate,
|
|
|
|
wireMsg.Amount.ToSatoshis(), remoteDustLimit,
|
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
if !isDustRemote {
|
|
|
|
theirP2WSH, theirWitnessScript, err := genHtlcScript(
|
2020-03-06 18:11:45 +03:00
|
|
|
lc.channelState.ChanType, false, false,
|
|
|
|
wireMsg.Expiry, wireMsg.PaymentHash,
|
2018-05-26 04:37:45 +03:00
|
|
|
remoteCommitKeys,
|
|
|
|
)
|
2017-11-10 09:51:03 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-05-26 04:37:45 +03:00
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
pd.theirPkScript = theirP2WSH
|
|
|
|
pd.theirWitnessScript = theirWitnessScript
|
|
|
|
}
|
|
|
|
|
2018-04-18 05:03:27 +03:00
|
|
|
// For HTLC's we're offered we'll fetch the original offered HTLC
|
2017-11-10 09:51:03 +03:00
|
|
|
// from the remote party's update log so we can retrieve the same
|
|
|
|
// PaymentDescriptor that SettleHTLC would produce.
|
2018-02-07 06:11:11 +03:00
|
|
|
case *lnwire.UpdateFulfillHTLC:
|
2017-11-10 09:51:03 +03:00
|
|
|
ogHTLC := remoteUpdateLog.lookupHtlc(wireMsg.ID)
|
|
|
|
|
|
|
|
pd = &PaymentDescriptor{
|
|
|
|
Amount: ogHTLC.Amount,
|
2020-01-06 16:02:17 +03:00
|
|
|
RHash: ogHTLC.RHash,
|
2017-11-10 09:51:03 +03:00
|
|
|
RPreimage: wireMsg.PaymentPreimage,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
ParentIndex: ogHTLC.HtlcIndex,
|
|
|
|
EntryType: Settle,
|
|
|
|
removeCommitHeightRemote: commitHeight,
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we sent a failure for a prior incoming HTLC, then we'll consult
|
|
|
|
// the update log of the remote party so we can retrieve the
|
|
|
|
// information of the original HTLC we're failing. We also set the
|
|
|
|
// removal height for the remote commitment.
|
|
|
|
case *lnwire.UpdateFailHTLC:
|
|
|
|
ogHTLC := remoteUpdateLog.lookupHtlc(wireMsg.ID)
|
|
|
|
|
|
|
|
pd = &PaymentDescriptor{
|
|
|
|
Amount: ogHTLC.Amount,
|
|
|
|
RHash: ogHTLC.RHash,
|
|
|
|
ParentIndex: ogHTLC.HtlcIndex,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
EntryType: Fail,
|
|
|
|
FailReason: wireMsg.Reason[:],
|
|
|
|
removeCommitHeightRemote: commitHeight,
|
|
|
|
}
|
|
|
|
|
|
|
|
// HTLC fails due to malformed onion blobs are treated the exact same
|
|
|
|
// way as regular HTLC fails.
|
|
|
|
case *lnwire.UpdateFailMalformedHTLC:
|
|
|
|
ogHTLC := remoteUpdateLog.lookupHtlc(wireMsg.ID)
|
|
|
|
// TODO(roasbeef): err if nil?
|
|
|
|
|
|
|
|
pd = &PaymentDescriptor{
|
|
|
|
Amount: ogHTLC.Amount,
|
|
|
|
RHash: ogHTLC.RHash,
|
|
|
|
ParentIndex: ogHTLC.HtlcIndex,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
EntryType: MalformedFail,
|
|
|
|
FailCode: wireMsg.FailureCode,
|
|
|
|
ShaOnionBlob: wireMsg.ShaOnionBlob,
|
|
|
|
removeCommitHeightRemote: commitHeight,
|
|
|
|
}
|
2019-01-10 14:23:56 +03:00
|
|
|
|
|
|
|
// For fee updates we'll create a FeeUpdate type to add to the log. We
|
|
|
|
// reuse the amount field to hold the fee rate. Since the amount field
|
|
|
|
// is denominated in msat we won't lose precision when storing the
|
|
|
|
// sat/kw denominated feerate. Note that we set both the add and remove
|
|
|
|
// height to the same value, as we consider the fee update locked in by
|
|
|
|
// adding and removing it at the same height.
|
|
|
|
case *lnwire.UpdateFee:
|
|
|
|
pd = &PaymentDescriptor{
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
Amount: lnwire.NewMSatFromSatoshis(
|
|
|
|
btcutil.Amount(wireMsg.FeePerKw),
|
|
|
|
),
|
|
|
|
EntryType: FeeUpdate,
|
|
|
|
addCommitHeightRemote: commitHeight,
|
|
|
|
removeCommitHeightRemote: commitHeight,
|
|
|
|
}
|
2017-11-10 09:51:03 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return pd, nil
|
|
|
|
}
|
|
|
|
|
2020-01-03 17:53:51 +03:00
|
|
|
// remoteLogUpdateToPayDesc converts a LogUpdate into a matching
|
|
|
|
// PaymentDescriptor entry that can be re-inserted into the update log. This
|
|
|
|
// method is used when we revoked a local commitment, but the connection was
|
|
|
|
// obstructed before we could sign a remote commitment that contains these
|
|
|
|
// updates. In this case, we need to re-insert the original entries back into
|
|
|
|
// the update log so we can resume as if nothing happened. The height of the
|
|
|
|
// latest local commitment is also expected to be provided. We are restoring all
|
|
|
|
// log update entries with this height, even though the real commitment height
|
|
|
|
// may be lower. In the way these fields are used elsewhere, this doesn't change
|
|
|
|
// anything.
|
|
|
|
func (lc *LightningChannel) remoteLogUpdateToPayDesc(logUpdate *channeldb.LogUpdate,
|
|
|
|
localUpdateLog *updateLog, commitHeight uint64) (*PaymentDescriptor,
|
|
|
|
error) {
|
|
|
|
|
|
|
|
switch wireMsg := logUpdate.UpdateMsg.(type) {
|
|
|
|
|
|
|
|
case *lnwire.UpdateAddHTLC:
|
|
|
|
pd := &PaymentDescriptor{
|
|
|
|
RHash: wireMsg.PaymentHash,
|
|
|
|
Timeout: wireMsg.Expiry,
|
|
|
|
Amount: wireMsg.Amount,
|
|
|
|
EntryType: Add,
|
|
|
|
HtlcIndex: wireMsg.ID,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
addCommitHeightLocal: commitHeight,
|
|
|
|
}
|
|
|
|
pd.OnionBlob = make([]byte, len(wireMsg.OnionBlob))
|
|
|
|
copy(pd.OnionBlob, wireMsg.OnionBlob[:])
|
|
|
|
|
|
|
|
// We don't need to generate an htlc script yet. This will be
|
|
|
|
// done once we sign our remote commitment.
|
|
|
|
|
|
|
|
return pd, nil
|
|
|
|
|
|
|
|
// For HTLCs that the remote party settled, we'll fetch the original
|
|
|
|
// offered HTLC from the local update log so we can retrieve the same
|
|
|
|
// PaymentDescriptor that ReceiveHTLCSettle would produce.
|
|
|
|
case *lnwire.UpdateFulfillHTLC:
|
|
|
|
ogHTLC := localUpdateLog.lookupHtlc(wireMsg.ID)
|
|
|
|
|
|
|
|
return &PaymentDescriptor{
|
|
|
|
Amount: ogHTLC.Amount,
|
|
|
|
RHash: ogHTLC.RHash,
|
|
|
|
RPreimage: wireMsg.PaymentPreimage,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
ParentIndex: ogHTLC.HtlcIndex,
|
|
|
|
EntryType: Settle,
|
|
|
|
removeCommitHeightLocal: commitHeight,
|
|
|
|
}, nil
|
|
|
|
|
|
|
|
// If we received a failure for a prior outgoing HTLC, then we'll
|
|
|
|
// consult the local update log so we can retrieve the information of
|
|
|
|
// the original HTLC we're failing.
|
|
|
|
case *lnwire.UpdateFailHTLC:
|
|
|
|
ogHTLC := localUpdateLog.lookupHtlc(wireMsg.ID)
|
|
|
|
|
|
|
|
return &PaymentDescriptor{
|
|
|
|
Amount: ogHTLC.Amount,
|
|
|
|
RHash: ogHTLC.RHash,
|
|
|
|
ParentIndex: ogHTLC.HtlcIndex,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
EntryType: Fail,
|
|
|
|
FailReason: wireMsg.Reason[:],
|
|
|
|
removeCommitHeightLocal: commitHeight,
|
|
|
|
}, nil
|
|
|
|
|
|
|
|
// HTLC fails due to malformed onion blobs are treated the exact same
|
|
|
|
// way as regular HTLC fails.
|
|
|
|
case *lnwire.UpdateFailMalformedHTLC:
|
|
|
|
ogHTLC := localUpdateLog.lookupHtlc(wireMsg.ID)
|
|
|
|
|
|
|
|
return &PaymentDescriptor{
|
|
|
|
Amount: ogHTLC.Amount,
|
|
|
|
RHash: ogHTLC.RHash,
|
|
|
|
ParentIndex: ogHTLC.HtlcIndex,
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
EntryType: MalformedFail,
|
|
|
|
FailCode: wireMsg.FailureCode,
|
|
|
|
ShaOnionBlob: wireMsg.ShaOnionBlob,
|
|
|
|
removeCommitHeightLocal: commitHeight,
|
|
|
|
}, nil
|
|
|
|
|
|
|
|
// For fee updates we'll create a FeeUpdate type to add to the log. We
|
|
|
|
// reuse the amount field to hold the fee rate. Since the amount field
|
|
|
|
// is denominated in msat we won't lose precision when storing the
|
|
|
|
// sat/kw denominated feerate. Note that we set both the add and remove
|
|
|
|
// height to the same value, as we consider the fee update locked in by
|
|
|
|
// adding and removing it at the same height.
|
|
|
|
case *lnwire.UpdateFee:
|
|
|
|
return &PaymentDescriptor{
|
|
|
|
LogIndex: logUpdate.LogIndex,
|
|
|
|
Amount: lnwire.NewMSatFromSatoshis(
|
|
|
|
btcutil.Amount(wireMsg.FeePerKw),
|
|
|
|
),
|
|
|
|
EntryType: FeeUpdate,
|
|
|
|
addCommitHeightLocal: commitHeight,
|
|
|
|
removeCommitHeightLocal: commitHeight,
|
|
|
|
}, nil
|
|
|
|
|
|
|
|
default:
|
|
|
|
return nil, errors.New("unknown message type")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
// restoreCommitState will restore the local commitment chain and updateLog
|
2018-05-26 04:37:45 +03:00
|
|
|
// state to a consistent in-memory representation of the passed disk commitment.
|
2017-11-10 09:51:03 +03:00
|
|
|
// This method is to be used upon reconnection to our channel counter party.
|
|
|
|
// Once the connection has been established, we'll prepare our in memory state
|
|
|
|
// to re-sync states with the remote party, and also verify/extend new proposed
|
|
|
|
// commitment states.
|
|
|
|
func (lc *LightningChannel) restoreCommitState(
|
2018-05-04 14:42:15 +03:00
|
|
|
localCommitState, remoteCommitState *channeldb.ChannelCommitment) error {
|
2017-11-10 09:51:03 +03:00
|
|
|
|
|
|
|
// In order to reconstruct the pkScripts on each of the pending HTLC
|
|
|
|
// outputs (if any) we'll need to regenerate the current revocation for
|
|
|
|
// this current un-revoked state as well as retrieve the current
|
|
|
|
// revocation for the remote party.
|
|
|
|
ourRevPreImage, err := lc.channelState.RevocationProducer.AtIndex(
|
|
|
|
lc.currentHeight,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
localCommitPoint := input.ComputeCommitmentPoint(ourRevPreImage[:])
|
2017-11-10 09:51:03 +03:00
|
|
|
remoteCommitPoint := lc.channelState.RemoteCurrentRevocation
|
|
|
|
|
|
|
|
// With the revocation state reconstructed, we can now convert the disk
|
|
|
|
// commitment into our in-memory commitment format, inserting it into
|
|
|
|
// the local commitment chain.
|
|
|
|
localCommit, err := lc.diskCommitToMemCommit(
|
2018-05-28 23:09:24 +03:00
|
|
|
true, localCommitState, localCommitPoint,
|
2017-11-10 09:51:03 +03:00
|
|
|
remoteCommitPoint,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
lc.localCommitChain.addCommitment(localCommit)
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Debugf("starting local commitment: %v",
|
|
|
|
newLogClosure(func() string {
|
2017-11-10 09:51:03 +03:00
|
|
|
return spew.Sdump(lc.localCommitChain.tail())
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
|
|
|
|
// We'll also do the same for the remote commitment chain.
|
|
|
|
remoteCommit, err := lc.diskCommitToMemCommit(
|
2018-05-28 23:09:24 +03:00
|
|
|
false, remoteCommitState, localCommitPoint,
|
2017-11-10 09:51:03 +03:00
|
|
|
remoteCommitPoint,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
lc.remoteCommitChain.addCommitment(remoteCommit)
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Debugf("starting remote commitment: %v",
|
|
|
|
newLogClosure(func() string {
|
2017-11-10 09:51:03 +03:00
|
|
|
return spew.Sdump(lc.remoteCommitChain.tail())
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
pendingRemoteCommit *commitment
|
|
|
|
pendingRemoteCommitDiff *channeldb.CommitDiff
|
2018-01-19 00:45:30 +03:00
|
|
|
pendingRemoteKeyChain *CommitmentKeyRing
|
2017-11-10 09:51:03 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// Next, we'll check to see if we have an un-acked commitment state we
|
|
|
|
// extended to the remote party but which was never ACK'd.
|
|
|
|
pendingRemoteCommitDiff, err = lc.channelState.RemoteCommitChainTip()
|
|
|
|
if err != nil && err != channeldb.ErrNoPendingCommit {
|
2018-05-04 14:18:31 +03:00
|
|
|
return err
|
2017-11-10 09:51:03 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if pendingRemoteCommitDiff != nil {
|
|
|
|
// If we have a pending remote commitment, then we'll also
|
|
|
|
// reconstruct the original commitment for that state,
|
|
|
|
// inserting it into the remote party's commitment chain. We
|
|
|
|
// don't pass our commit point as we don't have the
|
|
|
|
// corresponding state for the local commitment chain.
|
|
|
|
pendingCommitPoint := lc.channelState.RemoteNextRevocation
|
|
|
|
pendingRemoteCommit, err = lc.diskCommitToMemCommit(
|
2018-05-28 23:09:24 +03:00
|
|
|
false, &pendingRemoteCommitDiff.Commitment,
|
2017-11-10 09:51:03 +03:00
|
|
|
nil, pendingCommitPoint,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
lc.remoteCommitChain.addCommitment(pendingRemoteCommit)
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Debugf("pending remote commitment: %v",
|
2018-05-04 14:20:11 +03:00
|
|
|
newLogClosure(func() string {
|
|
|
|
return spew.Sdump(lc.remoteCommitChain.tip())
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
// We'll also re-create the set of commitment keys needed to
|
|
|
|
// fully re-derive the state.
|
2019-09-17 05:06:19 +03:00
|
|
|
pendingRemoteKeyChain = DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
pendingCommitPoint, false, lc.channelState.ChanType,
|
2020-01-06 13:42:02 +03:00
|
|
|
&lc.channelState.LocalChanCfg, &lc.channelState.RemoteChanCfg,
|
2017-11-10 09:51:03 +03:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-01-03 17:53:51 +03:00
|
|
|
// Fetch remote updates that we have acked but not yet signed for.
|
|
|
|
unsignedAckedUpdates, err := lc.channelState.UnsignedAckedUpdates()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
// Finally, with the commitment states restored, we'll now restore the
|
|
|
|
// state logs based on the current local+remote commit, and any pending
|
|
|
|
// remote commit that exists.
|
2019-03-11 02:38:45 +03:00
|
|
|
err = lc.restoreStateLogs(
|
|
|
|
localCommit, remoteCommit, pendingRemoteCommit,
|
2017-11-10 09:51:03 +03:00
|
|
|
pendingRemoteCommitDiff, pendingRemoteKeyChain,
|
2020-01-03 17:53:51 +03:00
|
|
|
unsignedAckedUpdates,
|
2017-11-10 09:51:03 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// restoreStateLogs runs through the current locked-in HTLCs from the point of
|
|
|
|
// view of the channel and insert corresponding log entries (both local and
|
|
|
|
// remote) for each HTLC read from disk. This method is required to sync the
|
|
|
|
// in-memory state of the state machine with that read from persistent storage.
|
|
|
|
func (lc *LightningChannel) restoreStateLogs(
|
|
|
|
localCommitment, remoteCommitment, pendingRemoteCommit *commitment,
|
|
|
|
pendingRemoteCommitDiff *channeldb.CommitDiff,
|
2020-01-03 17:53:51 +03:00
|
|
|
pendingRemoteKeys *CommitmentKeyRing,
|
|
|
|
unsignedAckedUpdates []channeldb.LogUpdate) error {
|
2017-11-10 09:51:03 +03:00
|
|
|
|
2018-05-28 23:09:24 +03:00
|
|
|
// We make a map of incoming HTLCs to the height of the remote
|
|
|
|
// commitment they were first added, and outgoing HTLCs to the height
|
|
|
|
// of the local commit they were first added. This will be used when we
|
|
|
|
// restore the update logs below.
|
|
|
|
incomingRemoteAddHeights := make(map[uint64]uint64)
|
|
|
|
outgoingLocalAddHeights := make(map[uint64]uint64)
|
|
|
|
|
|
|
|
// We start by setting the height of the incoming HTLCs on the pending
|
|
|
|
// remote commitment. We set these heights first since if there are
|
|
|
|
// duplicates, these will be overwritten by the lower height of the
|
|
|
|
// remoteCommitment below.
|
|
|
|
if pendingRemoteCommit != nil {
|
|
|
|
for _, r := range pendingRemoteCommit.incomingHTLCs {
|
|
|
|
incomingRemoteAddHeights[r.HtlcIndex] =
|
|
|
|
pendingRemoteCommit.height
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now set the remote commit height of all incoming HTLCs found on the
|
|
|
|
// remote commitment.
|
|
|
|
for _, r := range remoteCommitment.incomingHTLCs {
|
|
|
|
incomingRemoteAddHeights[r.HtlcIndex] = remoteCommitment.height
|
|
|
|
}
|
|
|
|
|
|
|
|
// And finally we can do the same for the outgoing HTLCs.
|
|
|
|
for _, l := range localCommitment.outgoingHTLCs {
|
|
|
|
outgoingLocalAddHeights[l.HtlcIndex] = localCommitment.height
|
|
|
|
}
|
|
|
|
|
2018-05-16 15:39:22 +03:00
|
|
|
// For each incoming HTLC within the local commitment, we add it to the
|
|
|
|
// remote update log. Since HTLCs are added first to the receiver's
|
|
|
|
// commitment, we don't have to restore outgoing HTLCs, as they will be
|
|
|
|
// restored from the remote commitment below.
|
2017-11-10 09:51:03 +03:00
|
|
|
for i := range localCommitment.incomingHTLCs {
|
|
|
|
htlc := localCommitment.incomingHTLCs[i]
|
2018-05-28 23:09:24 +03:00
|
|
|
|
|
|
|
// We'll need to set the add height of the HTLC. Since it is on
|
|
|
|
// this local commit, we can use its height as local add
|
|
|
|
// height. As remote add height we consult the incoming HTLC
|
|
|
|
// map we created earlier. Note that if this HTLC is not in
|
|
|
|
// incomingRemoteAddHeights, the remote add height will be set
|
|
|
|
// to zero, which indicates that it is not added yet.
|
|
|
|
htlc.addCommitHeightLocal = localCommitment.height
|
|
|
|
htlc.addCommitHeightRemote = incomingRemoteAddHeights[htlc.HtlcIndex]
|
|
|
|
|
|
|
|
// Restore the htlc back to the remote log.
|
2017-11-10 09:51:03 +03:00
|
|
|
lc.remoteUpdateLog.restoreHtlc(&htlc)
|
|
|
|
}
|
|
|
|
|
2018-05-16 15:39:22 +03:00
|
|
|
// Similarly, we'll do the same for the outgoing HTLCs within the
|
|
|
|
// remote commitment, adding them to the local update log.
|
2017-11-10 09:51:03 +03:00
|
|
|
for i := range remoteCommitment.outgoingHTLCs {
|
|
|
|
htlc := remoteCommitment.outgoingHTLCs[i]
|
2018-05-28 23:09:24 +03:00
|
|
|
|
|
|
|
// As for the incoming HTLCs, we'll use the current remote
|
|
|
|
// commit height as remote add height, and consult the map
|
|
|
|
// created above for the local add height.
|
|
|
|
htlc.addCommitHeightRemote = remoteCommitment.height
|
|
|
|
htlc.addCommitHeightLocal = outgoingLocalAddHeights[htlc.HtlcIndex]
|
|
|
|
|
|
|
|
// Restore the htlc back to the local log.
|
2017-11-10 09:51:03 +03:00
|
|
|
lc.localUpdateLog.restoreHtlc(&htlc)
|
|
|
|
}
|
|
|
|
|
2020-01-06 15:14:25 +03:00
|
|
|
// If we have a dangling (un-acked) commit for the remote party, then we
|
|
|
|
// restore the updates leading up to this commit.
|
|
|
|
if pendingRemoteCommit != nil {
|
|
|
|
err := lc.restorePendingLocalUpdates(
|
|
|
|
pendingRemoteCommitDiff, pendingRemoteKeys,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-11-10 09:51:03 +03:00
|
|
|
}
|
|
|
|
|
2020-01-03 17:53:51 +03:00
|
|
|
// Restore unsigned acked remote log updates so that we can include them
|
|
|
|
// in our next signature.
|
|
|
|
err := lc.restorePendingRemoteUpdates(
|
|
|
|
unsignedAckedUpdates, localCommitment.height,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// restorePendingRemoteUpdates restores the acked remote log updates that we
|
|
|
|
// haven't yet signed for.
|
|
|
|
func (lc *LightningChannel) restorePendingRemoteUpdates(
|
|
|
|
unsignedAckedUpdates []channeldb.LogUpdate,
|
|
|
|
localCommitmentHeight uint64) error {
|
|
|
|
|
|
|
|
lc.log.Debugf("Restoring %v dangling remote updates",
|
|
|
|
len(unsignedAckedUpdates))
|
|
|
|
|
|
|
|
for _, logUpdate := range unsignedAckedUpdates {
|
|
|
|
logUpdate := logUpdate
|
|
|
|
|
|
|
|
payDesc, err := lc.remoteLogUpdateToPayDesc(
|
|
|
|
&logUpdate, lc.localUpdateLog, localCommitmentHeight,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sanity check that we are not restoring a remote log update
|
|
|
|
// that we haven't received a sig for.
|
|
|
|
if payDesc.LogIndex >= lc.remoteUpdateLog.logIndex {
|
|
|
|
return fmt.Errorf("attempted to restore an "+
|
|
|
|
"unsigned remote update: log_index=%v",
|
|
|
|
payDesc.LogIndex)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert the update into the log. The log update index doesn't
|
|
|
|
// need to be incremented (hence the restore calls), because its
|
|
|
|
// final value was properly persisted with the last local
|
|
|
|
// commitment update.
|
|
|
|
switch payDesc.EntryType {
|
|
|
|
case Add:
|
|
|
|
lc.remoteUpdateLog.restoreHtlc(payDesc)
|
|
|
|
|
|
|
|
// Sanity check to be sure that we are not restoring an
|
|
|
|
// add update that the remote hasn't signed for yet.
|
|
|
|
if payDesc.HtlcIndex >= lc.remoteUpdateLog.htlcCounter {
|
|
|
|
return fmt.Errorf("attempted to restore an "+
|
|
|
|
"unsigned remote htlc: htlc_index=%v",
|
|
|
|
payDesc.HtlcIndex)
|
|
|
|
}
|
|
|
|
|
|
|
|
case FeeUpdate:
|
|
|
|
lc.remoteUpdateLog.restoreUpdate(payDesc)
|
|
|
|
|
|
|
|
default:
|
|
|
|
lc.remoteUpdateLog.restoreUpdate(payDesc)
|
|
|
|
|
|
|
|
lc.localUpdateLog.markHtlcModified(payDesc.ParentIndex)
|
|
|
|
}
|
2017-11-10 09:51:03 +03:00
|
|
|
}
|
|
|
|
|
2020-01-06 15:14:25 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// restorePendingLocalUpdates restores the local log updates leading up to the
|
|
|
|
// given pending remote commitment.
|
|
|
|
func (lc *LightningChannel) restorePendingLocalUpdates(
|
|
|
|
pendingRemoteCommitDiff *channeldb.CommitDiff,
|
|
|
|
pendingRemoteKeys *CommitmentKeyRing) error {
|
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
pendingCommit := pendingRemoteCommitDiff.Commitment
|
|
|
|
pendingHeight := pendingCommit.CommitHeight
|
|
|
|
|
|
|
|
// If we did have a dangling commit, then we'll examine which updates
|
|
|
|
// we included in that state and re-insert them into our update log.
|
|
|
|
for _, logUpdate := range pendingRemoteCommitDiff.LogUpdates {
|
|
|
|
payDesc, err := lc.logUpdateToPayDesc(
|
|
|
|
&logUpdate, lc.remoteUpdateLog, pendingHeight,
|
2019-10-31 05:43:05 +03:00
|
|
|
chainfee.SatPerKWeight(pendingCommit.FeePerKw),
|
|
|
|
pendingRemoteKeys,
|
2017-11-10 09:51:03 +03:00
|
|
|
lc.channelState.RemoteChanCfg.DustLimit,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-01-29 16:13:31 +03:00
|
|
|
// Earlier versions did not write the log index to disk for fee
|
|
|
|
// updates, so they will be unset. To account for this we set
|
|
|
|
// them to to current update log index.
|
|
|
|
if payDesc.EntryType == FeeUpdate && payDesc.LogIndex == 0 &&
|
|
|
|
lc.localUpdateLog.logIndex > 0 {
|
|
|
|
|
|
|
|
payDesc.LogIndex = lc.localUpdateLog.logIndex
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Debugf("Found FeeUpdate on "+
|
2019-01-29 16:13:31 +03:00
|
|
|
"pendingRemoteCommitDiff without logIndex, "+
|
|
|
|
"using %v", payDesc.LogIndex)
|
|
|
|
}
|
|
|
|
|
2019-01-29 16:28:19 +03:00
|
|
|
// At this point the restored update's logIndex must be equal
|
|
|
|
// to the update log, otherwise somthing is horribly wrong.
|
|
|
|
if payDesc.LogIndex != lc.localUpdateLog.logIndex {
|
|
|
|
panic(fmt.Sprintf("log index mismatch: "+
|
|
|
|
"%v vs %v", payDesc.LogIndex,
|
|
|
|
lc.localUpdateLog.logIndex))
|
|
|
|
}
|
|
|
|
|
2019-01-10 14:23:57 +03:00
|
|
|
switch payDesc.EntryType {
|
|
|
|
case Add:
|
2018-05-04 14:42:57 +03:00
|
|
|
// The HtlcIndex of the added HTLC _must_ be equal to
|
|
|
|
// the log's htlcCounter at this point. If it is not we
|
|
|
|
// panic to catch this.
|
|
|
|
// TODO(halseth): remove when cause of htlc entry bug
|
|
|
|
// is found.
|
|
|
|
if payDesc.HtlcIndex != lc.localUpdateLog.htlcCounter {
|
|
|
|
panic(fmt.Sprintf("htlc index mismatch: "+
|
|
|
|
"%v vs %v", payDesc.HtlcIndex,
|
|
|
|
lc.localUpdateLog.htlcCounter))
|
|
|
|
}
|
2018-05-26 04:39:16 +03:00
|
|
|
|
2017-11-10 09:51:03 +03:00
|
|
|
lc.localUpdateLog.appendHtlc(payDesc)
|
2019-01-10 14:23:57 +03:00
|
|
|
|
|
|
|
case FeeUpdate:
|
|
|
|
lc.localUpdateLog.appendUpdate(payDesc)
|
|
|
|
|
|
|
|
default:
|
2017-11-10 09:51:03 +03:00
|
|
|
lc.localUpdateLog.appendUpdate(payDesc)
|
2018-05-26 04:39:16 +03:00
|
|
|
|
|
|
|
lc.remoteUpdateLog.markHtlcModified(payDesc.ParentIndex)
|
2017-11-10 09:51:03 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-07-30 23:11:33 +03:00
|
|
|
// HtlcRetribution contains all the items necessary to seep a revoked HTLC
|
2017-11-27 23:24:00 +03:00
|
|
|
// transaction from a revoked commitment transaction broadcast by the remote
|
2017-07-30 23:11:33 +03:00
|
|
|
// party.
|
|
|
|
type HtlcRetribution struct {
|
|
|
|
// SignDesc is a design descriptor capable of generating the necessary
|
|
|
|
// signatures to satisfy the revocation clause of the HTLC's public key
|
|
|
|
// script.
|
2019-01-16 17:47:43 +03:00
|
|
|
SignDesc input.SignDescriptor
|
2017-07-30 23:11:33 +03:00
|
|
|
|
|
|
|
// OutPoint is the target outpoint of this HTLC pointing to the
|
|
|
|
// breached commitment transaction.
|
|
|
|
OutPoint wire.OutPoint
|
2017-09-06 23:38:01 +03:00
|
|
|
|
2018-01-21 07:12:49 +03:00
|
|
|
// SecondLevelWitnessScript is the witness script that will be created
|
|
|
|
// if the second level HTLC transaction for this output is
|
|
|
|
// broadcast/confirmed. We provide this as if the remote party attempts
|
2018-04-18 05:03:27 +03:00
|
|
|
// to go to the second level to claim the HTLC then we'll need to
|
2018-01-21 07:12:49 +03:00
|
|
|
// update the SignDesc above accordingly to sweep properly.
|
|
|
|
SecondLevelWitnessScript []byte
|
|
|
|
|
2017-09-06 23:38:01 +03:00
|
|
|
// IsIncoming is a boolean flag that indicates whether or not this
|
|
|
|
// HTLC was accepted from the counterparty. A false value indicates that
|
|
|
|
// this HTLC was offered by us. This flag is used determine the exact
|
|
|
|
// witness type should be used to sweep the output.
|
|
|
|
IsIncoming bool
|
2017-07-30 23:11:33 +03:00
|
|
|
}
|
|
|
|
|
2016-11-21 09:54:35 +03:00
|
|
|
// BreachRetribution contains all the data necessary to bring a channel
|
2017-01-13 08:01:50 +03:00
|
|
|
// counterparty to justice claiming ALL lingering funds within the channel in
|
2016-11-21 09:54:35 +03:00
|
|
|
// the scenario that they broadcast a revoked commitment transaction. A
|
|
|
|
// BreachRetribution is created by the closeObserver if it detects an
|
|
|
|
// uncooperative close of the channel which uses a revoked commitment
|
|
|
|
// transaction. The BreachRetribution is then sent over the ContractBreach
|
|
|
|
// channel in order to allow the subscriber of the channel to dispatch justice.
|
|
|
|
type BreachRetribution struct {
|
|
|
|
// BreachTransaction is the transaction which breached the channel
|
|
|
|
// contract by spending from the funding multi-sig with a revoked
|
|
|
|
// commitment transaction.
|
|
|
|
BreachTransaction *wire.MsgTx
|
|
|
|
|
2017-11-21 10:57:33 +03:00
|
|
|
// BreachHeight records the block height confirming the breach
|
|
|
|
// transaction, used as a height hint when registering for
|
|
|
|
// confirmations.
|
|
|
|
BreachHeight uint32
|
|
|
|
|
2017-11-10 10:06:10 +03:00
|
|
|
// ChainHash is the chain that the contract beach was identified
|
|
|
|
// within. This is also the resident chain of the contract (the chain
|
|
|
|
// the contract was created on).
|
|
|
|
ChainHash chainhash.Hash
|
|
|
|
|
2016-11-21 09:54:35 +03:00
|
|
|
// RevokedStateNum is the revoked state number which was broadcast.
|
|
|
|
RevokedStateNum uint64
|
|
|
|
|
2017-01-13 08:01:50 +03:00
|
|
|
// PendingHTLCs is a slice of the HTLCs which were pending at this
|
2016-11-21 09:54:35 +03:00
|
|
|
// point within the channel's history transcript.
|
2017-11-10 09:55:38 +03:00
|
|
|
PendingHTLCs []channeldb.HTLC
|
2016-11-21 09:54:35 +03:00
|
|
|
|
|
|
|
// LocalOutputSignDesc is a SignDescriptor which is capable of
|
|
|
|
// generating the signature necessary to sweep the output within the
|
|
|
|
// BreachTransaction that pays directly us.
|
2017-11-10 10:06:10 +03:00
|
|
|
//
|
2017-09-19 22:45:51 +03:00
|
|
|
// NOTE: A nil value indicates that the local output is considered dust
|
|
|
|
// according to the remote party's dust limit.
|
2019-01-16 17:47:43 +03:00
|
|
|
LocalOutputSignDesc *input.SignDescriptor
|
2016-11-21 09:54:35 +03:00
|
|
|
|
|
|
|
// LocalOutpoint is the outpoint of the output paying to us (the local
|
|
|
|
// party) within the breach transaction.
|
|
|
|
LocalOutpoint wire.OutPoint
|
|
|
|
|
2020-03-06 18:11:47 +03:00
|
|
|
// LocalDelay is the CSV delay for the to_remote script on the breached
|
|
|
|
// commitment.
|
|
|
|
LocalDelay uint32
|
|
|
|
|
2016-11-21 09:54:35 +03:00
|
|
|
// RemoteOutputSignDesc is a SignDescriptor which is capable of
|
|
|
|
// generating the signature required to claim the funds as described
|
|
|
|
// within the revocation clause of the remote party's commitment
|
|
|
|
// output.
|
2017-11-10 10:06:10 +03:00
|
|
|
//
|
2017-09-19 22:45:51 +03:00
|
|
|
// NOTE: A nil value indicates that the local output is considered dust
|
|
|
|
// according to the remote party's dust limit.
|
2019-01-16 17:47:43 +03:00
|
|
|
RemoteOutputSignDesc *input.SignDescriptor
|
2016-11-21 09:54:35 +03:00
|
|
|
|
2017-09-25 21:25:58 +03:00
|
|
|
// RemoteOutpoint is the outpoint of the output paying to the remote
|
2016-11-21 09:54:35 +03:00
|
|
|
// party within the breach transaction.
|
|
|
|
RemoteOutpoint wire.OutPoint
|
2017-07-30 23:11:33 +03:00
|
|
|
|
2020-03-06 18:11:47 +03:00
|
|
|
// RemoteDelay specifies the CSV delay applied to to-local scripts on
|
|
|
|
// the breaching commitment transaction.
|
|
|
|
RemoteDelay uint32
|
|
|
|
|
2017-07-30 23:11:33 +03:00
|
|
|
// HtlcRetributions is a slice of HTLC retributions for each output
|
|
|
|
// active HTLC output within the breached commitment transaction.
|
|
|
|
HtlcRetributions []HtlcRetribution
|
2018-12-20 08:50:44 +03:00
|
|
|
|
|
|
|
// KeyRing contains the derived public keys used to construct the
|
|
|
|
// breaching commitment transaction. This allows downstream clients to
|
|
|
|
// have access to the public keys used in the scripts.
|
|
|
|
KeyRing *CommitmentKeyRing
|
2016-11-21 09:54:35 +03:00
|
|
|
}
|
|
|
|
|
2018-01-19 00:48:30 +03:00
|
|
|
// NewBreachRetribution creates a new fully populated BreachRetribution for the
|
2016-11-21 09:54:35 +03:00
|
|
|
// passed channel, at a particular revoked state number, and one which targets
|
|
|
|
// the passed commitment transaction.
|
2018-01-19 00:48:30 +03:00
|
|
|
func NewBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64,
|
2017-11-21 10:57:33 +03:00
|
|
|
breachHeight uint32) (*BreachRetribution, error) {
|
2016-11-21 09:54:35 +03:00
|
|
|
|
|
|
|
// Query the on-disk revocation log for the snapshot which was recorded
|
|
|
|
// at this particular state num.
|
|
|
|
revokedSnapshot, err := chanState.FindPreviousState(stateNum)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-12-20 08:50:46 +03:00
|
|
|
commitHash := revokedSnapshot.CommitTx.TxHash()
|
|
|
|
|
2016-12-14 17:01:48 +03:00
|
|
|
// With the state number broadcast known, we can now derive/restore the
|
|
|
|
// proper revocation preimage necessary to sweep the remote party's
|
2016-11-21 09:54:35 +03:00
|
|
|
// output.
|
2016-12-14 17:01:48 +03:00
|
|
|
revocationPreimage, err := chanState.RevocationStore.LookUp(stateNum)
|
2016-11-21 09:54:35 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-04-05 03:41:05 +03:00
|
|
|
commitmentSecret, commitmentPoint := btcec.PrivKeyFromBytes(
|
|
|
|
btcec.S256(), revocationPreimage[:],
|
|
|
|
)
|
2017-07-30 23:11:33 +03:00
|
|
|
|
|
|
|
// With the commitment point generated, we can now generate the four
|
|
|
|
// keys we'll need to reconstruct the commitment state,
|
2019-09-17 05:06:19 +03:00
|
|
|
keyRing := DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
commitmentPoint, false, chanState.ChanType,
|
2019-08-01 06:10:45 +03:00
|
|
|
&chanState.LocalChanCfg, &chanState.RemoteChanCfg,
|
|
|
|
)
|
2016-11-21 09:54:35 +03:00
|
|
|
|
|
|
|
// Next, reconstruct the scripts as they were present at this state
|
|
|
|
// number so we can have the proper witness script to sign and include
|
|
|
|
// within the final witness.
|
2020-01-06 13:42:04 +03:00
|
|
|
theirDelay := uint32(chanState.RemoteChanCfg.CsvDelay)
|
|
|
|
theirPkScript, err := input.CommitScriptToSelf(
|
|
|
|
theirDelay, keyRing.ToLocalKey, keyRing.RevocationKey,
|
2018-04-05 03:41:05 +03:00
|
|
|
)
|
2016-11-21 09:54:35 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-01-06 13:42:04 +03:00
|
|
|
theirWitnessHash, err := input.WitnessScriptHash(theirPkScript)
|
2016-11-21 09:54:35 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-01-06 13:42:04 +03:00
|
|
|
|
|
|
|
// Since it is the remote breach we are reconstructing, the output going
|
|
|
|
// to us will be a to-remote script with our local params.
|
2020-03-06 18:11:47 +03:00
|
|
|
ourScript, ourDelay, err := CommitScriptToRemote(
|
2020-03-06 18:11:46 +03:00
|
|
|
chanState.ChanType, keyRing.ToRemoteKey,
|
2020-01-06 13:42:04 +03:00
|
|
|
)
|
2017-07-30 23:11:33 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-11-21 09:54:35 +03:00
|
|
|
|
|
|
|
// In order to fully populate the breach retribution struct, we'll need
|
2020-01-06 13:42:04 +03:00
|
|
|
// to find the exact index of the commitment outputs.
|
|
|
|
ourOutpoint := wire.OutPoint{
|
2016-11-21 09:54:35 +03:00
|
|
|
Hash: commitHash,
|
|
|
|
}
|
2020-01-06 13:42:04 +03:00
|
|
|
theirOutpoint := wire.OutPoint{
|
2016-11-21 09:54:35 +03:00
|
|
|
Hash: commitHash,
|
|
|
|
}
|
2018-12-20 08:50:46 +03:00
|
|
|
for i, txOut := range revokedSnapshot.CommitTx.TxOut {
|
2016-11-21 09:54:35 +03:00
|
|
|
switch {
|
2020-01-06 13:42:04 +03:00
|
|
|
case bytes.Equal(txOut.PkScript, ourScript.PkScript):
|
|
|
|
ourOutpoint.Index = uint32(i)
|
|
|
|
case bytes.Equal(txOut.PkScript, theirWitnessHash):
|
|
|
|
theirOutpoint.Index = uint32(i)
|
2016-09-12 22:33:22 +03:00
|
|
|
}
|
2016-11-21 09:54:35 +03:00
|
|
|
}
|
|
|
|
|
2017-09-19 22:45:51 +03:00
|
|
|
// Conditionally instantiate a sign descriptor for each of the
|
|
|
|
// commitment outputs. If either is considered dust using the remote
|
|
|
|
// party's dust limit, the respective sign descriptor will be nil.
|
|
|
|
var (
|
2020-01-06 13:42:04 +03:00
|
|
|
ourSignDesc *input.SignDescriptor
|
|
|
|
theirSignDesc *input.SignDescriptor
|
2017-09-19 22:45:51 +03:00
|
|
|
)
|
|
|
|
|
2020-01-06 13:42:04 +03:00
|
|
|
// Compute the balances in satoshis.
|
|
|
|
ourAmt := revokedSnapshot.LocalBalance.ToSatoshis()
|
|
|
|
theirAmt := revokedSnapshot.RemoteBalance.ToSatoshis()
|
2017-09-19 22:45:51 +03:00
|
|
|
|
2020-01-06 13:42:04 +03:00
|
|
|
// If our balance exceeds the remote party's dust limit, instantiate
|
|
|
|
// the sign descriptor for our output.
|
|
|
|
if ourAmt >= chanState.RemoteChanCfg.DustLimit {
|
|
|
|
ourSignDesc = &input.SignDescriptor{
|
2018-01-19 00:45:30 +03:00
|
|
|
SingleTweak: keyRing.LocalCommitKeyTweak,
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: chanState.LocalChanCfg.PaymentBasePoint,
|
2020-01-06 13:42:04 +03:00
|
|
|
WitnessScript: ourScript.WitnessScript,
|
2017-09-19 22:45:51 +03:00
|
|
|
Output: &wire.TxOut{
|
2020-01-06 13:42:04 +03:00
|
|
|
PkScript: ourScript.PkScript,
|
|
|
|
Value: int64(ourAmt),
|
2017-09-19 22:45:51 +03:00
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-06 13:42:04 +03:00
|
|
|
// Similarly, if their balance exceeds the remote party's dust limit,
|
|
|
|
// assemble the sign descriptor for their output, which we can sweep.
|
|
|
|
if theirAmt >= chanState.RemoteChanCfg.DustLimit {
|
|
|
|
theirSignDesc = &input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: chanState.LocalChanCfg.RevocationBasePoint,
|
2017-09-19 22:45:51 +03:00
|
|
|
DoubleTweak: commitmentSecret,
|
2020-01-06 13:42:04 +03:00
|
|
|
WitnessScript: theirPkScript,
|
2017-09-19 22:45:51 +03:00
|
|
|
Output: &wire.TxOut{
|
2020-01-06 13:42:04 +03:00
|
|
|
PkScript: theirWitnessHash,
|
|
|
|
Value: int64(theirAmt),
|
2017-09-19 22:45:51 +03:00
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-07-30 23:11:33 +03:00
|
|
|
// With the commitment outputs located, we'll now generate all the
|
|
|
|
// retribution structs for each of the HTLC transactions active on the
|
|
|
|
// remote commitment transaction.
|
2018-04-06 02:19:44 +03:00
|
|
|
htlcRetributions := make([]HtlcRetribution, 0, len(revokedSnapshot.Htlcs))
|
|
|
|
for _, htlc := range revokedSnapshot.Htlcs {
|
2018-04-05 03:07:45 +03:00
|
|
|
// If the HTLC is dust, then we'll skip it as it doesn't have
|
|
|
|
// an output on the commitment transaction.
|
|
|
|
if htlcIsDust(
|
2020-03-06 18:11:49 +03:00
|
|
|
chanState.ChanType, htlc.Incoming, false,
|
2019-10-31 05:43:05 +03:00
|
|
|
chainfee.SatPerKWeight(revokedSnapshot.FeePerKw),
|
2018-04-05 03:07:45 +03:00
|
|
|
htlc.Amt.ToSatoshis(), chanState.RemoteChanCfg.DustLimit,
|
|
|
|
) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-01-21 07:12:49 +03:00
|
|
|
// We'll generate the original second level witness script now,
|
|
|
|
// as we'll need it if we're revoking an HTLC output on the
|
|
|
|
// remote commitment transaction, and *they* go to the second
|
|
|
|
// level.
|
2019-01-16 17:47:43 +03:00
|
|
|
secondLevelWitnessScript, err := input.SecondLevelHtlcScript(
|
2020-01-06 13:42:04 +03:00
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey, theirDelay,
|
2018-01-21 07:12:49 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2017-07-30 23:11:33 +03:00
|
|
|
// If this is an incoming HTLC, then this means that they were
|
|
|
|
// the sender of the HTLC (relative to us). So we'll
|
2020-03-06 18:11:44 +03:00
|
|
|
// re-generate the sender HTLC script. Otherwise, is this was
|
|
|
|
// an outgoing HTLC that we sent, then from the PoV of the
|
|
|
|
// remote commitment state, they're the receiver of this HTLC.
|
|
|
|
htlcPkScript, htlcWitnessScript, err := genHtlcScript(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanState.ChanType, htlc.Incoming, false,
|
|
|
|
htlc.RefundTimeout, htlc.RHash, keyRing,
|
2020-03-06 18:11:44 +03:00
|
|
|
)
|
2018-07-18 05:22:17 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-04-06 02:19:44 +03:00
|
|
|
htlcRetributions = append(htlcRetributions, HtlcRetribution{
|
2019-01-16 17:47:43 +03:00
|
|
|
SignDesc: input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: chanState.LocalChanCfg.RevocationBasePoint,
|
2017-07-30 23:11:33 +03:00
|
|
|
DoubleTweak: commitmentSecret,
|
2018-07-18 05:22:17 +03:00
|
|
|
WitnessScript: htlcWitnessScript,
|
2017-07-30 23:11:33 +03:00
|
|
|
Output: &wire.TxOut{
|
2018-07-18 05:22:17 +03:00
|
|
|
PkScript: htlcPkScript,
|
|
|
|
Value: int64(htlc.Amt.ToSatoshis()),
|
2017-07-30 23:11:33 +03:00
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
},
|
|
|
|
OutPoint: wire.OutPoint{
|
|
|
|
Hash: commitHash,
|
|
|
|
Index: uint32(htlc.OutputIndex),
|
|
|
|
},
|
2018-01-21 07:12:49 +03:00
|
|
|
SecondLevelWitnessScript: secondLevelWitnessScript,
|
|
|
|
IsIncoming: htlc.Incoming,
|
2018-04-06 02:19:44 +03:00
|
|
|
})
|
2017-07-30 23:11:33 +03:00
|
|
|
}
|
|
|
|
|
2016-11-21 09:54:35 +03:00
|
|
|
// Finally, with all the necessary data constructed, we can create the
|
|
|
|
// BreachRetribution struct which houses all the data necessary to
|
|
|
|
// swiftly bring justice to the cheating remote party.
|
|
|
|
return &BreachRetribution{
|
2017-11-10 10:06:10 +03:00
|
|
|
ChainHash: chanState.ChainHash,
|
2018-12-20 08:50:46 +03:00
|
|
|
BreachTransaction: revokedSnapshot.CommitTx,
|
2017-11-21 10:57:33 +03:00
|
|
|
BreachHeight: breachHeight,
|
2017-09-19 22:45:51 +03:00
|
|
|
RevokedStateNum: stateNum,
|
|
|
|
PendingHTLCs: revokedSnapshot.Htlcs,
|
2020-01-06 13:42:04 +03:00
|
|
|
LocalOutpoint: ourOutpoint,
|
|
|
|
LocalOutputSignDesc: ourSignDesc,
|
2020-03-06 18:11:47 +03:00
|
|
|
LocalDelay: ourDelay,
|
2020-01-06 13:42:04 +03:00
|
|
|
RemoteOutpoint: theirOutpoint,
|
|
|
|
RemoteOutputSignDesc: theirSignDesc,
|
2020-03-06 18:11:47 +03:00
|
|
|
RemoteDelay: theirDelay,
|
2017-09-19 22:45:51 +03:00
|
|
|
HtlcRetributions: htlcRetributions,
|
2018-12-20 08:50:44 +03:00
|
|
|
KeyRing: keyRing,
|
2016-11-21 09:54:35 +03:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2017-07-30 22:44:13 +03:00
|
|
|
// htlcIsDust determines if an HTLC output is dust or not depending on two
|
|
|
|
// bits: if the HTLC is incoming and if the HTLC will be placed on our
|
|
|
|
// commitment transaction, or theirs. These two pieces of information are
|
2017-11-29 16:20:02 +03:00
|
|
|
// require as we currently used second-level HTLC transactions as off-chain
|
2017-07-30 22:44:13 +03:00
|
|
|
// covenants. Depending on the two bits, we'll either be using a timeout or
|
|
|
|
// success transaction which have different weights.
|
2020-03-06 18:11:49 +03:00
|
|
|
func htlcIsDust(chanType channeldb.ChannelType,
|
|
|
|
incoming, ourCommit bool, feePerKw chainfee.SatPerKWeight,
|
2018-02-13 16:43:58 +03:00
|
|
|
htlcAmt, dustLimit btcutil.Amount) bool {
|
2017-07-30 22:44:13 +03:00
|
|
|
|
|
|
|
// First we'll determine the fee required for this HTLC based on if this is
|
|
|
|
// an incoming HTLC or not, and also on whose commitment transaction it
|
|
|
|
// will be placed on.
|
|
|
|
var htlcFee btcutil.Amount
|
|
|
|
switch {
|
|
|
|
|
|
|
|
// If this is an incoming HTLC on our commitment transaction, then the
|
|
|
|
// second-level transaction will be a success transaction.
|
|
|
|
case incoming && ourCommit:
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee = HtlcSuccessFee(chanType, feePerKw)
|
2017-07-30 22:44:13 +03:00
|
|
|
|
|
|
|
// If this is an incoming HTLC on their commitment transaction, then
|
|
|
|
// we'll be using a second-level timeout transaction as they've added
|
|
|
|
// this HTLC.
|
|
|
|
case incoming && !ourCommit:
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee = HtlcTimeoutFee(chanType, feePerKw)
|
2017-07-30 22:44:13 +03:00
|
|
|
|
|
|
|
// If this is an outgoing HTLC on our commitment transaction, then
|
|
|
|
// we'll be using a timeout transaction as we're the sender of the
|
|
|
|
// HTLC.
|
|
|
|
case !incoming && ourCommit:
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee = HtlcTimeoutFee(chanType, feePerKw)
|
2017-07-30 22:44:13 +03:00
|
|
|
|
|
|
|
// If this is an outgoing HTLC on their commitment transaction, then
|
|
|
|
// we'll be using an HTLC success transaction as they're the receiver
|
|
|
|
// of this HTLC.
|
|
|
|
case !incoming && !ourCommit:
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee = HtlcSuccessFee(chanType, feePerKw)
|
2017-02-03 04:10:57 +03:00
|
|
|
}
|
|
|
|
|
2017-07-30 22:44:13 +03:00
|
|
|
return (htlcAmt - htlcFee) < dustLimit
|
2017-02-03 04:10:57 +03:00
|
|
|
}
|
|
|
|
|
2017-01-13 08:01:50 +03:00
|
|
|
// htlcView represents the "active" HTLCs at a particular point within the
|
2016-11-21 09:54:35 +03:00
|
|
|
// history of the HTLC update log.
|
2016-07-22 02:50:20 +03:00
|
|
|
type htlcView struct {
|
|
|
|
ourUpdates []*PaymentDescriptor
|
|
|
|
theirUpdates []*PaymentDescriptor
|
2019-10-31 05:43:05 +03:00
|
|
|
feePerKw chainfee.SatPerKWeight
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// fetchHTLCView returns all the candidate HTLC updates which should be
|
|
|
|
// considered for inclusion within a commitment based on the passed HTLC log
|
|
|
|
// indexes.
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
func (lc *LightningChannel) fetchHTLCView(theirLogIndex, ourLogIndex uint64) *htlcView {
|
2016-07-22 02:50:20 +03:00
|
|
|
var ourHTLCs []*PaymentDescriptor
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
for e := lc.localUpdateLog.Front(); e != nil; e = e.Next() {
|
2016-07-22 02:50:20 +03:00
|
|
|
htlc := e.Value.(*PaymentDescriptor)
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// This HTLC is active from this point-of-view iff the log
|
|
|
|
// index of the state update is below the specified index in
|
|
|
|
// our update log.
|
2017-10-23 02:28:30 +03:00
|
|
|
if htlc.LogIndex < ourLogIndex {
|
2016-07-22 02:50:20 +03:00
|
|
|
ourHTLCs = append(ourHTLCs, htlc)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var theirHTLCs []*PaymentDescriptor
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
for e := lc.remoteUpdateLog.Front(); e != nil; e = e.Next() {
|
2016-07-06 03:01:55 +03:00
|
|
|
htlc := e.Value.(*PaymentDescriptor)
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// If this is an incoming HTLC, then it is only active from
|
|
|
|
// this point-of-view if the index of the HTLC addition in
|
|
|
|
// their log is below the specified view index.
|
2017-10-23 02:28:30 +03:00
|
|
|
if htlc.LogIndex < theirLogIndex {
|
2016-07-22 02:50:20 +03:00
|
|
|
theirHTLCs = append(theirHTLCs, htlc)
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
return &htlcView{
|
|
|
|
ourUpdates: ourHTLCs,
|
|
|
|
theirUpdates: theirHTLCs,
|
|
|
|
}
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// fetchCommitmentView returns a populated commitment which expresses the state
|
|
|
|
// of the channel from the point of view of a local or remote chain, evaluating
|
|
|
|
// the HTLC log up to the passed indexes. This function is used to construct
|
|
|
|
// both local and remote commitment transactions in order to sign or verify new
|
|
|
|
// commitment updates. A fully populated commitment is returned which reflects
|
|
|
|
// the proper balances for both sides at this point in the commitment chain.
|
|
|
|
func (lc *LightningChannel) fetchCommitmentView(remoteChain bool,
|
2017-11-10 09:53:18 +03:00
|
|
|
ourLogIndex, ourHtlcIndex, theirLogIndex, theirHtlcIndex uint64,
|
2018-01-19 00:45:30 +03:00
|
|
|
keyRing *CommitmentKeyRing) (*commitment, error) {
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2017-07-30 23:07:38 +03:00
|
|
|
commitChain := lc.localCommitChain
|
2020-01-06 13:42:03 +03:00
|
|
|
dustLimit := lc.channelState.LocalChanCfg.DustLimit
|
2016-07-06 03:01:55 +03:00
|
|
|
if remoteChain {
|
|
|
|
commitChain = lc.remoteCommitChain
|
2020-01-06 13:42:03 +03:00
|
|
|
dustLimit = lc.channelState.RemoteChanCfg.DustLimit
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
nextHeight := commitChain.tip().height + 1
|
|
|
|
|
2017-01-13 08:01:50 +03:00
|
|
|
// Run through all the HTLCs that will be covered by this transaction
|
2016-07-06 03:01:55 +03:00
|
|
|
// in order to update their commitment addition height, and to adjust
|
2020-01-06 13:42:03 +03:00
|
|
|
// the balances on the commitment transaction accordingly. Note that
|
|
|
|
// these balances will be *before* taking a commitment fee from the
|
|
|
|
// initiator.
|
2016-07-22 02:50:20 +03:00
|
|
|
htlcView := lc.fetchHTLCView(theirLogIndex, ourLogIndex)
|
2020-02-12 13:10:19 +03:00
|
|
|
ourBalance, theirBalance, _, filteredHTLCView, err := lc.computeView(
|
2019-01-10 14:23:57 +03:00
|
|
|
htlcView, remoteChain, true,
|
|
|
|
)
|
2020-02-12 13:10:19 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-01-10 14:23:57 +03:00
|
|
|
feePerKw := filteredHTLCView.feePerKw
|
2017-07-14 21:38:35 +03:00
|
|
|
|
2020-01-06 13:42:03 +03:00
|
|
|
// Actually generate unsigned commitment transaction for this view.
|
|
|
|
commitTx, err := lc.commitBuilder.createUnsignedCommitmentTx(
|
|
|
|
ourBalance, theirBalance, !remoteChain, feePerKw, nextHeight,
|
|
|
|
filteredHTLCView, keyRing,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2017-07-30 23:07:38 +03:00
|
|
|
}
|
2017-09-25 23:05:49 +03:00
|
|
|
|
2020-03-06 18:11:46 +03:00
|
|
|
// We'll assert that there hasn't been a mistake during fee calculation
|
|
|
|
// leading to a fee too low.
|
|
|
|
var totalOut btcutil.Amount
|
|
|
|
for _, txOut := range commitTx.txn.TxOut {
|
|
|
|
totalOut += btcutil.Amount(txOut.Value)
|
|
|
|
}
|
|
|
|
fee := lc.channelState.Capacity - totalOut
|
|
|
|
|
|
|
|
// Since the transaction is not signed yet, we use the witness weight
|
|
|
|
// used for weight calculation.
|
|
|
|
uTx := btcutil.NewTx(commitTx.txn)
|
|
|
|
weight := blockchain.GetTransactionWeight(uTx) +
|
|
|
|
input.WitnessCommitmentTxWeight
|
|
|
|
|
|
|
|
effFeeRate := chainfee.SatPerKWeight(fee) * 1000 /
|
|
|
|
chainfee.SatPerKWeight(weight)
|
|
|
|
if effFeeRate < chainfee.FeePerKwFloor {
|
|
|
|
return nil, fmt.Errorf("height=%v, for ChannelPoint(%v) "+
|
|
|
|
"attempts to create commitment wigh feerate %v: %v",
|
|
|
|
nextHeight, lc.channelState.FundingOutpoint,
|
|
|
|
effFeeRate, spew.Sdump(commitTx))
|
|
|
|
}
|
|
|
|
|
2020-01-06 13:42:03 +03:00
|
|
|
// With the commitment view created, store the resulting balances and
|
|
|
|
// transaction with the other parameters for this height.
|
2017-09-25 23:05:49 +03:00
|
|
|
c := &commitment{
|
2020-01-06 13:42:03 +03:00
|
|
|
ourBalance: commitTx.ourBalance,
|
|
|
|
theirBalance: commitTx.theirBalance,
|
|
|
|
txn: commitTx.txn,
|
|
|
|
fee: commitTx.fee,
|
2017-09-25 23:05:49 +03:00
|
|
|
ourMessageIndex: ourLogIndex,
|
2017-11-10 09:53:18 +03:00
|
|
|
ourHtlcIndex: ourHtlcIndex,
|
2017-09-25 23:05:49 +03:00
|
|
|
theirMessageIndex: theirLogIndex,
|
2017-11-10 09:53:18 +03:00
|
|
|
theirHtlcIndex: theirHtlcIndex,
|
|
|
|
height: nextHeight,
|
2017-09-25 23:05:49 +03:00
|
|
|
feePerKw: feePerKw,
|
|
|
|
dustLimit: dustLimit,
|
|
|
|
isOurs: !remoteChain,
|
|
|
|
}
|
|
|
|
|
|
|
|
// In order to ensure _none_ of the HTLC's associated with this new
|
|
|
|
// commitment are mutated, we'll manually copy over each HTLC to its
|
|
|
|
// respective slice.
|
|
|
|
c.outgoingHTLCs = make([]PaymentDescriptor, len(filteredHTLCView.ourUpdates))
|
|
|
|
for i, htlc := range filteredHTLCView.ourUpdates {
|
|
|
|
c.outgoingHTLCs[i] = *htlc
|
|
|
|
}
|
|
|
|
c.incomingHTLCs = make([]PaymentDescriptor, len(filteredHTLCView.theirUpdates))
|
|
|
|
for i, htlc := range filteredHTLCView.theirUpdates {
|
|
|
|
c.incomingHTLCs[i] = *htlc
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll populate all the HTLC indexes so we can track the
|
|
|
|
// locations of each HTLC in the commitment state.
|
2020-03-06 18:11:49 +03:00
|
|
|
if err := c.populateHtlcIndexes(lc.channelState.ChanType); err != nil {
|
2017-09-25 23:05:49 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
2020-01-06 13:42:03 +03:00
|
|
|
func fundingTxIn(chanState *channeldb.OpenChannel) wire.TxIn {
|
|
|
|
return *wire.NewTxIn(&chanState.FundingOutpoint, nil, nil)
|
2017-09-26 07:47:39 +03:00
|
|
|
}
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// evaluateHTLCView processes all update entries in both HTLC update logs,
|
|
|
|
// producing a final view which is the result of properly applying all adds,
|
2019-01-10 14:23:57 +03:00
|
|
|
// settles, timeouts and fee updates found in both logs. The resulting view
|
|
|
|
// returned reflects the current state of HTLCs within the remote or local
|
|
|
|
// commitment chain, and the current commitment fee rate.
|
2018-02-06 22:02:01 +03:00
|
|
|
//
|
|
|
|
// If mutateState is set to true, then the add height of all added HTLCs
|
|
|
|
// will be set to nextHeight, and the remove height of all removed HTLCs
|
|
|
|
// will be set to nextHeight. This should therefore only be set to true
|
|
|
|
// once for each height, and only in concert with signing a new commitment.
|
|
|
|
// TODO(halseth): return htlcs to mutate instead of mutating inside
|
|
|
|
// method.
|
2016-07-22 02:50:20 +03:00
|
|
|
func (lc *LightningChannel) evaluateHTLCView(view *htlcView, ourBalance,
|
2018-02-06 22:02:01 +03:00
|
|
|
theirBalance *lnwire.MilliSatoshi, nextHeight uint64,
|
2020-02-12 13:10:19 +03:00
|
|
|
remoteChain, mutateState bool) (*htlcView, error) {
|
2016-07-22 02:50:20 +03:00
|
|
|
|
2019-01-10 14:23:57 +03:00
|
|
|
// We initialize the view's fee rate to the fee rate of the unfiltered
|
|
|
|
// view. If any fee updates are found when evaluating the view, it will
|
|
|
|
// be updated.
|
|
|
|
newView := &htlcView{
|
|
|
|
feePerKw: view.feePerKw,
|
|
|
|
}
|
2016-07-22 02:50:20 +03:00
|
|
|
|
|
|
|
// We use two maps, one for the local log and one for the remote log to
|
|
|
|
// keep track of which entries we need to skip when creating the final
|
|
|
|
// htlc view. We skip an entry whenever we find a settle or a timeout
|
|
|
|
// modifying an entry.
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
skipUs := make(map[uint64]struct{})
|
|
|
|
skipThem := make(map[uint64]struct{})
|
2016-07-22 02:50:20 +03:00
|
|
|
|
2020-02-12 13:10:18 +03:00
|
|
|
// fetchParentEntry is a helper method that will fetch the parent of
|
|
|
|
// entry from the corresponding update log.
|
|
|
|
fetchParentEntry := func(entry *PaymentDescriptor,
|
2020-02-12 13:10:19 +03:00
|
|
|
remoteLog bool) (*PaymentDescriptor, error) {
|
2020-02-12 13:10:18 +03:00
|
|
|
|
|
|
|
var (
|
|
|
|
updateLog *updateLog
|
|
|
|
logName string
|
|
|
|
)
|
|
|
|
|
|
|
|
if remoteLog {
|
|
|
|
updateLog = lc.remoteUpdateLog
|
|
|
|
logName = "remote"
|
|
|
|
} else {
|
|
|
|
updateLog = lc.localUpdateLog
|
|
|
|
logName = "local"
|
|
|
|
}
|
|
|
|
|
|
|
|
addEntry := updateLog.lookupHtlc(entry.ParentIndex)
|
|
|
|
|
|
|
|
switch {
|
2020-02-12 13:10:19 +03:00
|
|
|
// We check if the parent entry is not found at this point.
|
|
|
|
// This could happen for old versions of lnd, and we return an
|
|
|
|
// error to gracefully shut down the state machine if such an
|
|
|
|
// entry is still in the logs.
|
2020-02-12 13:10:18 +03:00
|
|
|
case addEntry == nil:
|
2020-02-12 13:10:19 +03:00
|
|
|
return nil, fmt.Errorf("unable to find parent entry "+
|
|
|
|
"%d in %v update log: %v\nUpdatelog: %v",
|
2020-02-12 13:10:18 +03:00
|
|
|
entry.ParentIndex, logName,
|
|
|
|
newLogClosure(func() string {
|
|
|
|
return spew.Sdump(entry)
|
|
|
|
}), newLogClosure(func() string {
|
|
|
|
return spew.Sdump(updateLog)
|
|
|
|
}),
|
2020-02-12 13:10:19 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// The parent add height should never be zero at this point. If
|
|
|
|
// that's the case we probably forgot to send a new commitment.
|
|
|
|
case remoteChain && addEntry.addCommitHeightRemote == 0:
|
|
|
|
return nil, fmt.Errorf("parent entry %d for update %d "+
|
|
|
|
"had zero remote add height", entry.ParentIndex,
|
|
|
|
entry.LogIndex)
|
|
|
|
case !remoteChain && addEntry.addCommitHeightLocal == 0:
|
|
|
|
return nil, fmt.Errorf("parent entry %d for update %d "+
|
|
|
|
"had zero local add height", entry.ParentIndex,
|
|
|
|
entry.LogIndex)
|
2020-02-12 13:10:18 +03:00
|
|
|
}
|
|
|
|
|
2020-02-12 13:10:19 +03:00
|
|
|
return addEntry, nil
|
2020-02-12 13:10:18 +03:00
|
|
|
}
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// First we run through non-add entries in both logs, populating the
|
2017-07-30 22:25:41 +03:00
|
|
|
// skip sets and mutating the current chain state (crediting balances,
|
|
|
|
// etc) to reflect the settle/timeout entry encountered.
|
2016-07-22 02:50:20 +03:00
|
|
|
for _, entry := range view.ourUpdates {
|
2019-01-10 14:23:57 +03:00
|
|
|
switch entry.EntryType {
|
|
|
|
// Skip adds for now. They will be processed below.
|
|
|
|
case Add:
|
|
|
|
continue
|
|
|
|
|
|
|
|
// Process fee updates, updating the current feePerKw.
|
|
|
|
case FeeUpdate:
|
|
|
|
processFeeUpdate(
|
|
|
|
entry, nextHeight, remoteChain, mutateState,
|
|
|
|
newView,
|
|
|
|
)
|
2016-07-22 02:50:20 +03:00
|
|
|
continue
|
|
|
|
}
|
2017-02-21 03:39:04 +03:00
|
|
|
|
2017-09-25 21:25:58 +03:00
|
|
|
// If we're settling an inbound HTLC, and it hasn't been
|
|
|
|
// processed yet, then increment our state tracking the total
|
2017-02-21 03:39:04 +03:00
|
|
|
// number of satoshis we've received within the channel.
|
2018-02-06 22:02:01 +03:00
|
|
|
if mutateState && entry.EntryType == Settle && !remoteChain &&
|
2017-02-21 03:39:04 +03:00
|
|
|
entry.removeCommitHeightLocal == 0 {
|
2017-08-22 09:20:29 +03:00
|
|
|
lc.channelState.TotalMSatReceived += entry.Amount
|
2016-11-18 01:39:38 +03:00
|
|
|
}
|
2016-07-22 02:50:20 +03:00
|
|
|
|
2020-02-12 13:10:19 +03:00
|
|
|
addEntry, err := fetchParentEntry(entry, true)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-05-04 14:25:10 +03:00
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
skipThem[addEntry.HtlcIndex] = struct{}{}
|
2016-07-22 02:50:20 +03:00
|
|
|
processRemoveEntry(entry, ourBalance, theirBalance,
|
2018-02-06 22:02:01 +03:00
|
|
|
nextHeight, remoteChain, true, mutateState)
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-07-22 02:50:20 +03:00
|
|
|
for _, entry := range view.theirUpdates {
|
2019-01-10 14:23:57 +03:00
|
|
|
switch entry.EntryType {
|
|
|
|
// Skip adds for now. They will be processed below.
|
|
|
|
case Add:
|
|
|
|
continue
|
|
|
|
|
|
|
|
// Process fee updates, updating the current feePerKw.
|
|
|
|
case FeeUpdate:
|
|
|
|
processFeeUpdate(
|
|
|
|
entry, nextHeight, remoteChain, mutateState,
|
|
|
|
newView,
|
|
|
|
)
|
2016-07-22 02:50:20 +03:00
|
|
|
continue
|
|
|
|
}
|
2017-02-21 03:39:04 +03:00
|
|
|
|
|
|
|
// If the remote party is settling one of our outbound HTLC's,
|
|
|
|
// and it hasn't been processed, yet, the increment our state
|
|
|
|
// tracking the total number of satoshis we've sent within the
|
|
|
|
// channel.
|
2018-02-06 22:02:01 +03:00
|
|
|
if mutateState && entry.EntryType == Settle && !remoteChain &&
|
2017-02-21 03:39:04 +03:00
|
|
|
entry.removeCommitHeightLocal == 0 {
|
2017-08-22 09:20:29 +03:00
|
|
|
lc.channelState.TotalMSatSent += entry.Amount
|
2016-11-18 01:39:38 +03:00
|
|
|
}
|
2016-07-22 02:50:20 +03:00
|
|
|
|
2020-02-12 13:10:19 +03:00
|
|
|
addEntry, err := fetchParentEntry(entry, false)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-05-04 14:25:10 +03:00
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
skipUs[addEntry.HtlcIndex] = struct{}{}
|
2016-07-22 02:50:20 +03:00
|
|
|
processRemoveEntry(entry, ourBalance, theirBalance,
|
2018-02-06 22:02:01 +03:00
|
|
|
nextHeight, remoteChain, false, mutateState)
|
2016-07-22 02:50:20 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Next we take a second pass through all the log entries, skipping any
|
2017-07-30 22:25:41 +03:00
|
|
|
// settled HTLCs, and debiting the chain state balance due to any newly
|
|
|
|
// added HTLCs.
|
2016-07-22 02:50:20 +03:00
|
|
|
for _, entry := range view.ourUpdates {
|
|
|
|
isAdd := entry.EntryType == Add
|
2017-10-23 02:28:30 +03:00
|
|
|
if _, ok := skipUs[entry.HtlcIndex]; !isAdd || ok {
|
2016-07-22 02:50:20 +03:00
|
|
|
continue
|
|
|
|
}
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
processAddEntry(entry, ourBalance, theirBalance, nextHeight,
|
2018-02-06 22:02:01 +03:00
|
|
|
remoteChain, false, mutateState)
|
2016-07-22 02:50:20 +03:00
|
|
|
newView.ourUpdates = append(newView.ourUpdates, entry)
|
|
|
|
}
|
|
|
|
for _, entry := range view.theirUpdates {
|
|
|
|
isAdd := entry.EntryType == Add
|
2017-10-23 02:28:30 +03:00
|
|
|
if _, ok := skipThem[entry.HtlcIndex]; !isAdd || ok {
|
2016-07-22 02:50:20 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
processAddEntry(entry, ourBalance, theirBalance, nextHeight,
|
2018-02-06 22:02:01 +03:00
|
|
|
remoteChain, true, mutateState)
|
2016-07-22 02:50:20 +03:00
|
|
|
newView.theirUpdates = append(newView.theirUpdates, entry)
|
|
|
|
}
|
|
|
|
|
2020-02-12 13:10:19 +03:00
|
|
|
return newView, nil
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// processAddEntry evaluates the effect of an add entry within the HTLC log.
|
2016-07-06 03:01:55 +03:00
|
|
|
// If the HTLC hasn't yet been committed in either chain, then the height it
|
2016-10-26 15:25:42 +03:00
|
|
|
// was committed is updated. Keeping track of this inclusion height allows us to
|
2016-07-06 03:01:55 +03:00
|
|
|
// later compact the log once the change is fully committed in both chains.
|
2017-08-22 09:20:29 +03:00
|
|
|
func processAddEntry(htlc *PaymentDescriptor, ourBalance, theirBalance *lnwire.MilliSatoshi,
|
2018-02-06 22:02:01 +03:00
|
|
|
nextHeight uint64, remoteChain bool, isIncoming, mutateState bool) {
|
2016-07-06 03:01:55 +03:00
|
|
|
|
|
|
|
// If we're evaluating this entry for the remote chain (to create/view
|
|
|
|
// a new commitment), then we'll may be updating the height this entry
|
|
|
|
// was added to the chain. Otherwise, we may be updating the entry's
|
|
|
|
// height w.r.t the local chain.
|
|
|
|
var addHeight *uint64
|
|
|
|
if remoteChain {
|
|
|
|
addHeight = &htlc.addCommitHeightRemote
|
|
|
|
} else {
|
|
|
|
addHeight = &htlc.addCommitHeightLocal
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
if *addHeight != 0 {
|
|
|
|
return
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
if isIncoming {
|
2016-07-06 03:01:55 +03:00
|
|
|
// If this is a new incoming (un-committed) HTLC, then we need
|
|
|
|
// to update their balance accordingly by subtracting the
|
|
|
|
// amount of the HTLC that are funds pending.
|
|
|
|
*theirBalance -= htlc.Amount
|
|
|
|
} else {
|
2016-07-22 02:50:20 +03:00
|
|
|
// Similarly, we need to debit our balance if this is an out
|
2016-07-06 03:01:55 +03:00
|
|
|
// going HTLC to reflect the pending balance.
|
|
|
|
*ourBalance -= htlc.Amount
|
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2018-02-06 22:02:01 +03:00
|
|
|
if mutateState {
|
|
|
|
*addHeight = nextHeight
|
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:53:18 +03:00
|
|
|
// processRemoveEntry processes a log entry which settles or times out a
|
2016-07-06 03:01:55 +03:00
|
|
|
// previously added HTLC. If the removal entry has already been processed, it
|
|
|
|
// is skipped.
|
|
|
|
func processRemoveEntry(htlc *PaymentDescriptor, ourBalance,
|
2017-08-22 09:20:29 +03:00
|
|
|
theirBalance *lnwire.MilliSatoshi, nextHeight uint64,
|
2018-02-06 22:02:01 +03:00
|
|
|
remoteChain bool, isIncoming, mutateState bool) {
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
var removeHeight *uint64
|
|
|
|
if remoteChain {
|
|
|
|
removeHeight = &htlc.removeCommitHeightRemote
|
|
|
|
} else {
|
|
|
|
removeHeight = &htlc.removeCommitHeightLocal
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// Ignore any removal entries which have already been processed.
|
|
|
|
if *removeHeight != 0 {
|
|
|
|
return
|
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
switch {
|
|
|
|
// If an incoming HTLC is being settled, then this means that we've
|
2017-01-13 08:01:50 +03:00
|
|
|
// received the preimage either from another subsystem, or the
|
2016-07-06 03:01:55 +03:00
|
|
|
// upstream peer in the route. Therefore, we increase our balance by
|
|
|
|
// the HTLC amount.
|
2016-07-22 02:50:20 +03:00
|
|
|
case isIncoming && htlc.EntryType == Settle:
|
2016-07-06 03:01:55 +03:00
|
|
|
*ourBalance += htlc.Amount
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
|
|
|
|
// Otherwise, this HTLC is being failed out, therefore the value of the
|
2016-07-06 03:01:55 +03:00
|
|
|
// HTLC should return to the remote party.
|
2017-08-14 14:21:57 +03:00
|
|
|
case isIncoming && (htlc.EntryType == Fail || htlc.EntryType == MalformedFail):
|
2016-07-06 03:01:55 +03:00
|
|
|
*theirBalance += htlc.Amount
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// If an outgoing HTLC is being settled, then this means that the
|
|
|
|
// downstream party resented the preimage or learned of it via a
|
|
|
|
// downstream peer. In either case, we credit their settled value with
|
|
|
|
// the value of the HTLC.
|
2016-07-22 02:50:20 +03:00
|
|
|
case !isIncoming && htlc.EntryType == Settle:
|
2016-07-06 03:01:55 +03:00
|
|
|
*theirBalance += htlc.Amount
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
|
|
|
|
// Otherwise, one of our outgoing HTLC's has timed out, so the value of
|
|
|
|
// the HTLC should be returned to our settled balance.
|
2017-08-14 14:21:57 +03:00
|
|
|
case !isIncoming && (htlc.EntryType == Fail || htlc.EntryType == MalformedFail):
|
2016-07-06 03:01:55 +03:00
|
|
|
*ourBalance += htlc.Amount
|
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2018-02-06 22:02:01 +03:00
|
|
|
if mutateState {
|
|
|
|
*removeHeight = nextHeight
|
|
|
|
}
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-06-21 08:07:03 +03:00
|
|
|
|
2019-01-10 14:23:57 +03:00
|
|
|
// processFeeUpdate processes a log update that updates the current commitment
|
|
|
|
// fee.
|
|
|
|
func processFeeUpdate(feeUpdate *PaymentDescriptor, nextHeight uint64,
|
|
|
|
remoteChain bool, mutateState bool, view *htlcView) {
|
|
|
|
|
|
|
|
// Fee updates are applied for all commitments after they are
|
|
|
|
// sent/received, so we consider them being added and removed at the
|
|
|
|
// same height.
|
|
|
|
var addHeight *uint64
|
|
|
|
var removeHeight *uint64
|
|
|
|
if remoteChain {
|
|
|
|
addHeight = &feeUpdate.addCommitHeightRemote
|
|
|
|
removeHeight = &feeUpdate.removeCommitHeightRemote
|
|
|
|
} else {
|
|
|
|
addHeight = &feeUpdate.addCommitHeightLocal
|
|
|
|
removeHeight = &feeUpdate.removeCommitHeightLocal
|
|
|
|
}
|
|
|
|
|
|
|
|
if *addHeight != 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the update wasn't already locked in, update the current fee rate
|
|
|
|
// to reflect this update.
|
2019-10-31 05:43:05 +03:00
|
|
|
view.feePerKw = chainfee.SatPerKWeight(feeUpdate.Amount.ToSatoshis())
|
2019-01-10 14:23:57 +03:00
|
|
|
|
|
|
|
if mutateState {
|
|
|
|
*addHeight = nextHeight
|
|
|
|
*removeHeight = nextHeight
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-07-30 23:00:24 +03:00
|
|
|
// generateRemoteHtlcSigJobs generates a series of HTLC signature jobs for the
|
|
|
|
// sig pool, along with a channel that if closed, will cancel any jobs after
|
|
|
|
// they have been submitted to the sigPool. This method is to be used when
|
|
|
|
// generating a new commitment for the remote party. The jobs generated by the
|
|
|
|
// signature can be submitted to the sigPool to generate all the signatures
|
|
|
|
// asynchronously and in parallel.
|
2018-01-19 00:45:30 +03:00
|
|
|
func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing,
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType channeldb.ChannelType,
|
2017-07-30 23:00:24 +03:00
|
|
|
localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
remoteCommitView *commitment) ([]SignJob, chan struct{}, error) {
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
txHash := remoteCommitView.txn.TxHash()
|
2018-03-22 15:04:57 +03:00
|
|
|
dustLimit := remoteChanCfg.DustLimit
|
2017-07-30 23:00:24 +03:00
|
|
|
feePerKw := remoteCommitView.feePerKw
|
2020-03-06 18:11:47 +03:00
|
|
|
sigHashType := HtlcSigHashType(chanType)
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
// With the keys generated, we'll make a slice with enough capacity to
|
2018-04-18 05:02:04 +03:00
|
|
|
// hold potentially all the HTLCs. The actual slice may be a bit
|
|
|
|
// smaller (than its total capacity) and some HTLCs may be dust.
|
2017-07-30 23:00:24 +03:00
|
|
|
numSigs := (len(remoteCommitView.incomingHTLCs) +
|
|
|
|
len(remoteCommitView.outgoingHTLCs))
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigBatch := make([]SignJob, 0, numSigs)
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
var err error
|
|
|
|
cancelChan := make(chan struct{})
|
|
|
|
|
2018-04-18 05:02:04 +03:00
|
|
|
// For each outgoing and incoming HTLC, if the HTLC isn't considered a
|
2017-07-30 23:00:24 +03:00
|
|
|
// dust output after taking into account second-level HTLC fees, then a
|
|
|
|
// sigJob will be generated and appended to the current batch.
|
|
|
|
for _, htlc := range remoteCommitView.incomingHTLCs {
|
2020-03-06 18:11:49 +03:00
|
|
|
if htlcIsDust(
|
|
|
|
chanType, true, false, feePerKw,
|
|
|
|
htlc.Amount.ToSatoshis(), dustLimit,
|
|
|
|
) {
|
2017-07-30 23:00:24 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the HTLC isn't dust, then we'll create an empty sign job
|
|
|
|
// to add to the batch momentarily.
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigJob := SignJob{}
|
|
|
|
sigJob.Cancel = cancelChan
|
|
|
|
sigJob.Resp = make(chan SignJobResp, 1)
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
// As this is an incoming HTLC and we're sinning the commitment
|
|
|
|
// transaction of the remote node, we'll need to generate an
|
|
|
|
// HTLC timeout transaction for them. The output of the timeout
|
|
|
|
// transaction needs to account for fees, so we'll compute the
|
|
|
|
// required fee and output now.
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee := HtlcTimeoutFee(chanType, feePerKw)
|
2017-08-22 09:20:29 +03:00
|
|
|
outputAmt := htlc.Amount.ToSatoshis() - htlcFee
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
// With the fee calculate, we can properly create the HTLC
|
|
|
|
// timeout transaction using the HTLC amount minus the fee.
|
|
|
|
op := wire.OutPoint{
|
|
|
|
Hash: txHash,
|
|
|
|
Index: uint32(htlc.remoteOutputIndex),
|
|
|
|
}
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigJob.Tx, err = createHtlcTimeoutTx(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, op, outputAmt, htlc.Timeout,
|
2018-04-05 03:41:05 +03:00
|
|
|
uint32(remoteChanCfg.CsvDelay),
|
2020-01-06 13:42:04 +03:00
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey,
|
2018-04-05 03:41:05 +03:00
|
|
|
)
|
2017-07-30 23:00:24 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll generate a sign descriptor to generate a
|
|
|
|
// signature to give to the remote party for this commitment
|
|
|
|
// transaction. Note we use the raw HTLC amount.
|
2019-01-16 17:47:43 +03:00
|
|
|
sigJob.SignDesc = input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.HtlcBasePoint,
|
2018-01-19 00:45:30 +03:00
|
|
|
SingleTweak: keyRing.LocalHtlcKeyTweak,
|
2017-07-30 23:00:24 +03:00
|
|
|
WitnessScript: htlc.theirWitnessScript,
|
|
|
|
Output: &wire.TxOut{
|
2017-08-22 09:20:29 +03:00
|
|
|
Value: int64(htlc.Amount.ToSatoshis()),
|
2017-07-30 23:00:24 +03:00
|
|
|
},
|
2020-03-06 18:11:47 +03:00
|
|
|
HashType: sigHashType,
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
SigHashes: txscript.NewTxSigHashes(sigJob.Tx),
|
2017-07-30 23:00:24 +03:00
|
|
|
InputIndex: 0,
|
|
|
|
}
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigJob.OutputIndex = htlc.remoteOutputIndex
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
sigBatch = append(sigBatch, sigJob)
|
|
|
|
}
|
|
|
|
for _, htlc := range remoteCommitView.outgoingHTLCs {
|
2020-03-06 18:11:49 +03:00
|
|
|
if htlcIsDust(
|
|
|
|
chanType, false, false, feePerKw,
|
|
|
|
htlc.Amount.ToSatoshis(), dustLimit,
|
|
|
|
) {
|
2017-07-30 23:00:24 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigJob := SignJob{}
|
|
|
|
sigJob.Cancel = cancelChan
|
|
|
|
sigJob.Resp = make(chan SignJobResp, 1)
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
// As this is an outgoing HTLC and we're signing the commitment
|
|
|
|
// transaction of the remote node, we'll need to generate an
|
|
|
|
// HTLC success transaction for them. The output of the timeout
|
|
|
|
// transaction needs to account for fees, so we'll compute the
|
|
|
|
// required fee and output now.
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee := HtlcSuccessFee(chanType, feePerKw)
|
2017-08-22 09:20:29 +03:00
|
|
|
outputAmt := htlc.Amount.ToSatoshis() - htlcFee
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
// With the proper output amount calculated, we can now
|
|
|
|
// generate the success transaction using the remote party's
|
|
|
|
// CSV delay.
|
|
|
|
op := wire.OutPoint{
|
|
|
|
Hash: txHash,
|
|
|
|
Index: uint32(htlc.remoteOutputIndex),
|
|
|
|
}
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigJob.Tx, err = createHtlcSuccessTx(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, op, outputAmt, uint32(remoteChanCfg.CsvDelay),
|
2020-01-06 13:42:04 +03:00
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey,
|
2018-04-05 03:41:05 +03:00
|
|
|
)
|
2017-07-30 23:00:24 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll generate a sign descriptor to generate a
|
|
|
|
// signature to give to the remote party for this commitment
|
|
|
|
// transaction. Note we use the raw HTLC amount.
|
2019-01-16 17:47:43 +03:00
|
|
|
sigJob.SignDesc = input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.HtlcBasePoint,
|
2018-01-19 00:45:30 +03:00
|
|
|
SingleTweak: keyRing.LocalHtlcKeyTweak,
|
2017-07-30 23:00:24 +03:00
|
|
|
WitnessScript: htlc.theirWitnessScript,
|
|
|
|
Output: &wire.TxOut{
|
2017-08-22 09:20:29 +03:00
|
|
|
Value: int64(htlc.Amount.ToSatoshis()),
|
2017-07-30 23:00:24 +03:00
|
|
|
},
|
2020-03-06 18:11:47 +03:00
|
|
|
HashType: sigHashType,
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
SigHashes: txscript.NewTxSigHashes(sigJob.Tx),
|
2017-07-30 23:00:24 +03:00
|
|
|
InputIndex: 0,
|
|
|
|
}
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sigJob.OutputIndex = htlc.remoteOutputIndex
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
sigBatch = append(sigBatch, sigJob)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sigBatch, cancelChan, nil
|
|
|
|
}
|
|
|
|
|
2017-11-10 09:55:38 +03:00
|
|
|
// createCommitDiff will create a commit diff given a new pending commitment
|
|
|
|
// for the remote party and the necessary signatures for the remote party to
|
|
|
|
// validate this new state. This function is called right before sending the
|
|
|
|
// new commitment to the remote party. The commit diff returned contains all
|
|
|
|
// information necessary for retransmission.
|
|
|
|
func (lc *LightningChannel) createCommitDiff(
|
2018-01-31 06:55:39 +03:00
|
|
|
newCommit *commitment, commitSig lnwire.Sig,
|
|
|
|
htlcSigs []lnwire.Sig) (*channeldb.CommitDiff, error) {
|
2017-11-10 09:55:38 +03:00
|
|
|
|
|
|
|
// First, we need to convert the funding outpoint into the ID that's
|
|
|
|
// used on the wire to identify this channel. We'll use this shortly
|
|
|
|
// when recording the exact CommitSig message that we'll be sending
|
|
|
|
// out.
|
2017-08-14 12:14:04 +03:00
|
|
|
chanID := lnwire.NewChanIDFromOutPoint(&lc.channelState.FundingOutpoint)
|
2017-11-10 09:55:38 +03:00
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
var (
|
2019-01-10 14:23:57 +03:00
|
|
|
logUpdates []channeldb.LogUpdate
|
2018-02-28 07:01:41 +03:00
|
|
|
ackAddRefs []channeldb.AddRef
|
|
|
|
settleFailRefs []channeldb.SettleFailRef
|
|
|
|
openCircuitKeys []channeldb.CircuitKey
|
|
|
|
closedCircuitKeys []channeldb.CircuitKey
|
|
|
|
)
|
|
|
|
|
2017-11-10 09:55:38 +03:00
|
|
|
// We'll now run through our local update log to locate the items which
|
|
|
|
// were only just committed within this pending state. This will be the
|
|
|
|
// set of items we need to retransmit if we reconnect and find that
|
|
|
|
// they didn't process this new state fully.
|
2017-08-14 12:14:04 +03:00
|
|
|
for e := lc.localUpdateLog.Front(); e != nil; e = e.Next() {
|
|
|
|
pd := e.Value.(*PaymentDescriptor)
|
|
|
|
|
2017-11-10 09:55:38 +03:00
|
|
|
// If this entry wasn't committed at the exact height of this
|
|
|
|
// remote commitment, then we'll skip it as it was already
|
|
|
|
// lingering in the log.
|
|
|
|
if pd.addCommitHeightRemote != newCommit.height &&
|
|
|
|
pd.removeCommitHeightRemote != newCommit.height {
|
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Knowing that this update is a part of this new commitment,
|
2018-02-07 06:13:07 +03:00
|
|
|
// we'll create a log update and not its index in the log so
|
2017-11-10 09:55:38 +03:00
|
|
|
// we can later restore it properly if a restart occurs.
|
|
|
|
logUpdate := channeldb.LogUpdate{
|
|
|
|
LogIndex: pd.LogIndex,
|
|
|
|
}
|
|
|
|
|
|
|
|
// We'll map the type of the PaymentDescriptor to one of the
|
|
|
|
// four messages that it corresponds to. With this set of
|
|
|
|
// messages obtained, we can simply read from disk and re-send
|
|
|
|
// them in the case of a needed channel sync.
|
|
|
|
switch pd.EntryType {
|
|
|
|
case Add:
|
|
|
|
htlc := &lnwire.UpdateAddHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.HtlcIndex,
|
|
|
|
Amount: pd.Amount,
|
|
|
|
Expiry: pd.Timeout,
|
|
|
|
PaymentHash: pd.RHash,
|
|
|
|
}
|
|
|
|
copy(htlc.OnionBlob[:], pd.OnionBlob)
|
|
|
|
logUpdate.UpdateMsg = htlc
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// Gather any references for circuits opened by this Add
|
|
|
|
// HTLC.
|
2018-02-28 07:04:41 +03:00
|
|
|
if pd.OpenCircuitKey != nil {
|
2018-02-28 07:01:41 +03:00
|
|
|
openCircuitKeys = append(openCircuitKeys,
|
2018-02-28 07:04:41 +03:00
|
|
|
*pd.OpenCircuitKey)
|
2018-02-28 07:01:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
logUpdates = append(logUpdates, logUpdate)
|
|
|
|
|
|
|
|
// Short circuit here since an add should not have any
|
|
|
|
// of the references gathered in the case of settles,
|
|
|
|
// fails or malformed fails.
|
|
|
|
continue
|
|
|
|
|
2017-11-10 09:55:38 +03:00
|
|
|
case Settle:
|
2018-02-07 06:11:11 +03:00
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFulfillHTLC{
|
2017-11-10 09:55:38 +03:00
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
PaymentPreimage: pd.RPreimage,
|
|
|
|
}
|
|
|
|
|
|
|
|
case Fail:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFailHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
Reason: pd.FailReason,
|
2017-08-14 12:14:04 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:55:38 +03:00
|
|
|
case MalformedFail:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFailMalformedHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
ShaOnionBlob: pd.ShaOnionBlob,
|
|
|
|
FailureCode: pd.FailCode,
|
|
|
|
}
|
2019-01-10 14:23:56 +03:00
|
|
|
|
|
|
|
case FeeUpdate:
|
|
|
|
// The Amount field holds the feerate denominated in
|
|
|
|
// msat. Since feerates are only denominated in sat/kw,
|
|
|
|
// we can convert it without loss of precision.
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFee{
|
|
|
|
ChanID: chanID,
|
|
|
|
FeePerKw: uint32(pd.Amount.ToSatoshis()),
|
|
|
|
}
|
2017-08-14 12:14:04 +03:00
|
|
|
}
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// Gather the fwd pkg references from any settle or fail
|
|
|
|
// packets, if they exist.
|
|
|
|
if pd.SourceRef != nil {
|
|
|
|
ackAddRefs = append(ackAddRefs, *pd.SourceRef)
|
|
|
|
}
|
|
|
|
if pd.DestRef != nil {
|
|
|
|
settleFailRefs = append(settleFailRefs, *pd.DestRef)
|
|
|
|
}
|
2018-02-28 07:04:41 +03:00
|
|
|
if pd.ClosedCircuitKey != nil {
|
2018-02-28 07:01:41 +03:00
|
|
|
closedCircuitKeys = append(closedCircuitKeys,
|
2018-02-28 07:04:41 +03:00
|
|
|
*pd.ClosedCircuitKey)
|
2018-02-28 07:01:41 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:55:38 +03:00
|
|
|
logUpdates = append(logUpdates, logUpdate)
|
2017-08-14 12:14:04 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:55:38 +03:00
|
|
|
// With the set of log updates mapped into wire messages, we'll now
|
|
|
|
// convert the in-memory commit into a format suitable for writing to
|
|
|
|
// disk.
|
|
|
|
diskCommit := newCommit.toDiskCommit(false)
|
|
|
|
|
2017-08-14 12:14:04 +03:00
|
|
|
return &channeldb.CommitDiff{
|
2017-11-10 09:55:38 +03:00
|
|
|
Commitment: *diskCommit,
|
|
|
|
CommitSig: &lnwire.CommitSig{
|
|
|
|
ChanID: lnwire.NewChanIDFromOutPoint(
|
|
|
|
&lc.channelState.FundingOutpoint,
|
|
|
|
),
|
|
|
|
CommitSig: commitSig,
|
|
|
|
HtlcSigs: htlcSigs,
|
|
|
|
},
|
2018-02-28 07:01:41 +03:00
|
|
|
LogUpdates: logUpdates,
|
|
|
|
OpenedCircuitKeys: openCircuitKeys,
|
|
|
|
ClosedCircuitKeys: closedCircuitKeys,
|
|
|
|
AddAcks: ackAddRefs,
|
|
|
|
SettleFailAcks: settleFailRefs,
|
2017-08-14 12:14:04 +03:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-01-03 17:53:51 +03:00
|
|
|
// getUnsignedAckedUpdates returns all remote log updates that we haven't
|
|
|
|
// signed for yet ourselves.
|
|
|
|
func (lc *LightningChannel) getUnsignedAckedUpdates() []channeldb.LogUpdate {
|
|
|
|
// First, we need to convert the funding outpoint into the ID that's
|
|
|
|
// used on the wire to identify this channel.
|
|
|
|
chanID := lnwire.NewChanIDFromOutPoint(&lc.channelState.FundingOutpoint)
|
|
|
|
|
|
|
|
// Fetch the last remote update that we have signed for.
|
|
|
|
lastRemoteCommitted := lc.remoteCommitChain.tip().theirMessageIndex
|
|
|
|
|
|
|
|
// Fetch the last remote update that we have acked.
|
|
|
|
lastLocalCommitted := lc.localCommitChain.tail().theirMessageIndex
|
|
|
|
|
|
|
|
// We'll now run through the remote update log to locate the items that
|
|
|
|
// we haven't signed for yet. This will be the set of items we need to
|
|
|
|
// restore if we reconnect in order to produce the signature that the
|
|
|
|
// remote party expects.
|
|
|
|
var logUpdates []channeldb.LogUpdate
|
|
|
|
for e := lc.remoteUpdateLog.Front(); e != nil; e = e.Next() {
|
|
|
|
pd := e.Value.(*PaymentDescriptor)
|
|
|
|
|
|
|
|
// Skip all remote updates that we have already included in our
|
|
|
|
// commit chain.
|
|
|
|
if pd.LogIndex < lastRemoteCommitted {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Skip all remote updates that we haven't acked yet. At the
|
|
|
|
// moment this function is called, there shouldn't be any, but
|
|
|
|
// we check it anyway to make this function more generally
|
|
|
|
// usable.
|
|
|
|
if pd.LogIndex >= lastLocalCommitted {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
logUpdate := channeldb.LogUpdate{
|
|
|
|
LogIndex: pd.LogIndex,
|
|
|
|
}
|
|
|
|
|
|
|
|
// We'll map the type of the PaymentDescriptor to one of the
|
|
|
|
// four messages that it corresponds to.
|
|
|
|
switch pd.EntryType {
|
|
|
|
case Add:
|
|
|
|
htlc := &lnwire.UpdateAddHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.HtlcIndex,
|
|
|
|
Amount: pd.Amount,
|
|
|
|
Expiry: pd.Timeout,
|
|
|
|
PaymentHash: pd.RHash,
|
|
|
|
}
|
|
|
|
copy(htlc.OnionBlob[:], pd.OnionBlob)
|
|
|
|
logUpdate.UpdateMsg = htlc
|
|
|
|
|
|
|
|
case Settle:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFulfillHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
PaymentPreimage: pd.RPreimage,
|
|
|
|
}
|
|
|
|
|
|
|
|
case Fail:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFailHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
Reason: pd.FailReason,
|
|
|
|
}
|
|
|
|
|
|
|
|
case MalformedFail:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFailMalformedHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
ShaOnionBlob: pd.ShaOnionBlob,
|
|
|
|
FailureCode: pd.FailCode,
|
|
|
|
}
|
|
|
|
|
|
|
|
case FeeUpdate:
|
|
|
|
// The Amount field holds the feerate denominated in
|
|
|
|
// msat. Since feerates are only denominated in sat/kw,
|
|
|
|
// we can convert it without loss of precision.
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFee{
|
|
|
|
ChanID: chanID,
|
|
|
|
FeePerKw: uint32(pd.Amount.ToSatoshis()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
logUpdates = append(logUpdates, logUpdate)
|
|
|
|
}
|
|
|
|
return logUpdates
|
|
|
|
}
|
|
|
|
|
2019-08-01 06:10:45 +03:00
|
|
|
// validateCommitmentSanity is used to validate the current state of the
|
|
|
|
// commitment transaction in terms of the ChannelConstraints that we and our
|
2020-02-19 14:27:41 +03:00
|
|
|
// remote peer agreed upon during the funding workflow. The
|
|
|
|
// predict[Our|Their]Add should parameters should be set to a valid
|
|
|
|
// PaymentDescriptor if we are validating in the state when adding a new HTLC,
|
|
|
|
// or nil otherwise.
|
2019-08-01 06:10:45 +03:00
|
|
|
func (lc *LightningChannel) validateCommitmentSanity(theirLogCounter,
|
|
|
|
ourLogCounter uint64, remoteChain bool,
|
2020-02-19 14:27:41 +03:00
|
|
|
predictOurAdd, predictTheirAdd *PaymentDescriptor) error {
|
2019-08-01 06:10:45 +03:00
|
|
|
|
|
|
|
// Fetch all updates not committed.
|
|
|
|
view := lc.fetchHTLCView(theirLogCounter, ourLogCounter)
|
|
|
|
|
|
|
|
// If we are checking if we can add a new HTLC, we add this to the
|
2020-02-15 17:45:25 +03:00
|
|
|
// appropriate update log, in order to validate the sanity of the
|
|
|
|
// commitment resulting from _actually adding_ this HTLC to the state.
|
2020-02-19 14:27:41 +03:00
|
|
|
if predictOurAdd != nil {
|
|
|
|
view.ourUpdates = append(view.ourUpdates, predictOurAdd)
|
|
|
|
}
|
|
|
|
if predictTheirAdd != nil {
|
|
|
|
view.theirUpdates = append(view.theirUpdates, predictTheirAdd)
|
2019-08-01 06:10:45 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
commitChain := lc.localCommitChain
|
|
|
|
if remoteChain {
|
|
|
|
commitChain = lc.remoteCommitChain
|
|
|
|
}
|
|
|
|
ourInitialBalance := commitChain.tip().ourBalance
|
|
|
|
theirInitialBalance := commitChain.tip().theirBalance
|
|
|
|
|
2020-02-12 13:10:19 +03:00
|
|
|
ourBalance, theirBalance, commitWeight, filteredView, err := lc.computeView(
|
2019-08-01 06:10:45 +03:00
|
|
|
view, remoteChain, false,
|
|
|
|
)
|
2020-02-12 13:10:19 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-08-01 06:10:45 +03:00
|
|
|
feePerKw := filteredView.feePerKw
|
|
|
|
|
|
|
|
// Calculate the commitment fee, and subtract it from the initiator's
|
|
|
|
// balance.
|
|
|
|
commitFee := feePerKw.FeeForWeight(commitWeight)
|
|
|
|
commitFeeMsat := lnwire.NewMSatFromSatoshis(commitFee)
|
|
|
|
if lc.channelState.IsInitiator {
|
|
|
|
ourBalance -= commitFeeMsat
|
|
|
|
} else {
|
|
|
|
theirBalance -= commitFeeMsat
|
|
|
|
}
|
|
|
|
|
|
|
|
// As a quick sanity check, we'll ensure that if we interpret the
|
|
|
|
// balances as signed integers, they haven't dipped down below zero. If
|
|
|
|
// they have, then this indicates that a party doesn't have sufficient
|
|
|
|
// balance to satisfy the final evaluated HTLC's.
|
|
|
|
switch {
|
|
|
|
case int64(ourBalance) < 0:
|
|
|
|
return ErrBelowChanReserve
|
|
|
|
case int64(theirBalance) < 0:
|
|
|
|
return ErrBelowChanReserve
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure that the fee being applied is enough to be relayed across the
|
|
|
|
// network in a reasonable time frame.
|
2019-10-31 05:43:05 +03:00
|
|
|
if feePerKw < chainfee.FeePerKwFloor {
|
2019-08-01 06:10:45 +03:00
|
|
|
return fmt.Errorf("commitment fee per kw %v below fee floor %v",
|
2019-10-31 05:43:05 +03:00
|
|
|
feePerKw, chainfee.FeePerKwFloor)
|
2019-08-01 06:10:45 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// If the added HTLCs will decrease the balance, make sure they won't
|
|
|
|
// dip the local and remote balances below the channel reserves.
|
|
|
|
switch {
|
|
|
|
case ourBalance < ourInitialBalance &&
|
|
|
|
ourBalance < lnwire.NewMSatFromSatoshis(
|
2020-01-06 13:42:02 +03:00
|
|
|
lc.channelState.LocalChanCfg.ChanReserve):
|
2019-08-01 06:10:45 +03:00
|
|
|
|
|
|
|
return ErrBelowChanReserve
|
|
|
|
case theirBalance < theirInitialBalance &&
|
|
|
|
theirBalance < lnwire.NewMSatFromSatoshis(
|
2020-01-06 13:42:02 +03:00
|
|
|
lc.channelState.RemoteChanCfg.ChanReserve):
|
2019-08-01 06:10:45 +03:00
|
|
|
|
|
|
|
return ErrBelowChanReserve
|
|
|
|
}
|
|
|
|
|
|
|
|
// validateUpdates take a set of updates, and validates them against
|
|
|
|
// the passed channel constraints.
|
|
|
|
validateUpdates := func(updates []*PaymentDescriptor,
|
|
|
|
constraints *channeldb.ChannelConfig) error {
|
|
|
|
|
|
|
|
// We keep track of the number of HTLCs in flight for the
|
|
|
|
// commitment, and the amount in flight.
|
|
|
|
var numInFlight uint16
|
|
|
|
var amtInFlight lnwire.MilliSatoshi
|
|
|
|
|
|
|
|
// Go through all updates, checking that they don't violate the
|
|
|
|
// channel constraints.
|
|
|
|
for _, entry := range updates {
|
|
|
|
if entry.EntryType == Add {
|
|
|
|
// An HTLC is being added, this will add to the
|
|
|
|
// number and amount in flight.
|
|
|
|
amtInFlight += entry.Amount
|
|
|
|
numInFlight++
|
|
|
|
|
|
|
|
// Check that the value of the HTLC they added
|
|
|
|
// is above our minimum.
|
|
|
|
if entry.Amount < constraints.MinHTLC {
|
|
|
|
return ErrBelowMinHTLC
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that we know the total value of added HTLCs, we check
|
|
|
|
// that this satisfy the MaxPendingAmont contraint.
|
|
|
|
if amtInFlight > constraints.MaxPendingAmount {
|
|
|
|
return ErrMaxPendingAmount
|
|
|
|
}
|
|
|
|
|
|
|
|
// In this step, we verify that the total number of active
|
|
|
|
// HTLCs does not exceed the constraint of the maximum number
|
|
|
|
// of HTLCs in flight.
|
|
|
|
if numInFlight > constraints.MaxAcceptedHtlcs {
|
|
|
|
return ErrMaxHTLCNumber
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// First check that the remote updates won't violate it's channel
|
|
|
|
// constraints.
|
2020-02-12 13:10:19 +03:00
|
|
|
err = validateUpdates(
|
2020-01-06 13:42:02 +03:00
|
|
|
filteredView.theirUpdates, &lc.channelState.RemoteChanCfg,
|
2019-08-01 06:10:45 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Secondly check that our updates won't violate our channel
|
|
|
|
// constraints.
|
|
|
|
err = validateUpdates(
|
2020-01-06 13:42:02 +03:00
|
|
|
filteredView.ourUpdates, &lc.channelState.LocalChanCfg,
|
2019-08-01 06:10:45 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// SignNextCommitment signs a new commitment which includes any previous
|
|
|
|
// unsettled HTLCs, any new HTLCs, and any modifications to prior HTLCs
|
|
|
|
// committed in previous commitment updates. Signing a new commitment
|
|
|
|
// decrements the available revocation window by 1. After a successful method
|
|
|
|
// call, the remote party's commitment chain is extended by a new commitment
|
|
|
|
// which includes all updates to the HTLC log prior to this method invocation.
|
2017-11-10 09:53:18 +03:00
|
|
|
// The first return parameter is the signature for the commitment transaction
|
|
|
|
// itself, while the second parameter is a slice of all HTLC signatures (if
|
|
|
|
// any). The HTLC signatures are sorted according to the BIP 69 order of the
|
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
|
|
|
// HTLC's on the commitment transaction. Finally, the new set of pending HTLCs
|
|
|
|
// for the remote party's commitment are also returned.
|
|
|
|
func (lc *LightningChannel) SignNextCommitment() (lnwire.Sig, []lnwire.Sig, []channeldb.HTLC, error) {
|
|
|
|
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2019-09-24 15:33:59 +03:00
|
|
|
// Check for empty commit sig. This should never happen, but we don't
|
|
|
|
// dare to fail hard here. We assume peers can deal with the empty sig
|
|
|
|
// and continue channel operation. We log an error so that the bug
|
|
|
|
// causing this can be tracked down.
|
|
|
|
if !lc.oweCommitment(true) {
|
|
|
|
lc.log.Errorf("sending empty commit sig")
|
|
|
|
}
|
|
|
|
|
2018-01-31 06:55:39 +03:00
|
|
|
var (
|
|
|
|
sig lnwire.Sig
|
|
|
|
htlcSigs []lnwire.Sig
|
|
|
|
)
|
|
|
|
|
2017-12-11 03:10:44 +03:00
|
|
|
// If we're awaiting for an ACK to a commitment signature, or if we
|
|
|
|
// don't yet have the initial next revocation point of the remote
|
|
|
|
// party, then we're unable to create new states. Each time we create a
|
|
|
|
// new state, we consume a prior revocation point.
|
2017-12-12 02:32:24 +03:00
|
|
|
commitPoint := lc.channelState.RemoteNextRevocation
|
|
|
|
if lc.remoteCommitChain.hasUnackedCommitment() || commitPoint == nil {
|
2017-12-11 03:10:44 +03:00
|
|
|
|
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
|
|
|
return sig, htlcSigs, nil, ErrNoWindow
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
}
|
|
|
|
|
2017-10-19 03:36:28 +03:00
|
|
|
// Determine the last update on the remote log that has been locked in.
|
|
|
|
remoteACKedIndex := lc.localCommitChain.tail().theirMessageIndex
|
2017-11-10 09:56:08 +03:00
|
|
|
remoteHtlcIndex := lc.localCommitChain.tail().theirHtlcIndex
|
2017-10-19 03:36:28 +03:00
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
// Before we extend this new commitment to the remote commitment chain,
|
|
|
|
// ensure that we aren't violating any of the constraints the remote
|
|
|
|
// party set up when we initially set up the channel. If we are, then
|
|
|
|
// we'll abort this state transition.
|
2019-03-09 03:05:28 +03:00
|
|
|
err := lc.validateCommitmentSanity(
|
2020-02-19 14:27:41 +03:00
|
|
|
remoteACKedIndex, lc.localUpdateLog.logIndex, true, nil, nil,
|
2019-03-09 03:05:28 +03:00
|
|
|
)
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
if err != 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
|
|
|
return sig, htlcSigs, nil, err
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2017-09-04 01:38:36 +03:00
|
|
|
// Grab the next commitment point for the remote party. This will be
|
2017-07-30 22:32:24 +03:00
|
|
|
// used within fetchCommitmentView to derive all the keys necessary to
|
|
|
|
// construct the commitment state.
|
2019-09-17 05:06:19 +03:00
|
|
|
keyRing := DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
commitPoint, false, lc.channelState.ChanType,
|
2020-01-06 13:42:02 +03:00
|
|
|
&lc.channelState.LocalChanCfg, &lc.channelState.RemoteChanCfg,
|
2019-03-09 03:05:28 +03:00
|
|
|
)
|
2016-07-06 03:01:55 +03:00
|
|
|
|
|
|
|
// Create a new commitment view which will calculate the evaluated
|
|
|
|
// state of the remote node's new commitment including our latest added
|
2017-01-13 08:01:50 +03:00
|
|
|
// HTLCs. The view includes the latest balances for both sides on the
|
2016-07-06 03:01:55 +03:00
|
|
|
// remote node's chain, and also update the addition height of any new
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
// HTLC log entries. When we creating a new remote view, we include
|
|
|
|
// _all_ of our changes (pending or committed) but only the remote
|
|
|
|
// node's changes up to the last change we've ACK'd.
|
2017-11-10 09:53:18 +03:00
|
|
|
newCommitView, err := lc.fetchCommitmentView(
|
|
|
|
true, lc.localUpdateLog.logIndex, lc.localUpdateLog.htlcCounter,
|
|
|
|
remoteACKedIndex, remoteHtlcIndex, keyRing,
|
|
|
|
)
|
2016-01-06 00:01:42 +03:00
|
|
|
if err != 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
|
|
|
return sig, htlcSigs, nil, err
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Tracef("extending remote chain to height %v, "+
|
2017-11-10 09:53:18 +03:00
|
|
|
"local_log=%v, remote_log=%v",
|
2019-09-24 14:12:53 +03:00
|
|
|
newCommitView.height,
|
2017-11-10 09:53:18 +03:00
|
|
|
lc.localUpdateLog.logIndex, remoteACKedIndex)
|
2017-07-30 22:25:41 +03:00
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Tracef("remote chain: our_balance=%v, "+
|
2017-07-30 22:25:41 +03:00
|
|
|
"their_balance=%v, commit_tx: %v",
|
2019-09-24 14:12:53 +03:00
|
|
|
newCommitView.ourBalance,
|
2017-07-30 22:25:41 +03:00
|
|
|
newCommitView.theirBalance,
|
2016-07-22 02:50:20 +03:00
|
|
|
newLogClosure(func() string {
|
|
|
|
return spew.Sdump(newCommitView.txn)
|
2017-07-30 22:25:41 +03:00
|
|
|
}),
|
|
|
|
)
|
2016-07-13 03:35:51 +03:00
|
|
|
|
2017-07-30 23:00:24 +03:00
|
|
|
// With the commitment view constructed, if there are any HTLC's, we'll
|
|
|
|
// need to generate signatures of each of them for the remote party's
|
|
|
|
// commitment state. We do so in two phases: first we generate and
|
|
|
|
// submit the set of signature jobs to the worker pool.
|
2020-03-06 18:11:45 +03:00
|
|
|
sigBatch, cancelChan, err := genRemoteHtlcSigJobs(
|
|
|
|
keyRing, lc.channelState.ChanType,
|
2020-01-06 13:42:02 +03:00
|
|
|
&lc.channelState.LocalChanCfg, &lc.channelState.RemoteChanCfg,
|
|
|
|
newCommitView,
|
2017-07-30 23:00:24 +03:00
|
|
|
)
|
|
|
|
if err != 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
|
|
|
return sig, htlcSigs, nil, err
|
2017-07-30 23:00:24 +03:00
|
|
|
}
|
|
|
|
lc.sigPool.SubmitSignBatch(sigBatch)
|
|
|
|
|
|
|
|
// While the jobs are being carried out, we'll Sign their version of
|
|
|
|
// the new commitment transaction while we're waiting for the rest of
|
|
|
|
// the HTLC signatures to be processed.
|
2016-08-13 01:50:47 +03:00
|
|
|
lc.signDesc.SigHashes = txscript.NewTxSigHashes(newCommitView.txn)
|
2018-04-30 01:40:59 +03:00
|
|
|
rawSig, err := lc.Signer.SignOutputRaw(newCommitView.txn, lc.signDesc)
|
2016-07-06 03:01:55 +03:00
|
|
|
if err != nil {
|
2017-07-30 23:00:24 +03:00
|
|
|
close(cancelChan)
|
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
|
|
|
return sig, htlcSigs, nil, err
|
2017-07-30 23:00:24 +03:00
|
|
|
}
|
2018-01-31 06:55:39 +03:00
|
|
|
sig, err = lnwire.NewSigFromRawSignature(rawSig)
|
2017-07-30 23:00:24 +03:00
|
|
|
if err != nil {
|
|
|
|
close(cancelChan)
|
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
|
|
|
return sig, htlcSigs, nil, err
|
2017-07-30 23:00:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// We'll need to send over the signatures to the remote party in the
|
|
|
|
// order as they appear on the commitment transaction after BIP 69
|
|
|
|
// sorting.
|
2017-09-04 01:38:36 +03:00
|
|
|
sort.Slice(sigBatch, func(i, j int) bool {
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
return sigBatch[i].OutputIndex < sigBatch[j].OutputIndex
|
2017-09-04 01:38:36 +03:00
|
|
|
})
|
2017-07-30 23:00:24 +03:00
|
|
|
|
|
|
|
// With the jobs sorted, we'll now iterate through all the responses to
|
|
|
|
// gather each of the signatures in order.
|
2018-01-31 06:55:39 +03:00
|
|
|
htlcSigs = make([]lnwire.Sig, 0, len(sigBatch))
|
2017-09-04 01:38:36 +03:00
|
|
|
for _, htlcSigJob := range sigBatch {
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
jobResp := <-htlcSigJob.Resp
|
2017-07-30 23:00:24 +03:00
|
|
|
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
// If an error occurred, then we'll cancel any other active
|
|
|
|
// jobs.
|
|
|
|
if jobResp.Err != nil {
|
|
|
|
close(cancelChan)
|
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
|
|
|
return sig, htlcSigs, nil, err
|
2017-07-30 23:00:24 +03:00
|
|
|
}
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
|
|
|
|
htlcSigs = append(htlcSigs, jobResp.Sig)
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2017-11-10 09:56:08 +03:00
|
|
|
// As we're about to proposer a new commitment state for the remote
|
|
|
|
// party, we'll write this pending state to disk before we exit, so we
|
|
|
|
// can retransmit it if necessary.
|
|
|
|
commitDiff, err := lc.createCommitDiff(newCommitView, sig, htlcSigs)
|
2017-08-14 12:14:04 +03:00
|
|
|
if err != 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
|
|
|
return sig, htlcSigs, nil, err
|
2017-08-14 12:14:04 +03:00
|
|
|
}
|
2019-03-09 03:05:57 +03:00
|
|
|
err = lc.channelState.AppendRemoteCommitChain(commitDiff)
|
|
|
|
if err != 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
|
|
|
return sig, htlcSigs, nil, err
|
2017-08-15 20:09:16 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:56:08 +03:00
|
|
|
// TODO(roasbeef): check that one eclair bug
|
|
|
|
// * need to retransmit on first state still?
|
|
|
|
// * after initial reconnect
|
|
|
|
|
|
|
|
// Extend the remote commitment chain by one with the addition of our
|
|
|
|
// latest commitment update.
|
|
|
|
lc.remoteCommitChain.addCommitment(newCommitView)
|
2017-08-14 12:14:04 +03:00
|
|
|
|
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
|
|
|
return sig, htlcSigs, commitDiff.Commitment.Htlcs, nil
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2017-11-10 09:59:14 +03:00
|
|
|
// ProcessChanSyncMsg processes a ChannelReestablish message sent by the remote
|
|
|
|
// connection upon re establishment of our connection with them. This method
|
|
|
|
// will return a single message if we are currently out of sync, otherwise a
|
|
|
|
// nil lnwire.Message will be returned. If it is decided that our level of
|
|
|
|
// de-synchronization is irreconcilable, then an error indicating the issue
|
|
|
|
// will be returned. In this case that an error is returned, the channel should
|
|
|
|
// be force closed, as we cannot continue updates.
|
|
|
|
//
|
|
|
|
// One of two message sets will be returned:
|
|
|
|
//
|
|
|
|
// * CommitSig+Updates: if we have a pending remote commit which they claim to
|
|
|
|
// have not received
|
|
|
|
// * RevokeAndAck: if we sent a revocation message that they claim to have
|
|
|
|
// not received
|
2018-02-28 07:04:41 +03:00
|
|
|
//
|
|
|
|
// If we detect a scenario where we need to send a CommitSig+Updates, this
|
|
|
|
// method also returns two sets channeldb.CircuitKeys identifying the circuits
|
|
|
|
// that were opened and closed, respectively, as a result of signing the
|
|
|
|
// previous commitment txn. This allows the link to clear its mailbox of those
|
|
|
|
// circuits in case they are still in memory, and ensure the switch's circuit
|
|
|
|
// map has been updated by deleting the closed circuits.
|
2018-02-28 07:01:41 +03:00
|
|
|
func (lc *LightningChannel) ProcessChanSyncMsg(
|
2018-02-28 07:04:41 +03:00
|
|
|
msg *lnwire.ChannelReestablish) ([]lnwire.Message, []channeldb.CircuitKey,
|
|
|
|
[]channeldb.CircuitKey, error) {
|
2017-11-10 09:59:14 +03:00
|
|
|
|
|
|
|
// Now we'll examine the state we have, vs what was contained in the
|
|
|
|
// chain sync message. If we're de-synchronized, then we'll send a
|
|
|
|
// batch of messages which when applied will kick start the chain
|
|
|
|
// resync.
|
2018-02-28 07:01:41 +03:00
|
|
|
var (
|
2018-02-28 07:04:41 +03:00
|
|
|
updates []lnwire.Message
|
|
|
|
openedCircuits []channeldb.CircuitKey
|
|
|
|
closedCircuits []channeldb.CircuitKey
|
2018-02-28 07:01:41 +03:00
|
|
|
)
|
2017-07-09 02:30:20 +03:00
|
|
|
|
2017-11-14 09:45:57 +03:00
|
|
|
// If the remote party included the optional fields, then we'll verify
|
|
|
|
// their correctness first, as it will influence our decisions below.
|
|
|
|
hasRecoveryOptions := msg.LocalUnrevokedCommitPoint != nil
|
|
|
|
if hasRecoveryOptions && msg.RemoteCommitTailHeight != 0 {
|
|
|
|
// We'll check that they've really sent a valid commit
|
|
|
|
// secret from our shachain for our prior height, but only if
|
|
|
|
// this isn't the first state.
|
|
|
|
heightSecret, err := lc.channelState.RevocationProducer.AtIndex(
|
|
|
|
msg.RemoteCommitTailHeight - 1,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2018-02-28 07:04:41 +03:00
|
|
|
return nil, nil, nil, err
|
2017-11-14 09:45:57 +03:00
|
|
|
}
|
2018-07-12 12:02:52 +03:00
|
|
|
commitSecretCorrect := bytes.Equal(
|
2017-11-14 09:45:57 +03:00
|
|
|
heightSecret[:], msg.LastRemoteCommitSecret[:],
|
|
|
|
)
|
2018-07-12 12:02:52 +03:00
|
|
|
|
|
|
|
// If the commit secret they sent is incorrect then we'll fail
|
|
|
|
// the channel as the remote node has an inconsistent state.
|
|
|
|
if !commitSecretCorrect {
|
|
|
|
// In this case, we'll return an error to indicate the
|
|
|
|
// remote node sent us the wrong values. This will let
|
|
|
|
// the caller act accordingly.
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: remote provided invalid " +
|
|
|
|
"commit secret!")
|
2018-07-12 12:02:52 +03:00
|
|
|
return nil, nil, nil, ErrInvalidLastCommitSecret
|
|
|
|
}
|
2017-11-14 09:45:57 +03:00
|
|
|
}
|
|
|
|
|
2019-03-11 02:38:45 +03:00
|
|
|
// If we detect that this is is a restored channel, then we can skip a
|
|
|
|
// portion of the verification, as we already know that we're unable to
|
|
|
|
// proceed with any updates.
|
|
|
|
isRestoredChan := lc.channelState.HasChanStatus(
|
|
|
|
channeldb.ChanStatusRestored,
|
|
|
|
)
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
// Take note of our current commit chain heights before we begin adding
|
|
|
|
// more to them.
|
|
|
|
var (
|
|
|
|
localTailHeight = lc.localCommitChain.tail().height
|
2018-07-12 12:02:53 +03:00
|
|
|
remoteTailHeight = lc.remoteCommitChain.tail().height
|
|
|
|
remoteTipHeight = lc.remoteCommitChain.tip().height
|
2018-07-12 12:02:53 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// We'll now check that their view of our local chain is up-to-date.
|
|
|
|
// This means checking that what their view of our local chain tail
|
|
|
|
// height is what they believe. Note that the tail and tip height will
|
|
|
|
// always be the same for the local chain at this stage, as we won't
|
|
|
|
// store any received commitment to disk before it is ACKed.
|
2017-11-14 09:45:57 +03:00
|
|
|
switch {
|
2018-07-12 12:02:53 +03:00
|
|
|
|
|
|
|
// If their reported height for our local chain tail is ahead of our
|
|
|
|
// view, then we're behind!
|
2019-03-11 02:38:45 +03:00
|
|
|
case msg.RemoteCommitTailHeight > localTailHeight || isRestoredChan:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed with local data loss: remote "+
|
|
|
|
"believes our tail height is %v, while we have %v!",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.RemoteCommitTailHeight, localTailHeight)
|
|
|
|
|
2019-03-11 02:38:45 +03:00
|
|
|
if isRestoredChan {
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Warnf("detected restored triggering DLP")
|
2019-03-11 02:38:45 +03:00
|
|
|
}
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
// We must check that we had recovery options to ensure the
|
|
|
|
// commitment secret matched up, and the remote is just not
|
|
|
|
// lying about its height.
|
|
|
|
if !hasRecoveryOptions {
|
|
|
|
// At this point we the remote is either lying about
|
|
|
|
// its height, or we are actually behind but the remote
|
|
|
|
// doesn't support data loss protection. In either case
|
|
|
|
// it is not safe for us to keep using the channel, so
|
|
|
|
// we mark it borked and fail the channel.
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: local data loss, but no " +
|
|
|
|
"recovery option.")
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
return nil, nil, nil, ErrCannotSyncCommitChains
|
|
|
|
}
|
|
|
|
|
|
|
|
// In this case, we've likely lost data and shouldn't proceed
|
2019-09-06 14:14:40 +03:00
|
|
|
// with channel updates.
|
2019-09-06 14:14:39 +03:00
|
|
|
return nil, nil, nil, &ErrCommitSyncLocalDataLoss{
|
|
|
|
ChannelPoint: lc.channelState.FundingOutpoint,
|
|
|
|
CommitPoint: msg.LocalUnrevokedCommitPoint,
|
|
|
|
}
|
2018-07-12 12:02:53 +03:00
|
|
|
|
|
|
|
// If the height of our commitment chain reported by the remote party
|
|
|
|
// is behind our view of the chain, then they probably lost some state,
|
|
|
|
// and we'll force close the channel.
|
|
|
|
case msg.RemoteCommitTailHeight+1 < localTailHeight:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: remote believes our tail height is "+
|
|
|
|
"%v, while we have %v!",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.RemoteCommitTailHeight, localTailHeight)
|
|
|
|
return nil, nil, nil, ErrCommitSyncRemoteDataLoss
|
|
|
|
|
|
|
|
// Their view of our commit chain is consistent with our view.
|
|
|
|
case msg.RemoteCommitTailHeight == localTailHeight:
|
|
|
|
// In sync, don't have to do anything.
|
|
|
|
|
|
|
|
// We owe them a revocation if the tail of our current commitment chain
|
|
|
|
// is one greater than what they _think_ our commitment tail is. In
|
|
|
|
// this case we'll re-send the last revocation message that we sent.
|
|
|
|
// This will be the revocation message for our prior chain tail.
|
|
|
|
case msg.RemoteCommitTailHeight+1 == localTailHeight:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Debugf("sync: remote believes our tail height is %v, "+
|
|
|
|
"while we have %v, we owe them a revocation",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.RemoteCommitTailHeight, localTailHeight)
|
|
|
|
|
2017-11-10 09:59:14 +03:00
|
|
|
revocationMsg, err := lc.generateRevocation(
|
2018-07-12 12:02:53 +03:00
|
|
|
localTailHeight - 1,
|
2017-11-10 09:59:14 +03:00
|
|
|
)
|
2017-07-09 02:30:20 +03:00
|
|
|
if err != nil {
|
2018-02-28 07:04:41 +03:00
|
|
|
return nil, nil, nil, err
|
2017-07-09 02:30:20 +03:00
|
|
|
}
|
|
|
|
updates = append(updates, revocationMsg)
|
|
|
|
|
2017-11-10 09:59:14 +03:00
|
|
|
// Next, as a precaution, we'll check a special edge case. If
|
|
|
|
// they initiated a state transition, we sent the revocation,
|
|
|
|
// but died before the signature was sent. We re-transmit our
|
|
|
|
// revocation, but also initiate a state transition to re-sync
|
|
|
|
// them.
|
2019-09-23 15:27:06 +03:00
|
|
|
if lc.OweCommitment(true) {
|
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
|
|
|
commitSig, htlcSigs, _, err := lc.SignNextCommitment()
|
2017-12-12 02:42:00 +03:00
|
|
|
switch {
|
|
|
|
|
|
|
|
// If we signed this state, then we'll accumulate
|
|
|
|
// another update to send over.
|
|
|
|
case err == nil:
|
|
|
|
updates = append(updates, &lnwire.CommitSig{
|
|
|
|
ChanID: lnwire.NewChanIDFromOutPoint(
|
|
|
|
&lc.channelState.FundingOutpoint,
|
|
|
|
),
|
|
|
|
CommitSig: commitSig,
|
|
|
|
HtlcSigs: htlcSigs,
|
|
|
|
})
|
|
|
|
|
|
|
|
// If we get a failure due to not knowing their next
|
|
|
|
// point, then this is fine as they'll either send
|
|
|
|
// FundingLocked, or revoke their next state to allow
|
|
|
|
// us to continue forwards.
|
|
|
|
case err == ErrNoWindow:
|
|
|
|
|
|
|
|
// Otherwise, this is an error and we'll treat it as
|
|
|
|
// such.
|
|
|
|
default:
|
2018-02-28 07:04:41 +03:00
|
|
|
return nil, nil, nil, err
|
2017-11-10 09:59:14 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
// There should be no other possible states.
|
|
|
|
default:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: remote believes our tail height is "+
|
|
|
|
"%v, while we have %v!",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.RemoteCommitTailHeight, localTailHeight)
|
2018-02-28 07:04:41 +03:00
|
|
|
return nil, nil, nil, ErrCannotSyncCommitChains
|
2017-11-10 09:59:14 +03:00
|
|
|
}
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
// Now check if our view of the remote chain is consistent with what
|
|
|
|
// they tell us.
|
|
|
|
switch {
|
|
|
|
|
|
|
|
// The remote's view of what their next commit height is 2+ states
|
|
|
|
// ahead of us, we most likely lost data, or the remote is trying to
|
|
|
|
// trick us. Since we have no way of verifying whether they are lying
|
|
|
|
// or not, we will fail the channel, but should not force close it
|
|
|
|
// automatically.
|
|
|
|
case msg.NextLocalCommitHeight > remoteTipHeight+1:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: remote's next commit height is %v, "+
|
|
|
|
"while we believe it is %v!",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.NextLocalCommitHeight, remoteTipHeight)
|
|
|
|
|
|
|
|
return nil, nil, nil, ErrCannotSyncCommitChains
|
|
|
|
|
|
|
|
// They are waiting for a state they have already ACKed.
|
|
|
|
case msg.NextLocalCommitHeight <= remoteTailHeight:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: remote's next commit height is %v, "+
|
|
|
|
"while we believe it is %v!",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.NextLocalCommitHeight, remoteTipHeight)
|
|
|
|
|
|
|
|
// They previously ACKed our current tail, and now they are
|
|
|
|
// waiting for it. They probably lost state.
|
|
|
|
return nil, nil, nil, ErrCommitSyncRemoteDataLoss
|
|
|
|
|
|
|
|
// They have received our latest commitment, life is good.
|
|
|
|
case msg.NextLocalCommitHeight == remoteTipHeight+1:
|
|
|
|
|
|
|
|
// We owe them a commitment if the tip of their chain (from our Pov) is
|
|
|
|
// equal to what they think their next commit height should be. We'll
|
2018-09-06 11:48:46 +03:00
|
|
|
// re-send all the updates necessary to recreate this state, along
|
2018-07-12 12:02:53 +03:00
|
|
|
// with the commit sig.
|
|
|
|
case msg.NextLocalCommitHeight == remoteTipHeight:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Debugf("sync: remote's next commit height is %v, while "+
|
|
|
|
"we believe it is %v, we owe them a commitment",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.NextLocalCommitHeight, remoteTipHeight)
|
|
|
|
|
|
|
|
// Grab the current remote chain tip from the database. This
|
2017-11-10 09:59:14 +03:00
|
|
|
// commit diff contains all the information required to re-sync
|
|
|
|
// our states.
|
|
|
|
commitDiff, err := lc.channelState.RemoteCommitChainTip()
|
2017-07-09 02:30:20 +03:00
|
|
|
if err != nil {
|
2018-02-28 07:04:41 +03:00
|
|
|
return nil, nil, nil, err
|
2017-07-09 02:30:20 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:59:14 +03:00
|
|
|
// Next, we'll need to send over any updates we sent as part of
|
|
|
|
// this new proposed commitment state.
|
|
|
|
for _, logUpdate := range commitDiff.LogUpdates {
|
|
|
|
updates = append(updates, logUpdate.UpdateMsg)
|
2017-07-09 02:30:20 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 09:59:14 +03:00
|
|
|
// With the batch of updates accumulated, we'll now re-send the
|
|
|
|
// original CommitSig message required to re-sync their remote
|
|
|
|
// commitment chain with our local version of their chain.
|
|
|
|
updates = append(updates, commitDiff.CommitSig)
|
|
|
|
|
2018-02-28 07:04:41 +03:00
|
|
|
openedCircuits = commitDiff.OpenedCircuitKeys
|
|
|
|
closedCircuits = commitDiff.ClosedCircuitKeys
|
2017-11-10 09:59:14 +03:00
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
// There should be no other possible states as long as the commit chain
|
|
|
|
// can have at most two elements. If that's the case, something is
|
|
|
|
// wrong.
|
|
|
|
default:
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: remote's next commit height is %v, "+
|
|
|
|
"while we believe it is %v!",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.NextLocalCommitHeight, remoteTipHeight)
|
2018-02-28 07:04:41 +03:00
|
|
|
return nil, nil, nil, ErrCannotSyncCommitChains
|
2017-07-09 02:30:20 +03:00
|
|
|
}
|
|
|
|
|
2018-07-12 12:02:53 +03:00
|
|
|
// If we didn't have recovery options, then the final check cannot be
|
|
|
|
// performed, and we'll return early.
|
|
|
|
if !hasRecoveryOptions {
|
|
|
|
return updates, openedCircuits, closedCircuits, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// At this point we have determined that either the commit heights are
|
|
|
|
// in sync, or that we are in a state we can recover from. As a final
|
|
|
|
// check, we ensure that the commitment point sent to us by the remote
|
|
|
|
// is valid.
|
|
|
|
var commitPoint *btcec.PublicKey
|
|
|
|
switch {
|
2019-03-11 02:39:31 +03:00
|
|
|
// If their height is one beyond what we know their current height to
|
|
|
|
// be, then we need to compare their current unrevoked commitment point
|
|
|
|
// as that's what they should send.
|
2018-07-12 12:02:53 +03:00
|
|
|
case msg.NextLocalCommitHeight == remoteTailHeight+1:
|
|
|
|
commitPoint = lc.channelState.RemoteCurrentRevocation
|
2019-03-11 02:43:25 +03:00
|
|
|
|
|
|
|
// Alternatively, if their height is two beyond what we know their best
|
|
|
|
// height to be, then they're holding onto two commitments, and the
|
2019-03-11 03:05:00 +03:00
|
|
|
// highest unrevoked point is their next revocation.
|
2019-03-11 02:43:25 +03:00
|
|
|
//
|
|
|
|
// TODO(roasbeef): verify this in the spec...
|
|
|
|
case msg.NextLocalCommitHeight == remoteTailHeight+2:
|
|
|
|
commitPoint = lc.channelState.RemoteNextRevocation
|
2018-07-12 12:02:53 +03:00
|
|
|
}
|
2019-03-11 02:43:25 +03:00
|
|
|
|
2019-08-01 06:10:45 +03:00
|
|
|
// Only if this is a tweakless channel will we attempt to verify the
|
|
|
|
// commitment point, as otherwise it has no validity requirements.
|
|
|
|
tweakless := lc.channelState.ChanType.IsTweakless()
|
|
|
|
if !tweakless && commitPoint != nil &&
|
2018-07-12 12:02:53 +03:00
|
|
|
!commitPoint.IsEqual(msg.LocalUnrevokedCommitPoint) {
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Errorf("sync failed: remote sent invalid commit point "+
|
|
|
|
"for height %v!",
|
2018-07-12 12:02:53 +03:00
|
|
|
msg.NextLocalCommitHeight)
|
|
|
|
return nil, nil, nil, ErrInvalidLocalUnrevokedCommitPoint
|
|
|
|
}
|
|
|
|
|
2018-02-28 07:04:41 +03:00
|
|
|
return updates, openedCircuits, closedCircuits, nil
|
2017-07-09 02:30:20 +03:00
|
|
|
}
|
|
|
|
|
2018-02-25 06:16:49 +03:00
|
|
|
// computeView takes the given htlcView, and calculates the balances, filtered
|
|
|
|
// view (settling unsettled HTLCs), commitment weight and feePerKw, after
|
2018-02-25 06:19:46 +03:00
|
|
|
// applying the HTLCs to the latest commitment. The returned balances are the
|
2018-02-25 06:16:49 +03:00
|
|
|
// balances *before* subtracting the commitment fee from the initiator's
|
|
|
|
// balance.
|
2018-01-09 18:42:07 +03:00
|
|
|
//
|
2018-02-25 06:16:49 +03:00
|
|
|
// If the updateState boolean is set true, the add and remove heights of the
|
|
|
|
// HTLCs will be set to the next commitment height.
|
2018-01-09 18:42:07 +03:00
|
|
|
func (lc *LightningChannel) computeView(view *htlcView, remoteChain bool,
|
|
|
|
updateState bool) (lnwire.MilliSatoshi, lnwire.MilliSatoshi, int64,
|
2020-02-12 13:10:19 +03:00
|
|
|
*htlcView, error) {
|
2018-01-09 18:42:07 +03:00
|
|
|
|
|
|
|
commitChain := lc.localCommitChain
|
2020-01-06 13:42:02 +03:00
|
|
|
dustLimit := lc.channelState.LocalChanCfg.DustLimit
|
2018-01-09 18:42:07 +03:00
|
|
|
if remoteChain {
|
|
|
|
commitChain = lc.remoteCommitChain
|
2020-01-06 13:42:02 +03:00
|
|
|
dustLimit = lc.channelState.RemoteChanCfg.DustLimit
|
2018-01-09 18:42:07 +03:00
|
|
|
}
|
|
|
|
|
2018-02-25 06:16:49 +03:00
|
|
|
// Since the fetched htlc view will include all updates added after the
|
|
|
|
// last committed state, we start with the balances reflecting that
|
|
|
|
// state.
|
2018-01-09 18:42:07 +03:00
|
|
|
ourBalance := commitChain.tip().ourBalance
|
|
|
|
theirBalance := commitChain.tip().theirBalance
|
|
|
|
|
|
|
|
// Add the fee from the previous commitment state back to the
|
|
|
|
// initiator's balance, so that the fee can be recalculated and
|
2018-02-25 06:16:49 +03:00
|
|
|
// re-applied in case fee estimation parameters have changed or the
|
|
|
|
// number of outstanding HTLCs has changed.
|
2018-01-09 18:42:07 +03:00
|
|
|
if lc.channelState.IsInitiator {
|
|
|
|
ourBalance += lnwire.NewMSatFromSatoshis(
|
|
|
|
commitChain.tip().fee)
|
|
|
|
} else if !lc.channelState.IsInitiator {
|
|
|
|
theirBalance += lnwire.NewMSatFromSatoshis(
|
|
|
|
commitChain.tip().fee)
|
|
|
|
}
|
|
|
|
nextHeight := commitChain.tip().height + 1
|
|
|
|
|
2019-01-10 14:23:57 +03:00
|
|
|
// Initiate feePerKw to the last committed fee for this chain as we'll
|
|
|
|
// need this to determine which HTLCs are dust, and also the final fee
|
|
|
|
// rate.
|
|
|
|
view.feePerKw = commitChain.tip().feePerKw
|
|
|
|
|
2018-02-25 06:16:49 +03:00
|
|
|
// We evaluate the view at this stage, meaning settled and failed HTLCs
|
|
|
|
// will remove their corresponding added HTLCs. The resulting filtered
|
|
|
|
// view will only have Add entries left, making it easy to compare the
|
2019-01-10 14:23:57 +03:00
|
|
|
// channel constraints to the final commitment state. If any fee
|
2019-03-11 02:42:12 +03:00
|
|
|
// updates are found in the logs, the commitment fee rate should be
|
2019-01-10 14:23:57 +03:00
|
|
|
// changed, so we'll also set the feePerKw to this new value.
|
2020-02-12 13:10:19 +03:00
|
|
|
filteredHTLCView, err := lc.evaluateHTLCView(view, &ourBalance,
|
2018-01-09 18:42:07 +03:00
|
|
|
&theirBalance, nextHeight, remoteChain, updateState)
|
2020-02-12 13:10:19 +03:00
|
|
|
if err != nil {
|
|
|
|
return 0, 0, 0, nil, err
|
|
|
|
}
|
2019-01-10 14:23:57 +03:00
|
|
|
feePerKw := filteredHTLCView.feePerKw
|
2018-01-09 18:42:07 +03:00
|
|
|
|
|
|
|
// Now go through all HTLCs at this stage, to calculate the total
|
|
|
|
// weight, needed to calculate the transaction fee.
|
|
|
|
var totalHtlcWeight int64
|
|
|
|
for _, htlc := range filteredHTLCView.ourUpdates {
|
2020-03-06 18:11:49 +03:00
|
|
|
if htlcIsDust(
|
|
|
|
lc.channelState.ChanType, remoteChain, !remoteChain,
|
|
|
|
feePerKw, htlc.Amount.ToSatoshis(), dustLimit,
|
|
|
|
) {
|
2018-01-09 18:42:07 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-01-06 13:42:04 +03:00
|
|
|
totalHtlcWeight += input.HTLCWeight
|
2018-01-09 18:42:07 +03:00
|
|
|
}
|
|
|
|
for _, htlc := range filteredHTLCView.theirUpdates {
|
2020-03-06 18:11:49 +03:00
|
|
|
if htlcIsDust(
|
|
|
|
lc.channelState.ChanType, !remoteChain, !remoteChain,
|
|
|
|
feePerKw, htlc.Amount.ToSatoshis(), dustLimit,
|
|
|
|
) {
|
2018-01-09 18:42:07 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-01-06 13:42:04 +03:00
|
|
|
totalHtlcWeight += input.HTLCWeight
|
2018-01-09 18:42:07 +03:00
|
|
|
}
|
|
|
|
|
2020-03-06 18:11:46 +03:00
|
|
|
totalCommitWeight := CommitWeight(lc.channelState.ChanType) +
|
|
|
|
totalHtlcWeight
|
2020-02-12 13:10:19 +03:00
|
|
|
return ourBalance, theirBalance, totalCommitWeight, filteredHTLCView, nil
|
2018-01-09 18:42:07 +03:00
|
|
|
}
|
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
// genHtlcSigValidationJobs generates a series of signatures verification jobs
|
|
|
|
// meant to verify all the signatures for HTLC's attached to a newly created
|
|
|
|
// commitment state. The jobs generated are fully populated, and can be sent
|
|
|
|
// directly into the pool of workers.
|
|
|
|
func genHtlcSigValidationJobs(localCommitmentView *commitment,
|
2018-01-31 06:55:39 +03:00
|
|
|
keyRing *CommitmentKeyRing, htlcSigs []lnwire.Sig,
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType channeldb.ChannelType,
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
localChanCfg, remoteChanCfg *channeldb.ChannelConfig) ([]VerifyJob, error) {
|
2017-07-30 22:55:27 +03:00
|
|
|
|
|
|
|
txHash := localCommitmentView.txn.TxHash()
|
|
|
|
feePerKw := localCommitmentView.feePerKw
|
2020-03-06 18:11:47 +03:00
|
|
|
sigHashType := HtlcSigHashType(chanType)
|
2017-07-30 22:55:27 +03:00
|
|
|
|
|
|
|
// With the required state generated, we'll create a slice with large
|
|
|
|
// enough capacity to hold verification jobs for all HTLC's in this
|
|
|
|
// view. In the case that we have some dust outputs, then the actual
|
|
|
|
// length will be smaller than the total capacity.
|
|
|
|
numHtlcs := (len(localCommitmentView.incomingHTLCs) +
|
|
|
|
len(localCommitmentView.outgoingHTLCs))
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
verifyJobs := make([]VerifyJob, 0, numHtlcs)
|
2017-07-30 22:55:27 +03:00
|
|
|
|
|
|
|
// We'll iterate through each output in the commitment transaction,
|
|
|
|
// populating the sigHash closure function if it's detected to be an
|
|
|
|
// HLTC output. Given the sighash, and the signing key, we'll be able
|
|
|
|
// to validate each signature within the worker pool.
|
|
|
|
i := 0
|
2017-07-31 04:22:38 +03:00
|
|
|
for index := range localCommitmentView.txn.TxOut {
|
2018-01-31 06:55:39 +03:00
|
|
|
var (
|
2018-04-05 03:41:05 +03:00
|
|
|
htlcIndex uint64
|
|
|
|
sigHash func() ([]byte, error)
|
|
|
|
sig *btcec.Signature
|
|
|
|
err error
|
2018-01-31 06:55:39 +03:00
|
|
|
)
|
2017-07-30 22:55:27 +03:00
|
|
|
|
|
|
|
outputIndex := int32(index)
|
|
|
|
switch {
|
|
|
|
|
2018-04-05 03:41:05 +03:00
|
|
|
// If this output index is found within the incoming HTLC
|
|
|
|
// index, then this means that we need to generate an HTLC
|
|
|
|
// success transaction in order to validate the signature.
|
2017-07-30 22:55:27 +03:00
|
|
|
case localCommitmentView.incomingHTLCIndex[outputIndex] != nil:
|
|
|
|
htlc := localCommitmentView.incomingHTLCIndex[outputIndex]
|
|
|
|
|
2018-04-05 03:41:05 +03:00
|
|
|
htlcIndex = htlc.HtlcIndex
|
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
sigHash = func() ([]byte, error) {
|
|
|
|
op := wire.OutPoint{
|
|
|
|
Hash: txHash,
|
|
|
|
Index: uint32(htlc.localOutputIndex),
|
|
|
|
}
|
|
|
|
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee := HtlcSuccessFee(chanType, feePerKw)
|
2017-08-22 09:20:29 +03:00
|
|
|
outputAmt := htlc.Amount.ToSatoshis() - htlcFee
|
2017-07-30 22:55:27 +03:00
|
|
|
|
2020-03-06 18:11:45 +03:00
|
|
|
successTx, err := createHtlcSuccessTx(
|
|
|
|
chanType, op, outputAmt,
|
|
|
|
uint32(localChanCfg.CsvDelay),
|
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey,
|
|
|
|
)
|
2017-07-30 22:55:27 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
hashCache := txscript.NewTxSigHashes(successTx)
|
|
|
|
sigHash, err := txscript.CalcWitnessSigHash(
|
|
|
|
htlc.ourWitnessScript, hashCache,
|
2020-03-06 18:11:47 +03:00
|
|
|
sigHashType, successTx, 0,
|
2017-08-22 09:20:29 +03:00
|
|
|
int64(htlc.Amount.ToSatoshis()),
|
|
|
|
)
|
2017-07-30 22:55:27 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return sigHash, nil
|
|
|
|
}
|
|
|
|
|
2018-03-22 14:52:12 +03:00
|
|
|
// Make sure there are more signatures left.
|
|
|
|
if i >= len(htlcSigs) {
|
|
|
|
return nil, fmt.Errorf("not enough HTLC " +
|
|
|
|
"signatures.")
|
|
|
|
}
|
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
// With the sighash generated, we'll also store the
|
|
|
|
// signature so it can be written to disk if this state
|
|
|
|
// is valid.
|
2018-01-31 06:55:39 +03:00
|
|
|
sig, err = htlcSigs[i].ToSignature()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
htlc.sig = sig
|
2017-07-30 22:55:27 +03:00
|
|
|
|
|
|
|
// Otherwise, if this is an outgoing HTLC, then we'll need to
|
|
|
|
// generate a timeout transaction so we can verify the
|
|
|
|
// signature presented.
|
2017-09-25 21:25:58 +03:00
|
|
|
case localCommitmentView.outgoingHTLCIndex[outputIndex] != nil:
|
|
|
|
htlc := localCommitmentView.outgoingHTLCIndex[outputIndex]
|
2017-07-30 22:55:27 +03:00
|
|
|
|
2018-04-05 03:41:05 +03:00
|
|
|
htlcIndex = htlc.HtlcIndex
|
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
sigHash = func() ([]byte, error) {
|
|
|
|
op := wire.OutPoint{
|
|
|
|
Hash: txHash,
|
|
|
|
Index: uint32(htlc.localOutputIndex),
|
|
|
|
}
|
|
|
|
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee := HtlcTimeoutFee(chanType, feePerKw)
|
2017-08-22 09:20:29 +03:00
|
|
|
outputAmt := htlc.Amount.ToSatoshis() - htlcFee
|
2017-07-30 22:55:27 +03:00
|
|
|
|
2020-03-06 18:11:45 +03:00
|
|
|
timeoutTx, err := createHtlcTimeoutTx(
|
|
|
|
chanType, op, outputAmt, htlc.Timeout,
|
2017-07-30 22:55:27 +03:00
|
|
|
uint32(localChanCfg.CsvDelay),
|
2020-01-06 13:42:04 +03:00
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey,
|
2017-07-30 22:55:27 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
hashCache := txscript.NewTxSigHashes(timeoutTx)
|
|
|
|
sigHash, err := txscript.CalcWitnessSigHash(
|
|
|
|
htlc.ourWitnessScript, hashCache,
|
2020-03-06 18:11:47 +03:00
|
|
|
sigHashType, timeoutTx, 0,
|
2017-08-22 09:20:29 +03:00
|
|
|
int64(htlc.Amount.ToSatoshis()),
|
2017-07-30 22:55:27 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return sigHash, nil
|
|
|
|
}
|
|
|
|
|
2018-03-22 14:52:12 +03:00
|
|
|
// Make sure there are more signatures left.
|
|
|
|
if i >= len(htlcSigs) {
|
|
|
|
return nil, fmt.Errorf("not enough HTLC " +
|
|
|
|
"signatures.")
|
|
|
|
}
|
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
// With the sighash generated, we'll also store the
|
|
|
|
// signature so it can be written to disk if this state
|
|
|
|
// is valid.
|
2018-01-31 06:55:39 +03:00
|
|
|
sig, err = htlcSigs[i].ToSignature()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
htlc.sig = sig
|
2017-07-30 22:55:27 +03:00
|
|
|
|
|
|
|
default:
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
verifyJobs = append(verifyJobs, VerifyJob{
|
|
|
|
HtlcIndex: htlcIndex,
|
|
|
|
PubKey: keyRing.RemoteHtlcKey,
|
|
|
|
Sig: sig,
|
|
|
|
SigHash: sigHash,
|
2017-07-30 22:55:27 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
2018-03-22 15:23:23 +03:00
|
|
|
// If we received a number of HTLC signatures that doesn't match our
|
|
|
|
// commitment, we'll return an error now.
|
|
|
|
if len(htlcSigs) != i {
|
|
|
|
return nil, fmt.Errorf("number of htlc sig mismatch. "+
|
|
|
|
"Expected %v sigs, got %v", i, len(htlcSigs))
|
|
|
|
}
|
|
|
|
|
2018-01-31 06:55:39 +03:00
|
|
|
return verifyJobs, nil
|
2017-07-30 22:55:27 +03:00
|
|
|
}
|
|
|
|
|
2018-01-09 05:50:24 +03:00
|
|
|
// InvalidCommitSigError is a struct that implements the error interface to
|
2018-04-05 03:41:05 +03:00
|
|
|
// report a failure to validate a commitment signature for a remote peer.
|
2018-01-09 05:50:24 +03:00
|
|
|
// We'll use the items in this struct to generate a rich error message for the
|
|
|
|
// remote peer when we receive an invalid signature from it. Doing so can
|
|
|
|
// greatly aide in debugging cross implementation issues.
|
|
|
|
type InvalidCommitSigError struct {
|
|
|
|
commitHeight uint64
|
|
|
|
|
|
|
|
commitSig []byte
|
|
|
|
|
|
|
|
sigHash []byte
|
|
|
|
|
|
|
|
commitTx []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error returns a detailed error string including the exact transaction that
|
|
|
|
// caused an invalid commitment signature.
|
|
|
|
func (i *InvalidCommitSigError) Error() string {
|
|
|
|
return fmt.Sprintf("rejected commitment: commit_height=%v, "+
|
2018-04-05 03:41:05 +03:00
|
|
|
"invalid_commit_sig=%x, commit_tx=%x, sig_hash=%x", i.commitHeight,
|
2018-01-09 05:50:24 +03:00
|
|
|
i.commitSig[:], i.commitTx, i.sigHash[:])
|
|
|
|
}
|
|
|
|
|
|
|
|
// A compile time flag to ensure that InvalidCommitSigError implements the
|
|
|
|
// error interface.
|
|
|
|
var _ error = (*InvalidCommitSigError)(nil)
|
|
|
|
|
2018-07-31 11:29:12 +03:00
|
|
|
// InvalidHtlcSigError is a struct that implements the error interface to
|
2018-04-05 03:41:05 +03:00
|
|
|
// report a failure to validate an htlc signature from a remote peer. We'll use
|
|
|
|
// the items in this struct to generate a rich error message for the remote
|
|
|
|
// peer when we receive an invalid signature from it. Doing so can greatly aide
|
|
|
|
// in debugging across implementation issues.
|
|
|
|
type InvalidHtlcSigError struct {
|
|
|
|
commitHeight uint64
|
|
|
|
|
|
|
|
htlcSig []byte
|
|
|
|
|
|
|
|
htlcIndex uint64
|
|
|
|
|
|
|
|
sigHash []byte
|
|
|
|
|
|
|
|
commitTx []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error returns a detailed error string including the exact transaction that
|
|
|
|
// caused an invalid htlc signature.
|
|
|
|
func (i *InvalidHtlcSigError) Error() string {
|
|
|
|
return fmt.Sprintf("rejected commitment: commit_height=%v, "+
|
|
|
|
"invalid_htlc_sig=%x, commit_tx=%x, sig_hash=%x", i.commitHeight,
|
|
|
|
i.htlcSig, i.commitTx, i.sigHash[:])
|
|
|
|
}
|
|
|
|
|
|
|
|
// A compile time flag to ensure that InvalidCommitSigError implements the
|
|
|
|
// error interface.
|
|
|
|
var _ error = (*InvalidCommitSigError)(nil)
|
|
|
|
|
2016-11-23 11:36:55 +03:00
|
|
|
// ReceiveNewCommitment process a signature for a new commitment state sent by
|
2017-10-19 03:36:28 +03:00
|
|
|
// the remote party. This method should be called in response to the
|
2016-07-06 03:01:55 +03:00
|
|
|
// remote party initiating a new change, or when the remote party sends a
|
|
|
|
// signature fully accepting a new state we've initiated. If we are able to
|
2016-10-26 15:25:42 +03:00
|
|
|
// successfully validate the signature, then the generated commitment is added
|
2016-07-06 03:01:55 +03:00
|
|
|
// to our local commitment chain. Once we send a revocation for our prior
|
|
|
|
// state, then this newly added commitment becomes our current accepted channel
|
|
|
|
// state.
|
2018-01-31 06:55:39 +03:00
|
|
|
func (lc *LightningChannel) ReceiveNewCommitment(commitSig lnwire.Sig,
|
|
|
|
htlcSigs []lnwire.Sig) error {
|
2017-07-30 22:55:27 +03:00
|
|
|
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2019-09-24 15:33:59 +03:00
|
|
|
// Check for empty commit sig. Because of a previously existing bug, it
|
|
|
|
// is possible that we receive an empty commit sig from nodes running an
|
|
|
|
// older version. This is a relaxation of the spec, but it is still
|
|
|
|
// possible to handle it. To not break any channels with those older
|
|
|
|
// nodes, we just log the event. This check is also not totally
|
|
|
|
// reliable, because it could be that we've sent out a new sig, but the
|
|
|
|
// remote hasn't received it yet. We could then falsely assume that they
|
|
|
|
// should add our updates to their remote commitment tx.
|
|
|
|
if !lc.oweCommitment(false) {
|
|
|
|
lc.log.Warnf("empty commit sig message received")
|
|
|
|
}
|
|
|
|
|
2017-10-19 03:36:28 +03:00
|
|
|
// Determine the last update on the local log that has been locked in.
|
|
|
|
localACKedIndex := lc.remoteCommitChain.tail().ourMessageIndex
|
2017-11-10 10:01:00 +03:00
|
|
|
localHtlcIndex := lc.remoteCommitChain.tail().ourHtlcIndex
|
2017-10-19 03:36:28 +03:00
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
// Ensure that this new local update from the remote node respects all
|
|
|
|
// the constraints we specified during initial channel setup. If not,
|
|
|
|
// then we'll abort the channel as they've violated our constraints.
|
2019-03-09 03:05:28 +03:00
|
|
|
err := lc.validateCommitmentSanity(
|
2020-02-19 14:27:41 +03:00
|
|
|
lc.remoteUpdateLog.logIndex, localACKedIndex, false, nil, nil,
|
2019-03-09 03:05:28 +03:00
|
|
|
)
|
2016-11-23 11:36:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// We're receiving a new commitment which attempts to extend our local
|
2017-07-30 22:55:27 +03:00
|
|
|
// commitment chain height by one, so fetch the proper commitment point
|
2017-10-19 03:36:28 +03:00
|
|
|
// as this will be needed to derive the keys required to construct the
|
2017-07-30 22:55:27 +03:00
|
|
|
// commitment.
|
2016-07-06 03:01:55 +03:00
|
|
|
nextHeight := lc.currentHeight + 1
|
2017-07-30 22:55:27 +03:00
|
|
|
commitSecret, err := lc.channelState.RevocationProducer.AtIndex(nextHeight)
|
2016-07-06 03:01:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
commitPoint := input.ComputeCommitmentPoint(commitSecret[:])
|
2019-09-17 05:06:19 +03:00
|
|
|
keyRing := DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
commitPoint, true, lc.channelState.ChanType,
|
2020-01-06 13:42:02 +03:00
|
|
|
&lc.channelState.LocalChanCfg, &lc.channelState.RemoteChanCfg,
|
2019-03-09 03:05:28 +03:00
|
|
|
)
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
// With the current commitment point re-calculated, construct the new
|
2017-11-29 16:20:02 +03:00
|
|
|
// commitment view which includes all the entries (pending or committed)
|
|
|
|
// we know of in the remote node's HTLC log, but only our local changes
|
|
|
|
// up to the last change the remote node has ACK'd.
|
2017-11-10 09:53:18 +03:00
|
|
|
localCommitmentView, err := lc.fetchCommitmentView(
|
|
|
|
false, localACKedIndex, localHtlcIndex,
|
|
|
|
lc.remoteUpdateLog.logIndex, lc.remoteUpdateLog.htlcCounter,
|
|
|
|
keyRing,
|
|
|
|
)
|
2016-07-06 03:01:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Tracef("extending local chain to height %v, "+
|
2017-11-10 09:53:18 +03:00
|
|
|
"local_log=%v, remote_log=%v",
|
2019-09-24 14:12:53 +03:00
|
|
|
localCommitmentView.height,
|
2017-11-10 09:53:18 +03:00
|
|
|
localACKedIndex, lc.remoteUpdateLog.logIndex)
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Tracef("local chain: our_balance=%v, "+
|
|
|
|
"their_balance=%v, commit_tx: %v",
|
2016-07-13 03:35:51 +03:00
|
|
|
localCommitmentView.ourBalance, localCommitmentView.theirBalance,
|
2016-07-22 02:50:20 +03:00
|
|
|
newLogClosure(func() string {
|
|
|
|
return spew.Sdump(localCommitmentView.txn)
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
}),
|
|
|
|
)
|
2016-07-13 03:35:51 +03:00
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// Construct the sighash of the commitment transaction corresponding to
|
|
|
|
// this newly proposed state update.
|
|
|
|
localCommitTx := localCommitmentView.txn
|
2017-09-26 07:47:39 +03:00
|
|
|
multiSigScript := lc.signDesc.WitnessScript
|
2016-07-06 03:01:55 +03:00
|
|
|
hashCache := txscript.NewTxSigHashes(localCommitTx)
|
2019-03-09 03:05:28 +03:00
|
|
|
sigHash, err := txscript.CalcWitnessSigHash(
|
|
|
|
multiSigScript, hashCache, txscript.SigHashAll,
|
|
|
|
localCommitTx, 0, int64(lc.channelState.Capacity),
|
|
|
|
)
|
2016-07-06 03:01:55 +03:00
|
|
|
if err != nil {
|
2017-01-13 08:01:50 +03:00
|
|
|
// TODO(roasbeef): fetchview has already mutated the HTLCs...
|
2016-07-06 03:01:55 +03:00
|
|
|
// * need to either roll-back, or make pure
|
|
|
|
return err
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
// As an optimization, we'll generate a series of jobs for the worker
|
|
|
|
// pool to verify each of the HTLc signatures presented. Once
|
|
|
|
// generated, we'll submit these jobs to the worker pool.
|
2018-01-31 06:55:39 +03:00
|
|
|
verifyJobs, err := genHtlcSigValidationJobs(
|
2020-01-06 13:42:02 +03:00
|
|
|
localCommitmentView, keyRing, htlcSigs,
|
2020-03-06 18:11:45 +03:00
|
|
|
lc.channelState.ChanType, &lc.channelState.LocalChanCfg,
|
|
|
|
&lc.channelState.RemoteChanCfg,
|
2018-01-31 06:55:39 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
cancelChan := make(chan struct{})
|
|
|
|
verifyResps := lc.sigPool.SubmitVerifyBatch(verifyJobs, cancelChan)
|
|
|
|
|
|
|
|
// While the HTLC verification jobs are proceeding asynchronously,
|
|
|
|
// we'll ensure that the newly constructed commitment state has a valid
|
2016-07-06 03:01:55 +03:00
|
|
|
// signature.
|
2017-06-19 18:43:45 +03:00
|
|
|
verifyKey := btcec.PublicKey{
|
2020-01-06 13:42:02 +03:00
|
|
|
X: lc.channelState.RemoteChanCfg.MultiSigKey.PubKey.X,
|
|
|
|
Y: lc.channelState.RemoteChanCfg.MultiSigKey.PubKey.Y,
|
2017-06-19 18:43:45 +03:00
|
|
|
Curve: btcec.S256(),
|
|
|
|
}
|
2018-01-31 06:55:39 +03:00
|
|
|
cSig, err := commitSig.ToSignature()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !cSig.Verify(sigHash, &verifyKey) {
|
2017-07-30 22:55:27 +03:00
|
|
|
close(cancelChan)
|
2018-01-09 05:50:24 +03:00
|
|
|
|
|
|
|
// If we fail to validate their commitment signature, we'll
|
|
|
|
// generate a special error to send over the protocol. We'll
|
|
|
|
// include the exact signature and commitment we failed to
|
|
|
|
// verify against in order to aide debugging.
|
|
|
|
var txBytes bytes.Buffer
|
|
|
|
localCommitTx.Serialize(&txBytes)
|
|
|
|
return &InvalidCommitSigError{
|
|
|
|
commitHeight: nextHeight,
|
2018-01-31 06:55:39 +03:00
|
|
|
commitSig: commitSig.ToSignatureBytes(),
|
2018-01-09 05:50:24 +03:00
|
|
|
sigHash: sigHash,
|
|
|
|
commitTx: txBytes.Bytes(),
|
|
|
|
}
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2017-07-30 22:55:27 +03:00
|
|
|
// With the primary commitment transaction validated, we'll check each
|
|
|
|
// of the HTLC validation jobs.
|
|
|
|
for i := 0; i < len(verifyJobs); i++ {
|
|
|
|
// In the case that a single signature is invalid, we'll exit
|
|
|
|
// early and cancel all the outstanding verification jobs.
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
htlcErr := <-verifyResps
|
|
|
|
if htlcErr != nil {
|
|
|
|
close(cancelChan)
|
2018-04-05 03:41:05 +03:00
|
|
|
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
sig, err := lnwire.NewSigFromSignature(
|
|
|
|
htlcErr.Sig,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sigHash, err := htlcErr.SigHash()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-04-05 03:41:05 +03:00
|
|
|
|
multi: replace per channel sigPool with global daemon level sigPool
In this commit, we remove the per channel `sigPool` within the
`lnwallet.LightningChannel` struct. With this change, we ensure that as
the number of channels grows, the number of gouroutines idling in the
sigPool stays constant. It's the case that currently on the daemon, most
channels are likely inactive, with only a hand full actually
consistently carrying out channel updates. As a result, this change
should reduce the amount of idle CPU usage, as we have less active
goroutines in select loops.
In order to make this change, the `SigPool` itself has been publicly
exported such that outside callers can make a `SigPool` and pass it into
newly created channels. Since the sig pool now lives outside the
channel, we were also able to do away with the Stop() method on the
channel all together.
Finally, the server is the sub-system that is currently responsible for
managing the `SigPool` within lnd.
2018-12-15 03:35:07 +03:00
|
|
|
var txBytes bytes.Buffer
|
|
|
|
localCommitTx.Serialize(&txBytes)
|
|
|
|
return &InvalidHtlcSigError{
|
|
|
|
commitHeight: nextHeight,
|
|
|
|
htlcSig: sig.ToSignatureBytes(),
|
|
|
|
htlcIndex: htlcErr.HtlcIndex,
|
|
|
|
sigHash: sigHash,
|
|
|
|
commitTx: txBytes.Bytes(),
|
2017-11-12 02:00:45 +03:00
|
|
|
}
|
2017-07-30 22:55:27 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// The signature checks out, so we can now add the new commitment to
|
|
|
|
// our local commitment chain.
|
2018-01-31 06:55:39 +03:00
|
|
|
localCommitmentView.sig = commitSig.ToSignatureBytes()
|
2016-07-06 03:01:55 +03:00
|
|
|
lc.localCommitChain.addCommitment(localCommitmentView)
|
2016-01-06 00:01:42 +03:00
|
|
|
|
|
|
|
return nil
|
2015-12-17 07:58:01 +03:00
|
|
|
}
|
|
|
|
|
2019-09-24 15:33:59 +03:00
|
|
|
// OweCommitment returns a boolean value reflecting whether we need to send
|
|
|
|
// out a commitment signature because there are outstanding local updates and/or
|
|
|
|
// updates in the local commit tx that aren't reflected in the remote commit tx
|
|
|
|
// yet.
|
|
|
|
func (lc *LightningChannel) OweCommitment(local bool) bool {
|
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
return lc.oweCommitment(local)
|
|
|
|
}
|
|
|
|
|
|
|
|
// oweCommitment is the internal version of OweCommitment. This function expects
|
|
|
|
// to be executed with a lock held.
|
|
|
|
func (lc *LightningChannel) oweCommitment(local bool) bool {
|
|
|
|
var (
|
|
|
|
remoteUpdatesPending, localUpdatesPending bool
|
|
|
|
|
|
|
|
lastLocalCommit = lc.localCommitChain.tip()
|
|
|
|
lastRemoteCommit = lc.remoteCommitChain.tip()
|
|
|
|
|
|
|
|
perspective string
|
|
|
|
)
|
|
|
|
|
|
|
|
if local {
|
|
|
|
perspective = "local"
|
|
|
|
|
|
|
|
// There are local updates pending if our local update log is
|
|
|
|
// not in sync with our remote commitment tx.
|
|
|
|
localUpdatesPending = lc.localUpdateLog.logIndex !=
|
|
|
|
lastRemoteCommit.ourMessageIndex
|
|
|
|
|
|
|
|
// There are remote updates pending if their remote commitment
|
|
|
|
// tx (our local commitment tx) contains updates that we don't
|
|
|
|
// have added to our remote commitment tx yet.
|
|
|
|
remoteUpdatesPending = lastLocalCommit.theirMessageIndex !=
|
|
|
|
lastRemoteCommit.theirMessageIndex
|
|
|
|
|
|
|
|
} else {
|
|
|
|
perspective = "remote"
|
|
|
|
|
|
|
|
// There are local updates pending (local updates from the
|
|
|
|
// perspective of the remote party) if the remote party has
|
|
|
|
// updates to their remote tx pending for which they haven't
|
|
|
|
// signed yet.
|
|
|
|
localUpdatesPending = lc.remoteUpdateLog.logIndex !=
|
|
|
|
lastLocalCommit.theirMessageIndex
|
|
|
|
|
|
|
|
// There are remote updates pending (remote updates from the
|
|
|
|
// perspective of the remote party) if we have updates on our
|
|
|
|
// remote commitment tx that they haven't added to theirs yet.
|
|
|
|
remoteUpdatesPending = lastRemoteCommit.ourMessageIndex !=
|
|
|
|
lastLocalCommit.ourMessageIndex
|
|
|
|
}
|
|
|
|
|
|
|
|
// If any of the conditions above is true, we owe a commitment
|
|
|
|
// signature.
|
|
|
|
oweCommitment := localUpdatesPending || remoteUpdatesPending
|
|
|
|
|
|
|
|
lc.log.Tracef("%v owes commit: %v (local updates: %v, "+
|
|
|
|
"remote updates %v)", perspective, oweCommitment,
|
|
|
|
localUpdatesPending, remoteUpdatesPending)
|
|
|
|
|
|
|
|
return oweCommitment
|
|
|
|
}
|
|
|
|
|
2019-04-10 14:10:25 +03:00
|
|
|
// PendingLocalUpdateCount returns the number of local updates that still need
|
|
|
|
// to be applied to the remote commitment tx.
|
|
|
|
func (lc *LightningChannel) PendingLocalUpdateCount() uint64 {
|
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
lastRemoteCommit := lc.remoteCommitChain.tip()
|
|
|
|
|
|
|
|
return lc.localUpdateLog.logIndex - lastRemoteCommit.ourMessageIndex
|
|
|
|
}
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// RevokeCurrentCommitment revokes the next lowest unrevoked commitment
|
|
|
|
// transaction in the local commitment chain. As a result the edge of our
|
|
|
|
// revocation window is extended by one, and the tail of our local commitment
|
|
|
|
// chain is advanced by a single commitment. This now lowest unrevoked
|
2018-01-17 05:09:32 +03:00
|
|
|
// commitment becomes our currently accepted state within the channel. This
|
|
|
|
// method also returns the set of HTLC's currently active within the commitment
|
|
|
|
// transaction. This return value allows callers to act once an HTLC has been
|
|
|
|
// locked into our commitment transaction.
|
|
|
|
func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, []channeldb.HTLC, error) {
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2017-07-09 02:30:20 +03:00
|
|
|
revocationMsg, err := lc.generateRevocation(lc.currentHeight)
|
2016-07-06 03:01:55 +03:00
|
|
|
if err != nil {
|
2018-01-17 05:09:32 +03:00
|
|
|
return nil, nil, err
|
2015-12-31 09:36:01 +03:00
|
|
|
}
|
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Tracef("revoking height=%v, now at height=%v",
|
|
|
|
lc.localCommitChain.tail().height,
|
2017-11-10 10:01:00 +03:00
|
|
|
lc.currentHeight+1)
|
2016-07-13 03:35:51 +03:00
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
// Advance our tail, as we've revoked our previous state.
|
|
|
|
lc.localCommitChain.advanceTail()
|
|
|
|
lc.currentHeight++
|
|
|
|
|
2016-09-07 20:45:27 +03:00
|
|
|
// Additionally, generate a channel delta for this state transition for
|
|
|
|
// persistent storage.
|
2017-11-10 10:01:00 +03:00
|
|
|
chainTail := lc.localCommitChain.tail()
|
|
|
|
newCommitment := chainTail.toDiskCommit(true)
|
2020-01-03 17:53:51 +03:00
|
|
|
|
|
|
|
// Get the unsigned acked remotes updates that are currently in memory.
|
|
|
|
// We need them after a restart to sync our remote commitment with what
|
|
|
|
// is committed locally.
|
|
|
|
unsignedAckedUpdates := lc.getUnsignedAckedUpdates()
|
|
|
|
|
|
|
|
err = lc.channelState.UpdateCommitment(
|
|
|
|
newCommitment, unsignedAckedUpdates,
|
|
|
|
)
|
2016-09-07 20:45:27 +03:00
|
|
|
if err != nil {
|
2018-01-17 05:09:32 +03:00
|
|
|
return nil, nil, err
|
2016-09-07 20:45:27 +03:00
|
|
|
}
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Tracef("state transition accepted: "+
|
2020-01-03 17:53:51 +03:00
|
|
|
"our_balance=%v, their_balance=%v, unsigned_acked_updates=%v",
|
2019-09-24 14:12:53 +03:00
|
|
|
chainTail.ourBalance,
|
2020-01-03 17:53:51 +03:00
|
|
|
chainTail.theirBalance,
|
|
|
|
len(unsignedAckedUpdates))
|
2016-07-13 03:35:51 +03:00
|
|
|
|
2017-07-30 22:25:41 +03:00
|
|
|
revocationMsg.ChanID = lnwire.NewChanIDFromOutPoint(
|
|
|
|
&lc.channelState.FundingOutpoint,
|
|
|
|
)
|
|
|
|
|
2018-01-17 05:09:32 +03:00
|
|
|
return revocationMsg, newCommitment.Htlcs, nil
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ReceiveRevocation processes a revocation sent by the remote party for the
|
|
|
|
// lowest unrevoked commitment within their commitment chain. We receive a
|
|
|
|
// revocation either during the initial session negotiation wherein revocation
|
|
|
|
// windows are extended, or in response to a state update that we initiate. If
|
|
|
|
// successful, then the remote commitment chain is advanced by a single
|
2018-02-28 07:04:41 +03:00
|
|
|
// commitment, and a log compaction is attempted.
|
|
|
|
//
|
|
|
|
// The returned values correspond to:
|
|
|
|
// 1. The forwarding package corresponding to the remote commitment height
|
|
|
|
// that was revoked.
|
|
|
|
// 2. The PaymentDescriptor of any Add HTLCs that were locked in by this
|
|
|
|
// revocation.
|
|
|
|
// 3. The PaymentDescriptor of any Settle/Fail HTLCs that were locked in by
|
|
|
|
// this revocation.
|
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
|
|
|
// 4. The set of HTLCs present on the current valid commitment transaction
|
|
|
|
// for the remote party.
|
2018-02-28 07:01:41 +03:00
|
|
|
func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) (
|
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
|
|
|
*channeldb.FwdPkg, []*PaymentDescriptor, []*PaymentDescriptor,
|
|
|
|
[]channeldb.HTLC, error) {
|
2018-02-28 07:01:41 +03:00
|
|
|
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2016-12-14 17:01:48 +03:00
|
|
|
// Ensure that the new pre-image can be placed in preimage store.
|
|
|
|
store := lc.channelState.RevocationStore
|
2017-07-30 22:32:24 +03:00
|
|
|
revocation, err := chainhash.NewHash(revMsg.Revocation[:])
|
|
|
|
if err != 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
|
|
|
return nil, nil, nil, nil, err
|
2015-12-31 09:36:01 +03:00
|
|
|
}
|
2017-07-30 22:32:24 +03:00
|
|
|
if err := store.AddNextEntry(revocation); err != 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
|
|
|
return nil, nil, nil, nil, err
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2015-12-31 09:36:01 +03:00
|
|
|
|
2017-07-30 22:32:24 +03:00
|
|
|
// Verify that if we use the commitment point computed based off of the
|
|
|
|
// revealed secret to derive a revocation key with our revocation base
|
|
|
|
// point, then it matches the current revocation of the remote party.
|
|
|
|
currentCommitPoint := lc.channelState.RemoteCurrentRevocation
|
2019-01-16 17:47:43 +03:00
|
|
|
derivedCommitPoint := input.ComputeCommitmentPoint(revMsg.Revocation[:])
|
2017-07-30 22:32:24 +03:00
|
|
|
if !derivedCommitPoint.IsEqual(currentCommitPoint) {
|
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
|
|
|
return nil, nil, nil, nil, fmt.Errorf("revocation key mismatch")
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2017-07-30 22:32:24 +03:00
|
|
|
// Now that we've verified that the prior commitment has been properly
|
|
|
|
// revoked, we'll advance the revocation state we track for the remote
|
|
|
|
// party: the new current revocation is what was previously the next
|
|
|
|
// revocation, and the new next revocation is set to the key included
|
|
|
|
// in the message.
|
|
|
|
lc.channelState.RemoteCurrentRevocation = lc.channelState.RemoteNextRevocation
|
|
|
|
lc.channelState.RemoteNextRevocation = revMsg.NextRevocationKey
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2019-09-24 14:12:53 +03:00
|
|
|
lc.log.Tracef("remote party accepted state transition, revoked height "+
|
|
|
|
"%v, now at %v",
|
2016-07-13 03:32:32 +03:00
|
|
|
lc.remoteCommitChain.tail().height,
|
|
|
|
lc.remoteCommitChain.tail().height+1)
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// Add one to the remote tail since this will be height *after* we write
|
|
|
|
// the revocation to disk, the local height will remain unchanged.
|
|
|
|
remoteChainTail := lc.remoteCommitChain.tail().height + 1
|
|
|
|
localChainTail := lc.localCommitChain.tail().height
|
2016-07-13 03:32:32 +03:00
|
|
|
|
2018-05-28 13:59:41 +03:00
|
|
|
source := lc.ShortChanID()
|
2018-02-28 07:01:41 +03:00
|
|
|
chanID := lnwire.NewChanIDFromOutPoint(&lc.channelState.FundingOutpoint)
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// Determine the set of htlcs that can be forwarded as a result of
|
|
|
|
// having received the revocation. We will simultaneously construct the
|
|
|
|
// log updates and payment descriptors, allowing us to persist the log
|
|
|
|
// updates to disk and optimistically buffer the forwarding package in
|
|
|
|
// memory.
|
|
|
|
var (
|
|
|
|
addsToForward []*PaymentDescriptor
|
|
|
|
addUpdates []channeldb.LogUpdate
|
|
|
|
settleFailsToForward []*PaymentDescriptor
|
|
|
|
settleFailUpdates []channeldb.LogUpdate
|
|
|
|
)
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
var addIndex, settleFailIndex uint16
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
for e := lc.remoteUpdateLog.Front(); e != nil; e = e.Next() {
|
2018-02-28 07:01:41 +03:00
|
|
|
pd := e.Value.(*PaymentDescriptor)
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2019-01-10 14:23:56 +03:00
|
|
|
// Fee updates are local to this particular channel, and should
|
|
|
|
// never be forwarded.
|
|
|
|
if pd.EntryType == FeeUpdate {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
if pd.isForwarded {
|
2016-07-17 04:12:36 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-05-28 13:59:41 +03:00
|
|
|
// For each type of HTLC, we will only consider forwarding it if
|
|
|
|
// both of the remote and local heights are non-zero. If either
|
|
|
|
// of these values is zero, it has yet to be committed in both
|
|
|
|
// the local and remote chains.
|
|
|
|
committedAdd := pd.addCommitHeightRemote > 0 &&
|
|
|
|
pd.addCommitHeightLocal > 0
|
|
|
|
committedRmv := pd.removeCommitHeightRemote > 0 &&
|
|
|
|
pd.removeCommitHeightLocal > 0
|
2016-07-22 02:50:20 +03:00
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// Using the height of the remote and local commitments,
|
|
|
|
// preemptively compute whether or not to forward this HTLC for
|
|
|
|
// the case in which this in an Add HTLC, or if this is a
|
|
|
|
// Settle, Fail, or MalformedFail.
|
|
|
|
shouldFwdAdd := remoteChainTail == pd.addCommitHeightRemote &&
|
|
|
|
localChainTail >= pd.addCommitHeightLocal
|
2018-05-28 13:59:41 +03:00
|
|
|
shouldFwdRmv := remoteChainTail == pd.removeCommitHeightRemote &&
|
2018-02-28 07:01:41 +03:00
|
|
|
localChainTail >= pd.removeCommitHeightLocal
|
|
|
|
|
lnwallet: only forward freshly locked in HTLC's in ReceiveRevocation
This commit fixes a nasty bug that has been lingering within lnd, and
has been noticed due to the added retransmission logic. Before this
commit, upon a restart, if we had an active HTLC and received a new
commitment update, then we would re-forward ALL active HTLC’s. This
could at times lead to a nasty cycle:
* We re-forward an HTLC already processed.
* We then notice that the time-lock is out of date (retransmitted
HTLC), so we go to fail it.
* This is detected as a replay attack, so we send an
UpdateMalformedHTLC
* This second failure ends up creating a nil entry in the log,
leading to a panic.
* Remote party disconnects.
* Upon reconnect we send again as we need to retransmit the changes,
this goes on forever.
In order to fix this, we now ensure that we only forward HTLC’s that
have been newly locked in at this next state. With this, we now avoid
the loop described above, and also ensure that we don’t accidentally
attempt an HTLC replay attack on our selves.
Fixes #528.
Fixes #545.
2018-01-09 06:45:36 +03:00
|
|
|
// We'll only forward any new HTLC additions iff, it's "freshly
|
|
|
|
// locked in". Meaning that the HTLC was only *just* considered
|
|
|
|
// locked-in at this new state. By doing this we ensure that we
|
|
|
|
// don't re-forward any already processed HTLC's after a
|
|
|
|
// restart.
|
2018-02-28 07:01:41 +03:00
|
|
|
switch {
|
2018-05-28 13:59:41 +03:00
|
|
|
case pd.EntryType == Add && committedAdd && shouldFwdAdd:
|
2018-02-28 07:01:41 +03:00
|
|
|
// Construct a reference specifying the location that
|
|
|
|
// this forwarded Add will be written in the forwarding
|
|
|
|
// package constructed at this remote height.
|
|
|
|
pd.SourceRef = &channeldb.AddRef{
|
|
|
|
Height: remoteChainTail,
|
|
|
|
Index: addIndex,
|
|
|
|
}
|
|
|
|
addIndex++
|
|
|
|
|
|
|
|
pd.isForwarded = true
|
|
|
|
addsToForward = append(addsToForward, pd)
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
|
2018-05-28 13:59:41 +03:00
|
|
|
case pd.EntryType != Add && committedRmv && shouldFwdRmv:
|
2018-02-28 07:01:41 +03:00
|
|
|
// Construct a reference specifying the location that
|
|
|
|
// this forwarded Settle/Fail will be written in the
|
|
|
|
// forwarding package constructed at this remote height.
|
|
|
|
pd.DestRef = &channeldb.SettleFailRef{
|
2018-05-28 13:59:41 +03:00
|
|
|
Source: source,
|
2018-02-28 07:01:41 +03:00
|
|
|
Height: remoteChainTail,
|
|
|
|
Index: settleFailIndex,
|
|
|
|
}
|
|
|
|
settleFailIndex++
|
|
|
|
|
|
|
|
pd.isForwarded = true
|
|
|
|
settleFailsToForward = append(settleFailsToForward, pd)
|
|
|
|
|
|
|
|
default:
|
lnwallet: only forward freshly locked in HTLC's in ReceiveRevocation
This commit fixes a nasty bug that has been lingering within lnd, and
has been noticed due to the added retransmission logic. Before this
commit, upon a restart, if we had an active HTLC and received a new
commitment update, then we would re-forward ALL active HTLC’s. This
could at times lead to a nasty cycle:
* We re-forward an HTLC already processed.
* We then notice that the time-lock is out of date (retransmitted
HTLC), so we go to fail it.
* This is detected as a replay attack, so we send an
UpdateMalformedHTLC
* This second failure ends up creating a nil entry in the log,
leading to a panic.
* Remote party disconnects.
* Upon reconnect we send again as we need to retransmit the changes,
this goes on forever.
In order to fix this, we now ensure that we only forward HTLC’s that
have been newly locked in at this next state. With this, we now avoid
the loop described above, and also ensure that we don’t accidentally
attempt an HTLC replay attack on our selves.
Fixes #528.
Fixes #545.
2018-01-09 06:45:36 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// If we've reached this point, this HTLC will be added to the
|
|
|
|
// forwarding package at the height of the remote commitment.
|
|
|
|
// All types of HTLCs will record their assigned log index.
|
|
|
|
logUpdate := channeldb.LogUpdate{
|
|
|
|
LogIndex: pd.LogIndex,
|
|
|
|
}
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// Next, we'll map the type of the PaymentDescriptor to one of
|
|
|
|
// the four messages that it corresponds to and separate the
|
|
|
|
// updates into Adds and Settle/Fail/MalformedFail such that
|
|
|
|
// they can be written in the forwarding package. Adds are
|
|
|
|
// aggregated separately from the other types of HTLCs.
|
|
|
|
switch pd.EntryType {
|
|
|
|
case Add:
|
|
|
|
htlc := &lnwire.UpdateAddHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.HtlcIndex,
|
|
|
|
Amount: pd.Amount,
|
|
|
|
Expiry: pd.Timeout,
|
|
|
|
PaymentHash: pd.RHash,
|
|
|
|
}
|
|
|
|
copy(htlc.OnionBlob[:], pd.OnionBlob)
|
|
|
|
logUpdate.UpdateMsg = htlc
|
|
|
|
addUpdates = append(addUpdates, logUpdate)
|
|
|
|
|
|
|
|
case Settle:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFulfillHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
PaymentPreimage: pd.RPreimage,
|
|
|
|
}
|
|
|
|
settleFailUpdates = append(settleFailUpdates, logUpdate)
|
|
|
|
|
|
|
|
case Fail:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFailHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
Reason: pd.FailReason,
|
|
|
|
}
|
|
|
|
settleFailUpdates = append(settleFailUpdates, logUpdate)
|
|
|
|
|
|
|
|
case MalformedFail:
|
|
|
|
logUpdate.UpdateMsg = &lnwire.UpdateFailMalformedHTLC{
|
|
|
|
ChanID: chanID,
|
|
|
|
ID: pd.ParentIndex,
|
|
|
|
ShaOnionBlob: pd.ShaOnionBlob,
|
|
|
|
FailureCode: pd.FailCode,
|
|
|
|
}
|
|
|
|
settleFailUpdates = append(settleFailUpdates, logUpdate)
|
2016-07-22 02:50:20 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// Now that we have gathered the set of HTLCs to forward, separated by
|
|
|
|
// type, construct a forwarding package using the height that the remote
|
|
|
|
// commitment chain will be extended after persisting the revocation.
|
|
|
|
fwdPkg := channeldb.NewFwdPkg(
|
|
|
|
source, remoteChainTail, addUpdates, settleFailUpdates,
|
|
|
|
)
|
|
|
|
|
|
|
|
// At this point, the revocation has been accepted, and we've rotated
|
|
|
|
// the current revocation key+hash for the remote party. Therefore we
|
|
|
|
// sync now to ensure the revocation producer state is consistent with
|
|
|
|
// the current commitment height and also to advance the on-disk
|
|
|
|
// commitment chain.
|
|
|
|
err = lc.channelState.AdvanceCommitChainTail(fwdPkg)
|
|
|
|
if err != 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
|
|
|
return nil, nil, nil, nil, err
|
2018-02-28 07:01:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Since they revoked the current lowest height in their commitment
|
|
|
|
// chain, we can advance their chain by a single commitment.
|
|
|
|
lc.remoteCommitChain.advanceTail()
|
|
|
|
|
2017-02-25 03:09:21 +03:00
|
|
|
// As we've just completed a new state transition, attempt to see if we
|
|
|
|
// can remove any entries from the update log which have been removed
|
|
|
|
// from the PoV of both commitment chains.
|
2019-03-09 03:05:28 +03:00
|
|
|
compactLogs(
|
|
|
|
lc.localUpdateLog, lc.remoteUpdateLog, localChainTail,
|
|
|
|
remoteChainTail,
|
|
|
|
)
|
2016-07-22 02:50:20 +03:00
|
|
|
|
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
|
|
|
remoteHTLCs := lc.channelState.RemoteCommitment.Htlcs
|
|
|
|
|
|
|
|
return fwdPkg, addsToForward, settleFailsToForward, remoteHTLCs, nil
|
2015-12-31 09:36:01 +03:00
|
|
|
}
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// LoadFwdPkgs loads any pending log updates from disk and returns the payment
|
|
|
|
// descriptors to be processed by the link.
|
|
|
|
func (lc *LightningChannel) LoadFwdPkgs() ([]*channeldb.FwdPkg, error) {
|
|
|
|
return lc.channelState.LoadFwdPkgs()
|
|
|
|
}
|
|
|
|
|
2018-07-27 13:22:15 +03:00
|
|
|
// AckAddHtlcs sets a bit in the FwdFilter of a forwarding package belonging to
|
|
|
|
// this channel, that corresponds to the given AddRef. This method also succeeds
|
|
|
|
// if no forwarding package is found.
|
|
|
|
func (lc *LightningChannel) AckAddHtlcs(addRef channeldb.AddRef) error {
|
|
|
|
return lc.channelState.AckAddHtlcs(addRef)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AckSettleFails sets a bit in the SettleFailFilter of a forwarding package
|
|
|
|
// belonging to this channel, that corresponds to the given SettleFailRef. This
|
|
|
|
// method also succeeds if no forwarding package is found.
|
|
|
|
func (lc *LightningChannel) AckSettleFails(
|
|
|
|
settleFailRefs ...channeldb.SettleFailRef) error {
|
|
|
|
|
|
|
|
return lc.channelState.AckSettleFails(settleFailRefs...)
|
|
|
|
}
|
|
|
|
|
2018-02-28 07:01:41 +03:00
|
|
|
// SetFwdFilter writes the forwarding decision for a given remote commitment
|
|
|
|
// height.
|
|
|
|
func (lc *LightningChannel) SetFwdFilter(height uint64,
|
|
|
|
fwdFilter *channeldb.PkgFilter) error {
|
|
|
|
|
|
|
|
return lc.channelState.SetFwdFilter(height, fwdFilter)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveFwdPkg permanently deletes the forwarding package at the given height.
|
|
|
|
func (lc *LightningChannel) RemoveFwdPkg(height uint64) error {
|
|
|
|
return lc.channelState.RemoveFwdPkg(height)
|
|
|
|
}
|
|
|
|
|
2017-07-30 22:32:24 +03:00
|
|
|
// NextRevocationKey returns the commitment point for the _next_ commitment
|
2017-02-25 03:09:21 +03:00
|
|
|
// height. The pubkey returned by this function is required by the remote party
|
2018-04-18 05:03:27 +03:00
|
|
|
// along with their revocation base to extend our commitment chain with a
|
2017-07-30 22:32:24 +03:00
|
|
|
// new commitment.
|
2017-07-31 04:22:38 +03:00
|
|
|
func (lc *LightningChannel) NextRevocationKey() (*btcec.PublicKey, error) {
|
2017-02-25 03:09:21 +03:00
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
nextHeight := lc.currentHeight + 1
|
|
|
|
revocation, err := lc.channelState.RevocationProducer.AtIndex(nextHeight)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
return input.ComputeCommitmentPoint(revocation[:]), nil
|
2017-07-30 22:32:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// InitNextRevocation inserts the passed commitment point as the _next_
|
2017-09-25 21:25:58 +03:00
|
|
|
// revocation to be used when creating a new commitment state for the remote
|
2017-07-30 22:32:24 +03:00
|
|
|
// party. This function MUST be called before the channel can accept or propose
|
|
|
|
// any new states.
|
|
|
|
func (lc *LightningChannel) InitNextRevocation(revKey *btcec.PublicKey) error {
|
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
|
|
|
return lc.channelState.InsertNextRevocation(revKey)
|
2017-02-25 03:09:21 +03:00
|
|
|
}
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// AddHTLC adds an HTLC to the state machine's local update log. This method
|
|
|
|
// should be called when preparing to send an outgoing HTLC.
|
2018-02-28 07:04:41 +03:00
|
|
|
//
|
|
|
|
// The additional openKey argument corresponds to the incoming CircuitKey of the
|
|
|
|
// committed circuit for this HTLC. This value should never be nil.
|
|
|
|
//
|
2020-02-19 14:27:42 +03:00
|
|
|
// Note that AddHTLC doesn't reserve the HTLC fee for future payment (like
|
|
|
|
// AvailableBalance does), so one could get into the "stuck channel" state by
|
|
|
|
// sending dust HTLCs.
|
|
|
|
// TODO(halseth): fix this either by using additional reserve, or better commit
|
|
|
|
// format. See https://github.com/lightningnetwork/lightning-rfc/issues/728
|
|
|
|
//
|
2018-02-28 07:04:41 +03:00
|
|
|
// NOTE: It is okay for sourceRef to be nil when unit testing the wallet.
|
|
|
|
func (lc *LightningChannel) AddHTLC(htlc *lnwire.UpdateAddHTLC,
|
|
|
|
openKey *channeldb.CircuitKey) (uint64, error) {
|
2018-02-28 07:01:41 +03:00
|
|
|
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2016-07-06 03:01:55 +03:00
|
|
|
pd := &PaymentDescriptor{
|
2018-02-28 07:04:41 +03:00
|
|
|
EntryType: Add,
|
|
|
|
RHash: PaymentHash(htlc.PaymentHash),
|
|
|
|
Timeout: htlc.Expiry,
|
|
|
|
Amount: htlc.Amount,
|
|
|
|
LogIndex: lc.localUpdateLog.logIndex,
|
|
|
|
HtlcIndex: lc.localUpdateLog.htlcCounter,
|
|
|
|
OnionBlob: htlc.OnionBlob[:],
|
|
|
|
OpenCircuitKey: openKey,
|
2015-12-31 09:36:01 +03:00
|
|
|
}
|
|
|
|
|
2018-02-25 06:19:24 +03:00
|
|
|
// Make sure adding this HTLC won't violate any of the constraints we
|
2020-02-19 14:27:41 +03:00
|
|
|
// must keep on the commitment transactions.
|
2017-11-29 16:20:02 +03:00
|
|
|
remoteACKedIndex := lc.localCommitChain.tail().theirMessageIndex
|
2020-02-19 14:27:41 +03:00
|
|
|
|
|
|
|
// First we'll check whether this HTLC can be added to the remote
|
|
|
|
// commitment transaction without violation any of the constraints.
|
2018-02-25 06:19:24 +03:00
|
|
|
err := lc.validateCommitmentSanity(
|
2020-02-19 14:27:41 +03:00
|
|
|
remoteACKedIndex, lc.localUpdateLog.logIndex, true, pd, nil,
|
2018-02-25 06:19:24 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
2017-11-29 16:20:02 +03:00
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2020-02-19 14:27:41 +03:00
|
|
|
// We must also check whether it can be added to our own commitment
|
|
|
|
// transaction, or the remote node will refuse to sign. This is not
|
|
|
|
// totally bullet proof, as the remote might be adding updates
|
|
|
|
// concurrently, but if we fail this check there is for sure not
|
|
|
|
// possible for us to add the HTLC.
|
|
|
|
err = lc.validateCommitmentSanity(
|
|
|
|
lc.remoteUpdateLog.logIndex, lc.localUpdateLog.logIndex,
|
|
|
|
false, pd, nil,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
lc.localUpdateLog.appendHtlc(pd)
|
2016-07-22 02:50:20 +03:00
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
return pd.HtlcIndex, nil
|
2016-07-22 02:50:20 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ReceiveHTLC adds an HTLC to the state machine's remote update log. This
|
|
|
|
// method should be called in response to receiving a new HTLC from the remote
|
|
|
|
// party.
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
func (lc *LightningChannel) ReceiveHTLC(htlc *lnwire.UpdateAddHTLC) (uint64, error) {
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
if htlc.ID != lc.remoteUpdateLog.htlcCounter {
|
|
|
|
return 0, fmt.Errorf("ID %d on HTLC add does not match expected next "+
|
|
|
|
"ID %d", htlc.ID, lc.remoteUpdateLog.htlcCounter)
|
|
|
|
}
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
pd := &PaymentDescriptor{
|
2017-07-30 22:44:13 +03:00
|
|
|
EntryType: Add,
|
|
|
|
RHash: PaymentHash(htlc.PaymentHash),
|
|
|
|
Timeout: htlc.Expiry,
|
|
|
|
Amount: htlc.Amount,
|
2017-10-23 02:28:30 +03:00
|
|
|
LogIndex: lc.remoteUpdateLog.logIndex,
|
|
|
|
HtlcIndex: lc.remoteUpdateLog.htlcCounter,
|
2017-07-09 02:38:50 +03:00
|
|
|
OnionBlob: htlc.OnionBlob[:],
|
2015-12-31 09:36:01 +03:00
|
|
|
}
|
|
|
|
|
2020-02-15 17:45:25 +03:00
|
|
|
localACKedIndex := lc.remoteCommitChain.tail().ourMessageIndex
|
|
|
|
|
|
|
|
// Clamp down on the number of HTLC's we can receive by checking the
|
|
|
|
// commitment sanity.
|
|
|
|
err := lc.validateCommitmentSanity(
|
2020-02-19 14:27:41 +03:00
|
|
|
lc.remoteUpdateLog.logIndex, localACKedIndex, false, nil, pd,
|
2020-02-15 17:45:25 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
lc.remoteUpdateLog.appendHtlc(pd)
|
2016-07-06 03:01:55 +03:00
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
return pd.HtlcIndex, nil
|
2015-12-17 07:58:01 +03:00
|
|
|
}
|
|
|
|
|
2016-10-15 16:18:38 +03:00
|
|
|
// SettleHTLC attempts to settle an existing outstanding received HTLC. The
|
2016-07-22 02:50:20 +03:00
|
|
|
// remote log index of the HTLC settled is returned in order to facilitate
|
2017-01-13 08:01:50 +03:00
|
|
|
// creating the corresponding wire message. In the case the supplied preimage
|
2018-02-28 07:04:41 +03:00
|
|
|
// is invalid, an error is returned.
|
|
|
|
//
|
|
|
|
// The additional arguments correspond to:
|
|
|
|
// * sourceRef: specifies the location of the Add HTLC within a forwarding
|
|
|
|
// package that this HTLC is settling. Every Settle fails exactly one Add,
|
|
|
|
// so this should never be empty in practice.
|
|
|
|
//
|
|
|
|
// * destRef: specifies the location of the Settle HTLC within another
|
|
|
|
// channel's forwarding package. This value can be nil if the corresponding
|
|
|
|
// Add HTLC was never locked into an outgoing commitment txn, or this
|
|
|
|
// HTLC does not originate as a response from the peer on the outgoing
|
|
|
|
// link, e.g. on-chain resolutions.
|
|
|
|
//
|
|
|
|
// * closeKey: identifies the circuit that should be deleted after this Settle
|
|
|
|
// HTLC is included in a commitment txn. This value should only be nil if
|
|
|
|
// the HTLC was settled locally before committing a circuit to the circuit
|
|
|
|
// map.
|
|
|
|
//
|
|
|
|
// NOTE: It is okay for sourceRef, destRef, and closeKey to be nil when unit
|
|
|
|
// testing the wallet.
|
|
|
|
func (lc *LightningChannel) SettleHTLC(preimage [32]byte,
|
|
|
|
htlcIndex uint64, sourceRef *channeldb.AddRef,
|
|
|
|
destRef *channeldb.SettleFailRef, closeKey *channeldb.CircuitKey) error {
|
2017-10-24 10:48:52 +03:00
|
|
|
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
htlc := lc.remoteUpdateLog.lookupHtlc(htlcIndex)
|
|
|
|
if htlc == nil {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrUnknownHtlcIndex{lc.ShortChanID(), htlcIndex}
|
2017-10-24 10:48:52 +03:00
|
|
|
}
|
|
|
|
|
2018-05-26 04:39:55 +03:00
|
|
|
// Now that we know the HTLC exists, before checking to see if the
|
|
|
|
// preimage matches, we'll ensure that we haven't already attempted to
|
|
|
|
// modify the HTLC.
|
|
|
|
if lc.remoteUpdateLog.htlcHasModification(htlcIndex) {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrHtlcIndexAlreadySettled(htlcIndex)
|
2018-05-26 04:39:55 +03:00
|
|
|
}
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
if htlc.RHash != sha256.Sum256(preimage[:]) {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrInvalidSettlePreimage{preimage[:], htlc.RHash[:]}
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
pd := &PaymentDescriptor{
|
2018-02-28 07:04:41 +03:00
|
|
|
Amount: htlc.Amount,
|
|
|
|
RPreimage: preimage,
|
|
|
|
LogIndex: lc.localUpdateLog.logIndex,
|
|
|
|
ParentIndex: htlcIndex,
|
|
|
|
EntryType: Settle,
|
|
|
|
SourceRef: sourceRef,
|
|
|
|
DestRef: destRef,
|
|
|
|
ClosedCircuitKey: closeKey,
|
2016-01-06 00:01:42 +03:00
|
|
|
}
|
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
lc.localUpdateLog.appendUpdate(pd)
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2018-05-26 04:39:55 +03:00
|
|
|
// With the settle added to our local log, we'll now mark the HTLC as
|
|
|
|
// modified to prevent ourselves from accidentally attempting a
|
|
|
|
// duplicate settle.
|
|
|
|
lc.remoteUpdateLog.markHtlcModified(htlcIndex)
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
return nil
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
// ReceiveHTLCSettle attempts to settle an existing outgoing HTLC indexed by an
|
|
|
|
// index into the local log. If the specified index doesn't exist within the
|
|
|
|
// log, and error is returned. Similarly if the preimage is invalid w.r.t to
|
|
|
|
// the referenced of then a distinct error is returned.
|
2017-10-23 02:28:30 +03:00
|
|
|
func (lc *LightningChannel) ReceiveHTLCSettle(preimage [32]byte, htlcIndex uint64) error {
|
2016-11-21 06:18:30 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
htlc := lc.localUpdateLog.lookupHtlc(htlcIndex)
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
if htlc == nil {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrUnknownHtlcIndex{lc.ShortChanID(), htlcIndex}
|
2016-07-22 02:50:20 +03:00
|
|
|
}
|
|
|
|
|
2018-05-26 04:39:55 +03:00
|
|
|
// Now that we know the HTLC exists, before checking to see if the
|
|
|
|
// preimage matches, we'll ensure that they haven't already attempted
|
|
|
|
// to modify the HTLC.
|
|
|
|
if lc.localUpdateLog.htlcHasModification(htlcIndex) {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrHtlcIndexAlreadySettled(htlcIndex)
|
2018-05-26 04:39:55 +03:00
|
|
|
}
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
if htlc.RHash != sha256.Sum256(preimage[:]) {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrInvalidSettlePreimage{preimage[:], htlc.RHash[:]}
|
2016-07-22 02:50:20 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pd := &PaymentDescriptor{
|
|
|
|
Amount: htlc.Amount,
|
2016-09-22 04:27:46 +03:00
|
|
|
RPreimage: preimage,
|
2017-10-23 02:28:30 +03:00
|
|
|
ParentIndex: htlc.HtlcIndex,
|
2017-03-06 17:00:32 +03:00
|
|
|
RHash: htlc.RHash,
|
2017-10-23 02:28:30 +03:00
|
|
|
LogIndex: lc.remoteUpdateLog.logIndex,
|
2016-07-22 02:50:20 +03:00
|
|
|
EntryType: Settle,
|
|
|
|
}
|
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
lc.remoteUpdateLog.appendUpdate(pd)
|
2018-05-26 04:39:55 +03:00
|
|
|
|
|
|
|
// With the settle added to the remote log, we'll now mark the HTLC as
|
|
|
|
// modified to prevent the remote party from accidentally attempting a
|
|
|
|
// duplicate settle.
|
|
|
|
lc.localUpdateLog.markHtlcModified(htlcIndex)
|
|
|
|
|
2016-07-22 02:50:20 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
// FailHTLC attempts to fail a targeted HTLC by its payment hash, inserting an
|
|
|
|
// entry which will remove the target log entry within the next commitment
|
2017-01-06 07:54:39 +03:00
|
|
|
// update. This method is intended to be called in order to cancel in
|
|
|
|
// _incoming_ HTLC.
|
2018-02-28 07:04:41 +03:00
|
|
|
//
|
|
|
|
// The additional arguments correspond to:
|
|
|
|
// * sourceRef: specifies the location of the Add HTLC within a forwarding
|
|
|
|
// package that this HTLC is failing. Every Fail fails exactly one Add, so
|
|
|
|
// this should never be empty in practice.
|
|
|
|
//
|
|
|
|
// * destRef: specifies the location of the Fail HTLC within another channel's
|
|
|
|
// forwarding package. This value can be nil if the corresponding Add HTLC
|
|
|
|
// was never locked into an outgoing commitment txn, or this HTLC does not
|
|
|
|
// originate as a response from the peer on the outgoing link, e.g.
|
|
|
|
// on-chain resolutions.
|
|
|
|
//
|
|
|
|
// * closeKey: identifies the circuit that should be deleted after this Fail
|
|
|
|
// HTLC is included in a commitment txn. This value should only be nil if
|
|
|
|
// the HTLC was failed locally before committing a circuit to the circuit
|
|
|
|
// map.
|
|
|
|
//
|
|
|
|
// NOTE: It is okay for sourceRef, destRef, and closeKey to be nil when unit
|
|
|
|
// testing the wallet.
|
|
|
|
func (lc *LightningChannel) FailHTLC(htlcIndex uint64, reason []byte,
|
|
|
|
sourceRef *channeldb.AddRef, destRef *channeldb.SettleFailRef,
|
|
|
|
closeKey *channeldb.CircuitKey) error {
|
2018-02-28 07:01:41 +03:00
|
|
|
|
2017-01-06 07:54:39 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
htlc := lc.remoteUpdateLog.lookupHtlc(htlcIndex)
|
|
|
|
if htlc == nil {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrUnknownHtlcIndex{lc.ShortChanID(), htlcIndex}
|
2017-01-07 01:10:21 +03:00
|
|
|
}
|
2017-01-16 14:57:26 +03:00
|
|
|
|
2018-05-26 04:40:25 +03:00
|
|
|
// Now that we know the HTLC exists, we'll ensure that we haven't
|
|
|
|
// already attempted to fail the HTLC.
|
|
|
|
if lc.remoteUpdateLog.htlcHasModification(htlcIndex) {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrHtlcIndexAlreadyFailed(htlcIndex)
|
2018-05-26 04:40:25 +03:00
|
|
|
}
|
|
|
|
|
2017-01-06 07:54:39 +03:00
|
|
|
pd := &PaymentDescriptor{
|
2018-02-28 07:04:41 +03:00
|
|
|
Amount: htlc.Amount,
|
|
|
|
RHash: htlc.RHash,
|
|
|
|
ParentIndex: htlcIndex,
|
|
|
|
LogIndex: lc.localUpdateLog.logIndex,
|
|
|
|
EntryType: Fail,
|
|
|
|
FailReason: reason,
|
|
|
|
SourceRef: sourceRef,
|
|
|
|
DestRef: destRef,
|
|
|
|
ClosedCircuitKey: closeKey,
|
2017-01-06 07:54:39 +03:00
|
|
|
}
|
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
lc.localUpdateLog.appendUpdate(pd)
|
2017-01-06 07:54:39 +03:00
|
|
|
|
2018-05-26 04:40:25 +03:00
|
|
|
// With the fail added to the remote log, we'll now mark the HTLC as
|
|
|
|
// modified to prevent ourselves from accidentally attempting a
|
|
|
|
// duplicate fail.
|
|
|
|
lc.remoteUpdateLog.markHtlcModified(htlcIndex)
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
return nil
|
2017-01-06 07:54:39 +03:00
|
|
|
}
|
|
|
|
|
2017-08-14 14:21:57 +03:00
|
|
|
// MalformedFailHTLC attempts to fail a targeted HTLC by its payment hash,
|
|
|
|
// inserting an entry which will remove the target log entry within the next
|
|
|
|
// commitment update. This method is intended to be called in order to cancel
|
|
|
|
// in _incoming_ HTLC.
|
2018-02-28 07:04:41 +03:00
|
|
|
//
|
|
|
|
// The additional sourceRef specifies the location of the Add HTLC within a
|
|
|
|
// forwarding package that this HTLC is failing. This value should never be
|
|
|
|
// empty.
|
|
|
|
//
|
|
|
|
// NOTE: It is okay for sourceRef to be nil when unit testing the wallet.
|
2017-10-24 10:48:52 +03:00
|
|
|
func (lc *LightningChannel) MalformedFailHTLC(htlcIndex uint64,
|
2018-02-28 07:04:41 +03:00
|
|
|
failCode lnwire.FailCode, shaOnionBlob [sha256.Size]byte,
|
|
|
|
sourceRef *channeldb.AddRef) error {
|
2017-10-24 10:48:52 +03:00
|
|
|
|
2017-08-14 14:21:57 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
htlc := lc.remoteUpdateLog.lookupHtlc(htlcIndex)
|
|
|
|
if htlc == nil {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrUnknownHtlcIndex{lc.ShortChanID(), htlcIndex}
|
2017-08-14 14:21:57 +03:00
|
|
|
}
|
|
|
|
|
2018-05-26 04:40:25 +03:00
|
|
|
// Now that we know the HTLC exists, we'll ensure that we haven't
|
|
|
|
// already attempted to fail the HTLC.
|
|
|
|
if lc.remoteUpdateLog.htlcHasModification(htlcIndex) {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrHtlcIndexAlreadyFailed(htlcIndex)
|
2018-05-26 04:40:25 +03:00
|
|
|
}
|
|
|
|
|
2017-08-14 14:21:57 +03:00
|
|
|
pd := &PaymentDescriptor{
|
2017-10-24 10:48:52 +03:00
|
|
|
Amount: htlc.Amount,
|
|
|
|
RHash: htlc.RHash,
|
|
|
|
ParentIndex: htlcIndex,
|
2017-08-14 14:21:57 +03:00
|
|
|
LogIndex: lc.localUpdateLog.logIndex,
|
|
|
|
EntryType: MalformedFail,
|
|
|
|
FailCode: failCode,
|
|
|
|
ShaOnionBlob: shaOnionBlob,
|
2018-02-28 07:04:41 +03:00
|
|
|
SourceRef: sourceRef,
|
2017-08-14 14:21:57 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
lc.localUpdateLog.appendUpdate(pd)
|
|
|
|
|
2018-05-26 04:40:25 +03:00
|
|
|
// With the fail added to the remote log, we'll now mark the HTLC as
|
|
|
|
// modified to prevent ourselves from accidentally attempting a
|
|
|
|
// duplicate fail.
|
|
|
|
lc.remoteUpdateLog.markHtlcModified(htlcIndex)
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
return nil
|
2017-08-14 14:21:57 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ReceiveFailHTLC attempts to cancel a targeted HTLC by its log index,
|
2017-01-06 07:54:39 +03:00
|
|
|
// inserting an entry which will remove the target log entry within the next
|
|
|
|
// commitment update. This method should be called in response to the upstream
|
2017-09-25 06:17:51 +03:00
|
|
|
// party cancelling an outgoing HTLC. The value of the failed HTLC is returned
|
|
|
|
// along with an error indicating success.
|
2017-10-24 10:48:52 +03:00
|
|
|
func (lc *LightningChannel) ReceiveFailHTLC(htlcIndex uint64, reason []byte,
|
|
|
|
) error {
|
2017-07-10 13:48:43 +03:00
|
|
|
|
2017-01-06 07:54:39 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2017-10-23 02:28:30 +03:00
|
|
|
htlc := lc.localUpdateLog.lookupHtlc(htlcIndex)
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
if htlc == nil {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrUnknownHtlcIndex{lc.ShortChanID(), htlcIndex}
|
2017-01-06 07:54:39 +03:00
|
|
|
}
|
|
|
|
|
2018-05-26 04:40:25 +03:00
|
|
|
// Now that we know the HTLC exists, we'll ensure that they haven't
|
|
|
|
// already attempted to fail the HTLC.
|
|
|
|
if lc.localUpdateLog.htlcHasModification(htlcIndex) {
|
2018-07-27 13:22:15 +03:00
|
|
|
return ErrHtlcIndexAlreadyFailed(htlcIndex)
|
2018-05-26 04:40:25 +03:00
|
|
|
}
|
|
|
|
|
2017-01-06 07:54:39 +03:00
|
|
|
pd := &PaymentDescriptor{
|
|
|
|
Amount: htlc.Amount,
|
2017-01-08 06:58:54 +03:00
|
|
|
RHash: htlc.RHash,
|
2017-10-23 02:28:30 +03:00
|
|
|
ParentIndex: htlc.HtlcIndex,
|
|
|
|
LogIndex: lc.remoteUpdateLog.logIndex,
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
EntryType: Fail,
|
2017-07-10 13:48:43 +03:00
|
|
|
FailReason: reason,
|
2017-01-06 07:54:39 +03:00
|
|
|
}
|
|
|
|
|
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.
At a high level the following modifications have been made:
* When signing we no loner include the index of the remote party’s
log
that our signature covers. Instead we include ALL of our current
updates, but only the updates of the remote party that we’ve
ACK’d.
* A pending change is considered ACK’d once a revocation message
has been received, locking in the changes in the remote party’s
commitment transaction.
* When sending a new commitment, we remember the index of our
log at that point so we can mark that portion of the log as ACK’d
once we receive a revocation message from the remote party.
* When receiving a new commitment signature, we include ALL of
the remote party’s changes that we’ve received but only our set
of changes that’ve been ACK’d by the remote party.
* Implicitly a revocation message now also implicitly serves to ACK
all the changes that were included in the CommitSig message
received before it.
The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
* Alice -> Add, Add, Add
* Alice -> Sig
* Revoke <- Bob
* Sig <- Bob
* Alice -> Revoke
One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.
Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 04:55:33 +03:00
|
|
|
lc.remoteUpdateLog.appendUpdate(pd)
|
2017-09-25 06:17:51 +03:00
|
|
|
|
2018-05-26 04:40:25 +03:00
|
|
|
// With the fail added to the remote log, we'll now mark the HTLC as
|
|
|
|
// modified to prevent ourselves from accidentally attempting a
|
|
|
|
// duplicate fail.
|
|
|
|
lc.localUpdateLog.markHtlcModified(htlcIndex)
|
|
|
|
|
2017-10-24 10:48:52 +03:00
|
|
|
return nil
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ChannelPoint returns the outpoint of the original funding transaction which
|
|
|
|
// created this active channel. This outpoint is used throughout various
|
2017-01-13 08:01:50 +03:00
|
|
|
// subsystems to uniquely identify an open channel.
|
2016-07-06 03:01:55 +03:00
|
|
|
func (lc *LightningChannel) ChannelPoint() *wire.OutPoint {
|
2017-07-30 22:25:41 +03:00
|
|
|
return &lc.channelState.FundingOutpoint
|
2016-07-06 03:01:55 +03:00
|
|
|
}
|
2016-01-06 00:01:42 +03:00
|
|
|
|
2017-06-17 00:25:07 +03:00
|
|
|
// ShortChanID returns the short channel ID for the channel. The short channel
|
|
|
|
// ID encodes the exact location in the main chain that the original
|
|
|
|
// funding output can be found.
|
|
|
|
func (lc *LightningChannel) ShortChanID() lnwire.ShortChannelID {
|
2018-05-02 02:27:20 +03:00
|
|
|
return lc.channelState.ShortChanID()
|
2017-06-17 00:25:07 +03:00
|
|
|
}
|
|
|
|
|
2019-12-03 12:38:29 +03:00
|
|
|
// LocalUpfrontShutdownScript returns the local upfront shutdown script for the
|
|
|
|
// channel. If it was not set, an empty byte array is returned.
|
|
|
|
func (lc *LightningChannel) LocalUpfrontShutdownScript() lnwire.DeliveryAddress {
|
2019-12-03 12:38:29 +03:00
|
|
|
return lc.channelState.LocalShutdownScript
|
2019-12-03 12:38:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// RemoteUpfrontShutdownScript returns the remote upfront shutdown script for the
|
|
|
|
// channel. If it was not set, an empty byte array is returned.
|
|
|
|
func (lc *LightningChannel) RemoteUpfrontShutdownScript() lnwire.DeliveryAddress {
|
2019-12-03 12:38:29 +03:00
|
|
|
return lc.channelState.RemoteShutdownScript
|
2019-12-03 12:38:29 +03:00
|
|
|
}
|
|
|
|
|
2017-11-10 10:06:10 +03:00
|
|
|
// getSignedCommitTx function take the latest commitment transaction and
|
|
|
|
// populate it with witness data.
|
2017-05-16 04:12:52 +03:00
|
|
|
func (lc *LightningChannel) getSignedCommitTx() (*wire.MsgTx, error) {
|
|
|
|
// Fetch the current commitment transaction, along with their signature
|
|
|
|
// for the transaction.
|
2017-11-10 10:06:10 +03:00
|
|
|
localCommit := lc.channelState.LocalCommitment
|
2019-10-01 05:50:31 +03:00
|
|
|
commitTx := localCommit.CommitTx.Copy()
|
2017-11-10 10:06:10 +03:00
|
|
|
theirSig := append(localCommit.CommitSig, byte(txscript.SigHashAll))
|
2017-05-16 04:12:52 +03:00
|
|
|
|
|
|
|
// With this, we then generate the full witness so the caller can
|
|
|
|
// broadcast a fully signed transaction.
|
2017-11-10 10:06:10 +03:00
|
|
|
lc.signDesc.SigHashes = txscript.NewTxSigHashes(commitTx)
|
2018-04-30 01:40:59 +03:00
|
|
|
ourSigRaw, err := lc.Signer.SignOutputRaw(commitTx, lc.signDesc)
|
2017-05-16 04:12:52 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ourSig := append(ourSigRaw, byte(txscript.SigHashAll))
|
|
|
|
|
|
|
|
// With the final signature generated, create the witness stack
|
|
|
|
// required to spend from the multi-sig output.
|
2020-01-06 13:42:02 +03:00
|
|
|
ourKey := lc.channelState.LocalChanCfg.MultiSigKey.PubKey.
|
|
|
|
SerializeCompressed()
|
|
|
|
theirKey := lc.channelState.RemoteChanCfg.MultiSigKey.PubKey.
|
|
|
|
SerializeCompressed()
|
2017-05-16 04:12:52 +03:00
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
commitTx.TxIn[0].Witness = input.SpendMultiSig(
|
2017-09-26 07:47:39 +03:00
|
|
|
lc.signDesc.WitnessScript, ourKey,
|
2017-11-10 10:06:10 +03:00
|
|
|
ourSig, theirKey, theirSig,
|
|
|
|
)
|
2017-05-16 04:12:52 +03:00
|
|
|
|
2017-11-10 10:06:10 +03:00
|
|
|
return commitTx, nil
|
2017-07-30 22:25:41 +03:00
|
|
|
}
|
2017-07-30 23:20:58 +03:00
|
|
|
|
2018-01-17 05:17:18 +03:00
|
|
|
// CommitOutputResolution carries the necessary information required to allow
|
2020-03-06 18:11:46 +03:00
|
|
|
// us to sweep our commitment output in the case that either party goes to
|
|
|
|
// chain.
|
2018-01-17 05:17:18 +03:00
|
|
|
type CommitOutputResolution struct {
|
|
|
|
// SelfOutPoint is the full outpoint that points to out pay-to-self
|
|
|
|
// output within the closing commitment transaction.
|
|
|
|
SelfOutPoint wire.OutPoint
|
|
|
|
|
|
|
|
// SelfOutputSignDesc is a fully populated sign descriptor capable of
|
|
|
|
// generating a valid signature to sweep the output paying to us.
|
2019-01-16 17:47:43 +03:00
|
|
|
SelfOutputSignDesc input.SignDescriptor
|
2018-01-17 05:17:18 +03:00
|
|
|
|
|
|
|
// MaturityDelay is the relative time-lock, in blocks for all outputs
|
|
|
|
// that pay to the local party within the broadcast commitment
|
2020-03-06 18:11:46 +03:00
|
|
|
// transaction.
|
2018-01-17 05:17:18 +03:00
|
|
|
MaturityDelay uint32
|
|
|
|
}
|
|
|
|
|
2017-07-30 23:20:58 +03:00
|
|
|
// UnilateralCloseSummary describes the details of a detected unilateral
|
|
|
|
// channel closure. This includes the information about with which
|
|
|
|
// transactions, and block the channel was unilaterally closed, as well as
|
|
|
|
// summarization details concerning the _state_ of the channel at the point of
|
|
|
|
// channel closure. Additionally, if we had a commitment output above dust on
|
|
|
|
// the remote party's commitment transaction, the necessary a SignDescriptor
|
|
|
|
// with the material necessary to seep the output are returned. Finally, if we
|
|
|
|
// had any outgoing HTLC's within the commitment transaction, then an
|
|
|
|
// OutgoingHtlcResolution for each output will included.
|
|
|
|
type UnilateralCloseSummary struct {
|
2018-04-11 16:16:50 +03:00
|
|
|
// SpendDetail is a struct that describes how and when the funding
|
2017-07-30 23:20:58 +03:00
|
|
|
// output was spent.
|
|
|
|
*chainntnfs.SpendDetail
|
|
|
|
|
|
|
|
// ChannelCloseSummary is a struct describing the final state of the
|
|
|
|
// channel and in which state is was closed.
|
|
|
|
channeldb.ChannelCloseSummary
|
|
|
|
|
2018-01-17 05:17:18 +03:00
|
|
|
// CommitResolution contains all the data required to sweep the output
|
|
|
|
// to ourselves. If this is our commitment transaction, then we'll need
|
|
|
|
// to wait a time delay before we can sweep the output.
|
|
|
|
//
|
|
|
|
// NOTE: If our commitment delivery output is below the dust limit,
|
|
|
|
// then this will be nil.
|
|
|
|
CommitResolution *CommitOutputResolution
|
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
// HtlcResolutions contains a fully populated HtlcResolutions struct
|
|
|
|
// which contains all the data required to sweep any outgoing HTLC's,
|
|
|
|
// and also any incoming HTLC's that we know the pre-image to.
|
|
|
|
HtlcResolutions *HtlcResolutions
|
2018-01-17 05:17:18 +03:00
|
|
|
|
2018-01-19 00:49:35 +03:00
|
|
|
// RemoteCommit is the exact commitment state that the remote party
|
|
|
|
// broadcast.
|
|
|
|
RemoteCommit channeldb.ChannelCommitment
|
2019-12-13 13:14:22 +03:00
|
|
|
|
|
|
|
// AnchorResolution contains the data required to sweep our anchor
|
|
|
|
// output. If the channel type doesn't include anchors, the value of
|
|
|
|
// this field will be nil.
|
|
|
|
AnchorResolution *AnchorResolution
|
2018-01-19 00:49:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewUnilateralCloseSummary creates a new summary that provides the caller
|
|
|
|
// with all the information required to claim all funds on chain in the event
|
2018-07-12 12:02:52 +03:00
|
|
|
// that the remote party broadcasts their commitment. The commitPoint argument
|
|
|
|
// should be set to the per_commitment_point corresponding to the spending
|
|
|
|
// commitment.
|
2018-07-12 12:02:52 +03:00
|
|
|
//
|
|
|
|
// NOTE: The remoteCommit argument should be set to the stored commitment for
|
|
|
|
// this particular state. If we don't have the commitment stored (should only
|
|
|
|
// happen in case we have lost state) it should be set to an empty struct, in
|
|
|
|
// which case we will attempt to sweep the non-HTLC output using the passed
|
|
|
|
// commitPoint.
|
2019-01-16 17:47:43 +03:00
|
|
|
func NewUnilateralCloseSummary(chanState *channeldb.OpenChannel, signer input.Signer,
|
2019-04-15 15:24:43 +03:00
|
|
|
commitSpend *chainntnfs.SpendDetail,
|
2018-04-30 01:40:59 +03:00
|
|
|
remoteCommit channeldb.ChannelCommitment,
|
2018-07-12 12:02:52 +03:00
|
|
|
commitPoint *btcec.PublicKey) (*UnilateralCloseSummary, error) {
|
2018-01-19 00:49:35 +03:00
|
|
|
|
|
|
|
// First, we'll generate the commitment point and the revocation point
|
2018-07-12 12:02:52 +03:00
|
|
|
// so we can re-construct the HTLC state and also our payment key.
|
2019-09-17 05:06:19 +03:00
|
|
|
keyRing := DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
commitPoint, false, chanState.ChanType,
|
|
|
|
&chanState.LocalChanCfg, &chanState.RemoteChanCfg,
|
2018-01-19 00:49:35 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// Next, we'll obtain HTLC resolutions for all the outgoing HTLC's we
|
|
|
|
// had on their commitment transaction.
|
|
|
|
htlcResolutions, err := extractHtlcResolutions(
|
2019-10-31 05:43:05 +03:00
|
|
|
chainfee.SatPerKWeight(remoteCommit.FeePerKw), false, signer,
|
2019-03-11 02:42:12 +03:00
|
|
|
remoteCommit.Htlcs, keyRing, &chanState.LocalChanCfg,
|
|
|
|
&chanState.RemoteChanCfg, *commitSpend.SpenderTxHash,
|
2020-03-06 18:11:45 +03:00
|
|
|
chanState.ChanType,
|
2018-01-19 00:49:35 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
2019-03-11 02:42:12 +03:00
|
|
|
return nil, fmt.Errorf("unable to create htlc "+
|
|
|
|
"resolutions: %v", err)
|
2018-01-19 00:49:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
commitTxBroadcast := commitSpend.SpendingTx
|
|
|
|
|
|
|
|
// Before we can generate the proper sign descriptor, we'll need to
|
|
|
|
// locate the output index of our non-delayed output on the commitment
|
|
|
|
// transaction.
|
2020-03-06 18:11:46 +03:00
|
|
|
selfScript, maturityDelay, err := CommitScriptToRemote(
|
|
|
|
chanState.ChanType, keyRing.ToRemoteKey,
|
2020-01-06 13:42:04 +03:00
|
|
|
)
|
2018-01-19 00:49:35 +03:00
|
|
|
if err != nil {
|
2019-03-11 02:42:12 +03:00
|
|
|
return nil, fmt.Errorf("unable to create self commit "+
|
|
|
|
"script: %v", err)
|
2018-01-19 00:49:35 +03:00
|
|
|
}
|
2018-07-12 12:02:52 +03:00
|
|
|
|
|
|
|
var (
|
|
|
|
selfPoint *wire.OutPoint
|
|
|
|
localBalance int64
|
|
|
|
)
|
|
|
|
|
2018-01-19 00:49:35 +03:00
|
|
|
for outputIndex, txOut := range commitTxBroadcast.TxOut {
|
2020-01-06 13:42:04 +03:00
|
|
|
if bytes.Equal(txOut.PkScript, selfScript.PkScript) {
|
2018-01-19 00:49:35 +03:00
|
|
|
selfPoint = &wire.OutPoint{
|
|
|
|
Hash: *commitSpend.SpenderTxHash,
|
|
|
|
Index: uint32(outputIndex),
|
|
|
|
}
|
2018-07-12 12:02:52 +03:00
|
|
|
localBalance = txOut.Value
|
2018-01-19 00:49:35 +03:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// With the HTLC's taken care of, we'll generate the sign descriptor
|
|
|
|
// necessary to sweep our commitment output, but only if we had a
|
|
|
|
// non-trimmed balance.
|
|
|
|
var commitResolution *CommitOutputResolution
|
|
|
|
if selfPoint != nil {
|
|
|
|
localPayBase := chanState.LocalChanCfg.PaymentBasePoint
|
|
|
|
commitResolution = &CommitOutputResolution{
|
|
|
|
SelfOutPoint: *selfPoint,
|
2019-01-16 17:47:43 +03:00
|
|
|
SelfOutputSignDesc: input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localPayBase,
|
2018-01-19 00:49:35 +03:00
|
|
|
SingleTweak: keyRing.LocalCommitKeyTweak,
|
2020-01-06 13:42:04 +03:00
|
|
|
WitnessScript: selfScript.WitnessScript,
|
2018-01-19 00:49:35 +03:00
|
|
|
Output: &wire.TxOut{
|
2018-07-12 12:02:52 +03:00
|
|
|
Value: localBalance,
|
2020-01-06 13:42:04 +03:00
|
|
|
PkScript: selfScript.PkScript,
|
2018-01-19 00:49:35 +03:00
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
},
|
2020-03-06 18:11:46 +03:00
|
|
|
MaturityDelay: maturityDelay,
|
2018-01-19 00:49:35 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
closeSummary := channeldb.ChannelCloseSummary{
|
2018-08-14 05:15:54 +03:00
|
|
|
ChanPoint: chanState.FundingOutpoint,
|
|
|
|
ChainHash: chanState.ChainHash,
|
|
|
|
ClosingTXID: *commitSpend.SpenderTxHash,
|
|
|
|
CloseHeight: uint32(commitSpend.SpendingHeight),
|
|
|
|
RemotePub: chanState.IdentityPub,
|
|
|
|
Capacity: chanState.Capacity,
|
|
|
|
SettledBalance: btcutil.Amount(localBalance),
|
|
|
|
CloseType: channeldb.RemoteForceClose,
|
|
|
|
IsPending: true,
|
|
|
|
RemoteCurrentRevocation: chanState.RemoteCurrentRevocation,
|
|
|
|
RemoteNextRevocation: chanState.RemoteNextRevocation,
|
2018-10-19 23:48:59 +03:00
|
|
|
ShortChanID: chanState.ShortChanID(),
|
2018-08-14 05:15:54 +03:00
|
|
|
LocalChanConfig: chanState.LocalChanCfg,
|
2018-01-19 00:49:35 +03:00
|
|
|
}
|
|
|
|
|
2018-11-20 17:09:45 +03:00
|
|
|
// Attempt to add a channel sync message to the close summary.
|
2019-09-11 12:15:57 +03:00
|
|
|
chanSync, err := chanState.ChanSyncMsg()
|
2018-11-20 17:09:45 +03:00
|
|
|
if err != nil {
|
|
|
|
walletLog.Errorf("ChannelPoint(%v): unable to create channel sync "+
|
|
|
|
"message: %v", chanState.FundingOutpoint, err)
|
|
|
|
} else {
|
|
|
|
closeSummary.LastChanSyncMsg = chanSync
|
|
|
|
}
|
|
|
|
|
2019-12-13 13:14:22 +03:00
|
|
|
anchorResolution, err := NewAnchorResolution(
|
|
|
|
chanState, commitTxBroadcast,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-01-19 00:49:35 +03:00
|
|
|
return &UnilateralCloseSummary{
|
|
|
|
SpendDetail: commitSpend,
|
|
|
|
ChannelCloseSummary: closeSummary,
|
|
|
|
CommitResolution: commitResolution,
|
|
|
|
HtlcResolutions: htlcResolutions,
|
|
|
|
RemoteCommit: remoteCommit,
|
2019-12-13 13:14:22 +03:00
|
|
|
AnchorResolution: anchorResolution,
|
2018-01-19 00:49:35 +03:00
|
|
|
}, nil
|
2018-01-17 05:17:18 +03:00
|
|
|
}
|
2017-07-31 03:42:09 +03:00
|
|
|
|
2018-01-17 05:23:41 +03:00
|
|
|
// IncomingHtlcResolution houses the information required to sweep any incoming
|
|
|
|
// HTLC's that we know the preimage to. We'll need to sweep an HTLC manually
|
|
|
|
// using this struct if we need to go on-chain for any reason, or if we detect
|
|
|
|
// that the remote party broadcasts their commitment transaction.
|
|
|
|
type IncomingHtlcResolution struct {
|
2019-04-15 15:24:43 +03:00
|
|
|
// Preimage is the preimage that will be used to satisfy the contract of
|
|
|
|
// the HTLC.
|
2018-01-17 05:23:41 +03:00
|
|
|
//
|
2019-04-15 15:24:43 +03:00
|
|
|
// NOTE: This field will only be populated in the incoming contest
|
|
|
|
// resolver.
|
2018-01-17 05:23:41 +03:00
|
|
|
Preimage [32]byte
|
|
|
|
|
|
|
|
// SignedSuccessTx is the fully signed HTLC success transaction. This
|
|
|
|
// transaction (if non-nil) can be broadcast immediately. After a csv
|
|
|
|
// delay (included below), then the output created by this transactions
|
|
|
|
// can be swept on-chain.
|
|
|
|
//
|
|
|
|
// NOTE: If this field is nil, then this indicates that we don't need
|
|
|
|
// to go to the second level to claim this HTLC. Instead, it can be
|
|
|
|
// claimed directly from the outpoint listed below.
|
|
|
|
SignedSuccessTx *wire.MsgTx
|
|
|
|
|
|
|
|
// CsvDelay is the relative time lock (expressed in blocks) that must
|
|
|
|
// pass after the SignedSuccessTx is confirmed in the chain before the
|
|
|
|
// output can be swept.
|
|
|
|
//
|
2020-03-06 18:11:47 +03:00
|
|
|
// NOTE: If SignedTimeoutTx is nil, then this field denotes the CSV
|
|
|
|
// delay needed to spend from the commitment transaction.
|
2018-01-17 05:23:41 +03:00
|
|
|
CsvDelay uint32
|
2017-07-30 23:20:58 +03:00
|
|
|
|
2018-01-17 05:23:41 +03:00
|
|
|
// ClaimOutpoint is the final outpoint that needs to be spent in order
|
|
|
|
// to fully sweep the HTLC. The SignDescriptor below should be used to
|
|
|
|
// spend this outpoint. In the case of a second-level HTLC (non-nil
|
|
|
|
// SignedTimeoutTx), then we'll be spending a new transaction.
|
|
|
|
// Otherwise, it'll be an output in the commitment transaction.
|
|
|
|
ClaimOutpoint wire.OutPoint
|
2017-09-27 04:00:16 +03:00
|
|
|
|
2018-01-17 05:23:41 +03:00
|
|
|
// SweepSignDesc is a sign descriptor that has been populated with the
|
|
|
|
// necessary items required to spend the sole output of the above
|
|
|
|
// transaction.
|
2019-01-16 17:47:43 +03:00
|
|
|
SweepSignDesc input.SignDescriptor
|
2017-07-30 23:20:58 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 05:26:11 +03:00
|
|
|
// OutgoingHtlcResolution houses the information necessary to sweep any
|
|
|
|
// outgoing HTLC's after their contract has expired. This struct will be needed
|
|
|
|
// in one of two cases: the local party force closes the commitment transaction
|
|
|
|
// or the remote party unilaterally closes with their version of the commitment
|
2017-07-30 23:20:58 +03:00
|
|
|
// transaction.
|
|
|
|
type OutgoingHtlcResolution struct {
|
|
|
|
// Expiry the absolute timeout of the HTLC. This value is expressed in
|
|
|
|
// block height, meaning after this height the HLTC can be swept.
|
|
|
|
Expiry uint32
|
|
|
|
|
|
|
|
// SignedTimeoutTx is the fully signed HTLC timeout transaction. This
|
|
|
|
// must be broadcast immediately after timeout has passed. Once this
|
|
|
|
// has been confirmed, the HTLC output will transition into the
|
|
|
|
// delay+claim state.
|
2018-01-17 05:26:11 +03:00
|
|
|
//
|
|
|
|
// NOTE: If this field is nil, then this indicates that we don't need
|
|
|
|
// to go to the second level to claim this HTLC. Instead, it can be
|
|
|
|
// claimed directly from the outpoint listed below.
|
2017-07-30 23:20:58 +03:00
|
|
|
SignedTimeoutTx *wire.MsgTx
|
|
|
|
|
2018-01-17 05:26:11 +03:00
|
|
|
// CsvDelay is the relative time lock (expressed in blocks) that must
|
|
|
|
// pass after the SignedTimeoutTx is confirmed in the chain before the
|
|
|
|
// output can be swept.
|
|
|
|
//
|
2020-03-06 18:11:47 +03:00
|
|
|
// NOTE: If SignedTimeoutTx is nil, then this field denotes the CSV
|
|
|
|
// delay needed to spend from the commitment transaction.
|
2018-01-17 05:26:11 +03:00
|
|
|
CsvDelay uint32
|
|
|
|
|
|
|
|
// ClaimOutpoint is the final outpoint that needs to be spent in order
|
|
|
|
// to fully sweep the HTLC. The SignDescriptor below should be used to
|
|
|
|
// spend this outpoint. In the case of a second-level HTLC (non-nil
|
|
|
|
// SignedTimeoutTx), then we'll be spending a new transaction.
|
|
|
|
// Otherwise, it'll be an output in the commitment transaction.
|
|
|
|
ClaimOutpoint wire.OutPoint
|
|
|
|
|
2017-07-30 23:20:58 +03:00
|
|
|
// SweepSignDesc is a sign descriptor that has been populated with the
|
|
|
|
// necessary items required to spend the sole output of the above
|
|
|
|
// transaction.
|
2019-01-16 17:47:43 +03:00
|
|
|
SweepSignDesc input.SignDescriptor
|
2017-07-30 23:20:58 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
// HtlcResolutions contains the items necessary to sweep HTLC's on chain
|
|
|
|
// directly from a commitment transaction. We'll use this in case either party
|
|
|
|
// goes broadcasts a commitment transaction with live HTLC's.
|
|
|
|
type HtlcResolutions struct {
|
|
|
|
// IncomingHTLCs contains a set of structs that can be used to sweep
|
|
|
|
// all the incoming HTL'C that we know the preimage to.
|
|
|
|
IncomingHTLCs []IncomingHtlcResolution
|
|
|
|
|
|
|
|
// OutgoingHTLCs contains a set of structs that contains all the info
|
|
|
|
// needed to sweep an outgoing HTLC we've sent to the remote party
|
|
|
|
// after an absolute delay has expired.
|
|
|
|
OutgoingHTLCs []OutgoingHtlcResolution
|
|
|
|
}
|
|
|
|
|
2018-01-17 05:26:11 +03:00
|
|
|
// newOutgoingHtlcResolution generates a new HTLC resolution capable of
|
|
|
|
// allowing the caller to sweep an outgoing HTLC present on either their, or
|
|
|
|
// the remote party's commitment transaction.
|
2019-10-31 05:43:05 +03:00
|
|
|
func newOutgoingHtlcResolution(signer input.Signer,
|
|
|
|
localChanCfg *channeldb.ChannelConfig, commitHash chainhash.Hash,
|
|
|
|
htlc *channeldb.HTLC, keyRing *CommitmentKeyRing,
|
|
|
|
feePerKw chainfee.SatPerKWeight, csvDelay uint32,
|
2020-03-06 18:11:45 +03:00
|
|
|
localCommit bool, chanType channeldb.ChannelType) (*OutgoingHtlcResolution, error) {
|
2017-07-30 23:20:58 +03:00
|
|
|
|
|
|
|
op := wire.OutPoint{
|
|
|
|
Hash: commitHash,
|
|
|
|
Index: uint32(htlc.OutputIndex),
|
|
|
|
}
|
|
|
|
|
2020-03-06 18:11:44 +03:00
|
|
|
// First, we'll re-generate the script used to send the HTLC to
|
|
|
|
// the remote party within their commitment transaction.
|
|
|
|
htlcScriptHash, htlcScript, err := genHtlcScript(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, false, localCommit, htlc.RefundTimeout, htlc.RHash,
|
|
|
|
keyRing,
|
2020-03-06 18:11:44 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-01-17 05:26:11 +03:00
|
|
|
// If we're spending this HTLC output from the remote node's
|
|
|
|
// commitment, then we won't need to go to the second level as our
|
|
|
|
// outputs don't have a CSV delay.
|
|
|
|
if !localCommit {
|
|
|
|
// With the script generated, we can completely populated the
|
|
|
|
// SignDescriptor needed to sweep the output.
|
|
|
|
return &OutgoingHtlcResolution{
|
|
|
|
Expiry: htlc.RefundTimeout,
|
|
|
|
ClaimOutpoint: op,
|
2019-01-16 17:47:43 +03:00
|
|
|
SweepSignDesc: input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.HtlcBasePoint,
|
2018-01-19 00:45:30 +03:00
|
|
|
SingleTweak: keyRing.LocalHtlcKeyTweak,
|
2020-03-06 18:11:44 +03:00
|
|
|
WitnessScript: htlcScript,
|
2018-01-17 05:26:11 +03:00
|
|
|
Output: &wire.TxOut{
|
|
|
|
PkScript: htlcScriptHash,
|
|
|
|
Value: int64(htlc.Amt.ToSatoshis()),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
},
|
2020-03-06 18:11:47 +03:00
|
|
|
CsvDelay: HtlcSecondLevelInputSequence(chanType),
|
2018-01-17 05:26:11 +03:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, we'll need to craft a second level HTLC transaction, as
|
|
|
|
// well as a sign desc to sweep after the CSV delay.
|
|
|
|
|
2017-07-30 23:20:58 +03:00
|
|
|
// In order to properly reconstruct the HTLC transaction, we'll need to
|
|
|
|
// re-calculate the fee required at this state, so we can add the
|
|
|
|
// correct output value amount to the transaction.
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee := HtlcTimeoutFee(chanType, feePerKw)
|
2017-08-22 09:20:29 +03:00
|
|
|
secondLevelOutputAmt := htlc.Amt.ToSatoshis() - htlcFee
|
2017-07-30 23:20:58 +03:00
|
|
|
|
|
|
|
// With the fee calculated, re-construct the second level timeout
|
|
|
|
// transaction.
|
2017-09-27 05:03:04 +03:00
|
|
|
timeoutTx, err := createHtlcTimeoutTx(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, op, secondLevelOutputAmt, htlc.RefundTimeout,
|
|
|
|
csvDelay, keyRing.RevocationKey, keyRing.ToLocalKey,
|
2017-07-30 23:20:58 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// With the transaction created, we can generate a sign descriptor
|
|
|
|
// that's capable of generating the signature required to spend the
|
|
|
|
// HTLC output using the timeout transaction.
|
2019-01-16 17:47:43 +03:00
|
|
|
timeoutSignDesc := input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.HtlcBasePoint,
|
2018-01-19 00:45:30 +03:00
|
|
|
SingleTweak: keyRing.LocalHtlcKeyTweak,
|
2020-03-06 18:11:44 +03:00
|
|
|
WitnessScript: htlcScript,
|
2017-07-30 23:20:58 +03:00
|
|
|
Output: &wire.TxOut{
|
2017-08-22 09:20:29 +03:00
|
|
|
Value: int64(htlc.Amt.ToSatoshis()),
|
2017-07-30 23:20:58 +03:00
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
SigHashes: txscript.NewTxSigHashes(timeoutTx),
|
|
|
|
InputIndex: 0,
|
|
|
|
}
|
|
|
|
|
|
|
|
// With the sign desc created, we can now construct the full witness
|
|
|
|
// for the timeout transaction, and populate it as well.
|
2020-03-06 18:11:47 +03:00
|
|
|
sigHashType := HtlcSigHashType(chanType)
|
2019-01-16 17:47:43 +03:00
|
|
|
timeoutWitness, err := input.SenderHtlcSpendTimeout(
|
2020-03-06 18:11:47 +03:00
|
|
|
htlc.Signature, sigHashType, signer, &timeoutSignDesc, timeoutTx,
|
2018-07-18 05:22:17 +03:00
|
|
|
)
|
2017-07-30 23:20:58 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
timeoutTx.TxIn[0].Witness = timeoutWitness
|
|
|
|
|
|
|
|
// Finally, we'll generate the script output that the timeout
|
|
|
|
// transaction creates so we can generate the signDesc required to
|
|
|
|
// complete the claim process after a delay period.
|
2019-01-16 17:47:43 +03:00
|
|
|
htlcSweepScript, err := input.SecondLevelHtlcScript(
|
2020-01-06 13:42:04 +03:00
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey, csvDelay,
|
2017-09-27 05:03:04 +03:00
|
|
|
)
|
2017-07-30 23:20:58 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-06 18:11:44 +03:00
|
|
|
htlcSweepScriptHash, err := input.WitnessScriptHash(htlcSweepScript)
|
2017-09-30 00:28:10 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-07-30 23:20:58 +03:00
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
localDelayTweak := input.SingleTweakBytes(
|
2018-02-18 02:17:40 +03:00
|
|
|
keyRing.CommitPoint, localChanCfg.DelayBasePoint.PubKey,
|
|
|
|
)
|
2017-07-30 23:20:58 +03:00
|
|
|
return &OutgoingHtlcResolution{
|
|
|
|
Expiry: htlc.RefundTimeout,
|
|
|
|
SignedTimeoutTx: timeoutTx,
|
2018-01-17 05:23:41 +03:00
|
|
|
CsvDelay: csvDelay,
|
|
|
|
ClaimOutpoint: wire.OutPoint{
|
|
|
|
Hash: timeoutTx.TxHash(),
|
|
|
|
Index: 0,
|
|
|
|
},
|
2019-01-16 17:47:43 +03:00
|
|
|
SweepSignDesc: input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.DelayBasePoint,
|
2018-01-17 05:23:41 +03:00
|
|
|
SingleTweak: localDelayTweak,
|
|
|
|
WitnessScript: htlcSweepScript,
|
|
|
|
Output: &wire.TxOut{
|
2020-03-06 18:11:44 +03:00
|
|
|
PkScript: htlcSweepScriptHash,
|
2018-01-17 05:23:41 +03:00
|
|
|
Value: int64(secondLevelOutputAmt),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
},
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// newIncomingHtlcResolution creates a new HTLC resolution capable of allowing
|
|
|
|
// the caller to sweep an incoming HTLC. If the HTLC is on the caller's
|
|
|
|
// commitment transaction, then they'll need to broadcast a second-level
|
|
|
|
// transaction before sweeping the output (and incur a CSV delay). Otherwise,
|
|
|
|
// they can just sweep the output immediately with knowledge of the pre-image.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef) consolidate code with above func
|
2020-03-06 18:11:45 +03:00
|
|
|
func newIncomingHtlcResolution(signer input.Signer,
|
|
|
|
localChanCfg *channeldb.ChannelConfig, commitHash chainhash.Hash,
|
|
|
|
htlc *channeldb.HTLC, keyRing *CommitmentKeyRing,
|
|
|
|
feePerKw chainfee.SatPerKWeight, csvDelay uint32, localCommit bool,
|
|
|
|
chanType channeldb.ChannelType) (*IncomingHtlcResolution, error) {
|
2018-01-17 05:23:41 +03:00
|
|
|
|
|
|
|
op := wire.OutPoint{
|
|
|
|
Hash: commitHash,
|
|
|
|
Index: uint32(htlc.OutputIndex),
|
|
|
|
}
|
|
|
|
|
2020-03-06 18:11:44 +03:00
|
|
|
// First, we'll re-generate the script the remote party used to
|
|
|
|
// send the HTLC to us in their commitment transaction.
|
|
|
|
htlcScriptHash, htlcScript, err := genHtlcScript(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, true, localCommit, htlc.RefundTimeout, htlc.RHash,
|
|
|
|
keyRing,
|
2020-03-06 18:11:44 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-01-17 05:23:41 +03:00
|
|
|
// If we're spending this output from the remote node's commitment,
|
|
|
|
// then we can skip the second layer and spend the output directly.
|
|
|
|
if !localCommit {
|
|
|
|
// With the script generated, we can completely populated the
|
|
|
|
// SignDescriptor needed to sweep the output.
|
|
|
|
return &IncomingHtlcResolution{
|
|
|
|
ClaimOutpoint: op,
|
2019-01-16 17:47:43 +03:00
|
|
|
SweepSignDesc: input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.HtlcBasePoint,
|
2018-01-19 00:45:30 +03:00
|
|
|
SingleTweak: keyRing.LocalHtlcKeyTweak,
|
2020-03-06 18:11:44 +03:00
|
|
|
WitnessScript: htlcScript,
|
2018-01-17 05:23:41 +03:00
|
|
|
Output: &wire.TxOut{
|
|
|
|
PkScript: htlcScriptHash,
|
|
|
|
Value: int64(htlc.Amt.ToSatoshis()),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
},
|
2020-03-06 18:11:47 +03:00
|
|
|
CsvDelay: HtlcSecondLevelInputSequence(chanType),
|
2018-01-17 05:23:41 +03:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, we'll need to go to the second level to sweep this HTLC.
|
|
|
|
|
|
|
|
// First, we'll reconstruct the original HTLC success transaction,
|
|
|
|
// taking into account the fee rate used.
|
2020-03-06 18:11:49 +03:00
|
|
|
htlcFee := HtlcSuccessFee(chanType, feePerKw)
|
2018-01-17 05:23:41 +03:00
|
|
|
secondLevelOutputAmt := htlc.Amt.ToSatoshis() - htlcFee
|
|
|
|
successTx, err := createHtlcSuccessTx(
|
2020-03-06 18:11:45 +03:00
|
|
|
chanType, op, secondLevelOutputAmt, csvDelay,
|
2020-01-06 13:42:04 +03:00
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey,
|
2018-01-17 05:23:41 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Once we've created the second-level transaction, we'll generate the
|
|
|
|
// SignDesc needed spend the HTLC output using the success transaction.
|
2019-01-16 17:47:43 +03:00
|
|
|
successSignDesc := input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.HtlcBasePoint,
|
2018-01-19 00:45:30 +03:00
|
|
|
SingleTweak: keyRing.LocalHtlcKeyTweak,
|
2020-03-06 18:11:44 +03:00
|
|
|
WitnessScript: htlcScript,
|
2018-01-17 05:23:41 +03:00
|
|
|
Output: &wire.TxOut{
|
|
|
|
Value: int64(htlc.Amt.ToSatoshis()),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
SigHashes: txscript.NewTxSigHashes(successTx),
|
|
|
|
InputIndex: 0,
|
|
|
|
}
|
|
|
|
|
2019-04-15 15:24:43 +03:00
|
|
|
// Next, we'll construct the full witness needed to satisfy the input of
|
|
|
|
// the success transaction. Don't specify the preimage yet. The preimage
|
|
|
|
// will be supplied by the contract resolver, either directly or when it
|
|
|
|
// becomes known.
|
2020-03-06 18:11:47 +03:00
|
|
|
sigHashType := HtlcSigHashType(chanType)
|
2019-01-16 17:47:43 +03:00
|
|
|
successWitness, err := input.ReceiverHtlcSpendRedeem(
|
2020-03-06 18:11:47 +03:00
|
|
|
htlc.Signature, sigHashType, nil, signer, &successSignDesc,
|
|
|
|
successTx,
|
2018-01-17 05:23:41 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
successTx.TxIn[0].Witness = successWitness
|
|
|
|
|
|
|
|
// Finally, we'll generate the script that the second-level transaction
|
|
|
|
// creates so we can generate the proper signDesc to sweep it after the
|
|
|
|
// CSV delay has passed.
|
2019-01-16 17:47:43 +03:00
|
|
|
htlcSweepScript, err := input.SecondLevelHtlcScript(
|
2020-01-06 13:42:04 +03:00
|
|
|
keyRing.RevocationKey, keyRing.ToLocalKey, csvDelay,
|
2018-01-17 05:23:41 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-06 18:11:44 +03:00
|
|
|
htlcSweepScriptHash, err := input.WitnessScriptHash(htlcSweepScript)
|
2018-01-17 05:23:41 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
localDelayTweak := input.SingleTweakBytes(
|
2018-02-18 02:17:40 +03:00
|
|
|
keyRing.CommitPoint, localChanCfg.DelayBasePoint.PubKey,
|
2018-01-19 00:45:30 +03:00
|
|
|
)
|
2018-01-17 05:23:41 +03:00
|
|
|
return &IncomingHtlcResolution{
|
|
|
|
SignedSuccessTx: successTx,
|
|
|
|
CsvDelay: csvDelay,
|
|
|
|
ClaimOutpoint: wire.OutPoint{
|
|
|
|
Hash: successTx.TxHash(),
|
|
|
|
Index: 0,
|
|
|
|
},
|
2019-01-16 17:47:43 +03:00
|
|
|
SweepSignDesc: input.SignDescriptor{
|
2018-02-18 02:17:40 +03:00
|
|
|
KeyDesc: localChanCfg.DelayBasePoint,
|
2017-09-23 00:15:01 +03:00
|
|
|
SingleTweak: localDelayTweak,
|
2017-07-30 23:20:58 +03:00
|
|
|
WitnessScript: htlcSweepScript,
|
|
|
|
Output: &wire.TxOut{
|
2020-03-06 18:11:44 +03:00
|
|
|
PkScript: htlcSweepScriptHash,
|
2017-09-30 00:28:10 +03:00
|
|
|
Value: int64(secondLevelOutputAmt),
|
2017-07-30 23:20:58 +03:00
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
},
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2019-01-23 07:45:29 +03:00
|
|
|
// HtlcPoint returns the htlc's outpoint on the commitment tx.
|
|
|
|
func (r *IncomingHtlcResolution) HtlcPoint() wire.OutPoint {
|
|
|
|
// If we have a success transaction, then the htlc's outpoint
|
|
|
|
// is the transaction's only input. Otherwise, it's the claim
|
|
|
|
// point.
|
|
|
|
if r.SignedSuccessTx != nil {
|
|
|
|
return r.SignedSuccessTx.TxIn[0].PreviousOutPoint
|
|
|
|
}
|
|
|
|
|
|
|
|
return r.ClaimOutpoint
|
|
|
|
}
|
|
|
|
|
|
|
|
// HtlcPoint returns the htlc's outpoint on the commitment tx.
|
|
|
|
func (r *OutgoingHtlcResolution) HtlcPoint() wire.OutPoint {
|
|
|
|
// If we have a timeout transaction, then the htlc's outpoint
|
|
|
|
// is the transaction's only input. Otherwise, it's the claim
|
|
|
|
// point.
|
|
|
|
if r.SignedTimeoutTx != nil {
|
|
|
|
return r.SignedTimeoutTx.TxIn[0].PreviousOutPoint
|
|
|
|
}
|
|
|
|
|
|
|
|
return r.ClaimOutpoint
|
|
|
|
}
|
|
|
|
|
2017-07-30 23:20:58 +03:00
|
|
|
// extractHtlcResolutions creates a series of outgoing HTLC resolutions, and
|
|
|
|
// the local key used when generating the HTLC scrips. This function is to be
|
|
|
|
// used in two cases: force close, or a unilateral close.
|
2019-10-31 05:43:05 +03:00
|
|
|
func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, ourCommit bool,
|
2019-01-16 17:47:43 +03:00
|
|
|
signer input.Signer, htlcs []channeldb.HTLC, keyRing *CommitmentKeyRing,
|
2017-07-30 23:20:58 +03:00
|
|
|
localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
|
2020-03-06 18:11:45 +03:00
|
|
|
commitHash chainhash.Hash, chanType channeldb.ChannelType) (
|
|
|
|
*HtlcResolutions, error) {
|
2017-07-30 23:20:58 +03:00
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
// TODO(roasbeef): don't need to swap csv delay?
|
2017-07-30 23:20:58 +03:00
|
|
|
dustLimit := remoteChanCfg.DustLimit
|
2017-09-27 05:03:04 +03:00
|
|
|
csvDelay := remoteChanCfg.CsvDelay
|
2017-07-30 23:20:58 +03:00
|
|
|
if ourCommit {
|
|
|
|
dustLimit = localChanCfg.DustLimit
|
2017-09-27 05:03:04 +03:00
|
|
|
csvDelay = localChanCfg.CsvDelay
|
2017-07-30 23:20:58 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
incomingResolutions := make([]IncomingHtlcResolution, 0, len(htlcs))
|
|
|
|
outgoingResolutions := make([]OutgoingHtlcResolution, 0, len(htlcs))
|
2017-09-30 00:32:11 +03:00
|
|
|
for _, htlc := range htlcs {
|
2020-03-06 18:11:45 +03:00
|
|
|
htlc := htlc
|
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
// We'll skip any HTLC's which were dust on the commitment
|
2017-07-30 23:20:58 +03:00
|
|
|
// transaction, as these don't have a corresponding output
|
|
|
|
// within the commitment transaction.
|
2020-03-06 18:11:49 +03:00
|
|
|
if htlcIsDust(
|
|
|
|
chanType, htlc.Incoming, ourCommit, feePerKw,
|
|
|
|
htlc.Amt.ToSatoshis(), dustLimit,
|
|
|
|
) {
|
2017-07-30 23:20:58 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
// If the HTLC is incoming, then we'll attempt to see if we
|
|
|
|
// know the pre-image to the HTLC.
|
|
|
|
if htlc.Incoming {
|
|
|
|
// Otherwise, we'll create an incoming HTLC resolution
|
|
|
|
// as we can satisfy the contract.
|
|
|
|
ihr, err := newIncomingHtlcResolution(
|
2020-03-06 18:11:45 +03:00
|
|
|
signer, localChanCfg, commitHash, &htlc,
|
|
|
|
keyRing, feePerKw, uint32(csvDelay), ourCommit,
|
|
|
|
chanType,
|
2018-01-17 05:36:31 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
incomingResolutions = append(incomingResolutions, *ihr)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
ohr, err := newOutgoingHtlcResolution(
|
2017-11-10 10:06:10 +03:00
|
|
|
signer, localChanCfg, commitHash, &htlc, keyRing,
|
2020-03-06 18:11:45 +03:00
|
|
|
feePerKw, uint32(csvDelay), ourCommit, chanType,
|
2017-09-27 05:03:04 +03:00
|
|
|
)
|
2017-07-30 23:20:58 +03:00
|
|
|
if err != nil {
|
2017-09-23 00:15:01 +03:00
|
|
|
return nil, err
|
2017-07-30 23:20:58 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
outgoingResolutions = append(outgoingResolutions, *ohr)
|
2017-07-30 23:20:58 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 05:36:31 +03:00
|
|
|
return &HtlcResolutions{
|
|
|
|
IncomingHTLCs: incomingResolutions,
|
|
|
|
OutgoingHTLCs: outgoingResolutions,
|
|
|
|
}, nil
|
2017-05-16 04:12:52 +03:00
|
|
|
}
|
|
|
|
|
2019-12-13 13:14:22 +03:00
|
|
|
// AnchorResolution holds the information necessary to spend our commitment tx
|
|
|
|
// anchor.
|
|
|
|
type AnchorResolution struct {
|
|
|
|
// AnchorSignDescriptor is the sign descriptor for our anchor.
|
|
|
|
AnchorSignDescriptor input.SignDescriptor
|
|
|
|
|
|
|
|
// CommitAnchor is the anchor outpoint on the commit tx.
|
|
|
|
CommitAnchor wire.OutPoint
|
|
|
|
}
|
|
|
|
|
2018-03-19 17:19:19 +03:00
|
|
|
// LocalForceCloseSummary describes the final commitment state before the
|
|
|
|
// channel is locked-down to initiate a force closure by broadcasting the
|
|
|
|
// latest state on-chain. If we intend to broadcast this this state, the
|
|
|
|
// channel should not be used after generating this close summary. The summary
|
|
|
|
// includes all the information required to claim all rightfully owned outputs
|
|
|
|
// when the commitment gets confirmed.
|
|
|
|
type LocalForceCloseSummary struct {
|
2017-05-05 01:37:03 +03:00
|
|
|
// ChanPoint is the outpoint that created the channel which has been
|
|
|
|
// force closed.
|
|
|
|
ChanPoint wire.OutPoint
|
|
|
|
|
2018-03-19 17:19:19 +03:00
|
|
|
// CloseTx is the transaction which can be used to close the channel
|
|
|
|
// on-chain. When we initiate a force close, this will be our latest
|
|
|
|
// commitment state.
|
2016-09-12 22:33:22 +03:00
|
|
|
CloseTx *wire.MsgTx
|
|
|
|
|
2018-01-17 05:17:18 +03:00
|
|
|
// CommitResolution contains all the data required to sweep the output
|
2018-03-19 17:19:19 +03:00
|
|
|
// to ourselves. Since this is our commitment transaction, we'll need
|
2018-01-17 05:17:18 +03:00
|
|
|
// to wait a time delay before we can sweep the output.
|
2017-08-05 04:32:25 +03:00
|
|
|
//
|
2018-01-17 05:17:18 +03:00
|
|
|
// NOTE: If our commitment delivery output is below the dust limit,
|
|
|
|
// then this will be nil.
|
|
|
|
CommitResolution *CommitOutputResolution
|
|
|
|
|
|
|
|
// HtlcResolutions contains all the data required to sweep any outgoing
|
2018-03-19 17:19:19 +03:00
|
|
|
// HTLC's and incoming HTLc's we know the preimage to. For each of these
|
2018-01-17 05:17:18 +03:00
|
|
|
// HTLC's, we'll need to go to the second level to sweep them fully.
|
|
|
|
HtlcResolutions *HtlcResolutions
|
|
|
|
|
|
|
|
// ChanSnapshot is a snapshot of the final state of the channel at the
|
2018-03-19 17:19:19 +03:00
|
|
|
// time the summary was created.
|
2018-01-17 05:17:18 +03:00
|
|
|
ChanSnapshot channeldb.ChannelSnapshot
|
2019-12-13 13:14:22 +03:00
|
|
|
|
|
|
|
// AnchorResolution contains the data required to sweep the anchor
|
|
|
|
// output. If the channel type doesn't include anchors, the value of
|
|
|
|
// this field will be nil.
|
|
|
|
AnchorResolution *AnchorResolution
|
2016-11-23 11:29:05 +03:00
|
|
|
}
|
|
|
|
|
2016-09-12 22:33:22 +03:00
|
|
|
// ForceClose executes a unilateral closure of the transaction at the current
|
|
|
|
// lowest commitment height of the channel. Following a force closure, all
|
|
|
|
// state transitions, or modifications to the state update logs will be
|
2018-03-19 17:19:19 +03:00
|
|
|
// rejected. Additionally, this function also returns a LocalForceCloseSummary
|
|
|
|
// which includes the necessary details required to sweep all the time-locked
|
|
|
|
// outputs within the commitment transaction.
|
2016-09-12 22:33:22 +03:00
|
|
|
//
|
|
|
|
// TODO(roasbeef): all methods need to abort if in dispute state
|
|
|
|
// TODO(roasbeef): method to generate CloseSummaries for when the remote peer
|
|
|
|
// does a unilateral close
|
2018-03-19 17:19:19 +03:00
|
|
|
func (lc *LightningChannel) ForceClose() (*LocalForceCloseSummary, error) {
|
2016-09-12 22:33:22 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2018-12-10 06:54:25 +03:00
|
|
|
// If we've detected local data loss for this channel, then we won't
|
|
|
|
// allow a force close, as it may be the case that we have a dated
|
|
|
|
// version of the commitment, or this is actually a channel shell.
|
|
|
|
if lc.channelState.HasChanStatus(channeldb.ChanStatusLocalDataLoss) {
|
|
|
|
return nil, fmt.Errorf("cannot force close channel with "+
|
|
|
|
"state: %v", lc.channelState.ChanStatus())
|
|
|
|
}
|
|
|
|
|
2016-11-23 11:29:05 +03:00
|
|
|
commitTx, err := lc.getSignedCommitTx()
|
2016-09-12 22:33:22 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-03-19 17:19:19 +03:00
|
|
|
localCommitment := lc.channelState.LocalCommitment
|
2018-12-10 06:54:25 +03:00
|
|
|
summary, err := NewLocalForceCloseSummary(
|
2019-04-15 15:24:43 +03:00
|
|
|
lc.channelState, lc.Signer, commitTx,
|
2018-12-10 06:54:25 +03:00
|
|
|
localCommitment,
|
|
|
|
)
|
2018-03-19 17:19:19 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the channel state to indicate that the channel is now in a
|
|
|
|
// contested state.
|
|
|
|
lc.status = channelDispute
|
|
|
|
|
|
|
|
return summary, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewLocalForceCloseSummary generates a LocalForceCloseSummary from the given
|
|
|
|
// channel state. The passed commitTx must be a fully signed commitment
|
|
|
|
// transaction corresponding to localCommit.
|
2019-01-16 17:47:43 +03:00
|
|
|
func NewLocalForceCloseSummary(chanState *channeldb.OpenChannel, signer input.Signer,
|
2019-04-15 15:24:43 +03:00
|
|
|
commitTx *wire.MsgTx, localCommit channeldb.ChannelCommitment) (
|
|
|
|
*LocalForceCloseSummary, error) {
|
2018-03-19 17:19:19 +03:00
|
|
|
|
2017-01-24 12:38:25 +03:00
|
|
|
// Re-derive the original pkScript for to-self output within the
|
|
|
|
// commitment transaction. We'll need this to find the corresponding
|
|
|
|
// output in the commitment transaction and potentially for creating
|
|
|
|
// the sign descriptor.
|
2018-03-19 17:19:19 +03:00
|
|
|
csvTimeout := uint32(chanState.LocalChanCfg.CsvDelay)
|
|
|
|
revocation, err := chanState.RevocationProducer.AtIndex(
|
|
|
|
localCommit.CommitHeight,
|
2017-07-30 23:21:26 +03:00
|
|
|
)
|
2017-01-24 12:38:25 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
commitPoint := input.ComputeCommitmentPoint(revocation[:])
|
2019-09-17 05:06:19 +03:00
|
|
|
keyRing := DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
commitPoint, true, chanState.ChanType,
|
2019-09-17 05:06:19 +03:00
|
|
|
&chanState.LocalChanCfg, &chanState.RemoteChanCfg,
|
2019-08-01 06:10:45 +03:00
|
|
|
)
|
2020-01-06 13:42:04 +03:00
|
|
|
|
|
|
|
selfScript, err := input.CommitScriptToSelf(
|
|
|
|
csvTimeout, keyRing.ToLocalKey, keyRing.RevocationKey,
|
|
|
|
)
|
2017-01-24 12:38:25 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
payToUsScriptHash, err := input.WitnessScriptHash(selfScript)
|
2017-01-24 12:38:25 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2016-09-12 22:33:22 +03:00
|
|
|
// Locate the output index of the delayed commitment output back to us.
|
|
|
|
// We'll return the details of this output to the caller so they can
|
|
|
|
// sweep it once it's mature.
|
2017-07-30 23:21:26 +03:00
|
|
|
var (
|
2018-01-17 05:17:18 +03:00
|
|
|
delayIndex uint32
|
|
|
|
delayScript []byte
|
2017-07-30 23:21:26 +03:00
|
|
|
)
|
2016-09-12 22:33:22 +03:00
|
|
|
for i, txOut := range commitTx.TxOut {
|
2017-01-24 12:38:25 +03:00
|
|
|
if !bytes.Equal(payToUsScriptHash, txOut.PkScript) {
|
2016-09-12 22:33:22 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
delayIndex = uint32(i)
|
|
|
|
delayScript = txOut.PkScript
|
2017-01-24 12:38:25 +03:00
|
|
|
break
|
2016-09-12 22:33:22 +03:00
|
|
|
}
|
|
|
|
|
2016-11-21 08:54:18 +03:00
|
|
|
// With the necessary information gathered above, create a new sign
|
2016-09-12 22:33:22 +03:00
|
|
|
// descriptor which is capable of generating the signature the caller
|
|
|
|
// needs to sweep this output. The hash cache, and input index are not
|
|
|
|
// set as the caller will decide these values once sweeping the output.
|
2017-07-30 23:21:26 +03:00
|
|
|
// If the output is non-existent (dust), have the sign descriptor be
|
|
|
|
// nil.
|
2018-01-17 05:17:18 +03:00
|
|
|
var commitResolution *CommitOutputResolution
|
2017-01-24 12:38:25 +03:00
|
|
|
if len(delayScript) != 0 {
|
2018-03-19 17:19:19 +03:00
|
|
|
localBalance := localCommit.LocalBalance
|
2018-01-17 05:17:18 +03:00
|
|
|
commitResolution = &CommitOutputResolution{
|
|
|
|
SelfOutPoint: wire.OutPoint{
|
|
|
|
Hash: commitTx.TxHash(),
|
|
|
|
Index: delayIndex,
|
2017-01-24 12:38:25 +03:00
|
|
|
},
|
2019-01-16 17:47:43 +03:00
|
|
|
SelfOutputSignDesc: input.SignDescriptor{
|
2018-03-19 17:19:19 +03:00
|
|
|
KeyDesc: chanState.LocalChanCfg.DelayBasePoint,
|
2020-01-06 13:42:05 +03:00
|
|
|
SingleTweak: keyRing.LocalCommitKeyTweak,
|
2018-01-17 05:17:18 +03:00
|
|
|
WitnessScript: selfScript,
|
|
|
|
Output: &wire.TxOut{
|
|
|
|
PkScript: delayScript,
|
|
|
|
Value: int64(localBalance.ToSatoshis()),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
},
|
|
|
|
MaturityDelay: csvTimeout,
|
2017-01-24 12:38:25 +03:00
|
|
|
}
|
2016-09-12 22:33:22 +03:00
|
|
|
}
|
|
|
|
|
2017-07-30 23:21:26 +03:00
|
|
|
// Once the delay output has been found (if it exists), then we'll also
|
|
|
|
// need to create a series of sign descriptors for any lingering
|
|
|
|
// outgoing HTLC's that we'll need to claim as well.
|
|
|
|
txHash := commitTx.TxHash()
|
2017-09-23 00:15:01 +03:00
|
|
|
htlcResolutions, err := extractHtlcResolutions(
|
2019-10-31 05:43:05 +03:00
|
|
|
chainfee.SatPerKWeight(localCommit.FeePerKw), true, signer,
|
2018-03-19 17:19:19 +03:00
|
|
|
localCommit.Htlcs, keyRing, &chanState.LocalChanCfg,
|
2020-03-06 18:11:45 +03:00
|
|
|
&chanState.RemoteChanCfg, txHash, chanState.ChanType,
|
2019-04-15 15:24:43 +03:00
|
|
|
)
|
2017-07-30 23:21:26 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-12-13 13:14:22 +03:00
|
|
|
anchorResolution, err := NewAnchorResolution(
|
|
|
|
chanState, commitTx,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-03-19 17:19:19 +03:00
|
|
|
return &LocalForceCloseSummary{
|
|
|
|
ChanPoint: chanState.FundingOutpoint,
|
2018-01-17 05:17:18 +03:00
|
|
|
CloseTx: commitTx,
|
|
|
|
CommitResolution: commitResolution,
|
|
|
|
HtlcResolutions: htlcResolutions,
|
2018-03-19 17:19:19 +03:00
|
|
|
ChanSnapshot: *chanState.Snapshot(),
|
2019-12-13 13:14:22 +03:00
|
|
|
AnchorResolution: anchorResolution,
|
2016-09-12 22:33:22 +03:00
|
|
|
}, nil
|
2015-12-17 07:58:01 +03:00
|
|
|
}
|
|
|
|
|
2017-03-25 04:26:09 +03:00
|
|
|
// CreateCloseProposal is used by both parties in a cooperative channel close
|
|
|
|
// workflow to generate proposed close transactions and signatures. This method
|
|
|
|
// should only be executed once all pending HTLCs (if any) on the channel have
|
|
|
|
// been cleared/removed. Upon completion, the source channel will shift into
|
|
|
|
// the "closing" state, which indicates that all incoming/outgoing HTLC
|
|
|
|
// requests should be rejected. A signature for the closing transaction is
|
|
|
|
// returned.
|
2016-11-21 08:54:18 +03:00
|
|
|
//
|
2016-06-21 08:09:42 +03:00
|
|
|
// TODO(roasbeef): caller should initiate signal to reject all incoming HTLCs,
|
2017-07-30 23:26:09 +03:00
|
|
|
// settle any in flight.
|
2017-11-23 09:36:20 +03:00
|
|
|
func (lc *LightningChannel) CreateCloseProposal(proposedFee btcutil.Amount,
|
2018-01-20 04:18:26 +03:00
|
|
|
localDeliveryScript []byte,
|
|
|
|
remoteDeliveryScript []byte) ([]byte, *chainhash.Hash, btcutil.Amount, error) {
|
2017-05-18 02:51:10 +03:00
|
|
|
|
2016-06-21 08:09:42 +03:00
|
|
|
lc.Lock()
|
2016-07-27 21:32:27 +03:00
|
|
|
defer lc.Unlock()
|
2016-06-21 08:09:42 +03:00
|
|
|
|
2017-07-14 22:04:29 +03:00
|
|
|
// If we've already closed the channel, then ignore this request.
|
|
|
|
if lc.status == channelClosed {
|
2016-06-21 08:09:42 +03:00
|
|
|
// TODO(roasbeef): check to ensure no pending payments
|
2018-01-20 04:18:26 +03:00
|
|
|
return nil, nil, 0, ErrChanClosing
|
2016-06-21 08:09:42 +03:00
|
|
|
}
|
|
|
|
|
2017-05-18 02:51:10 +03:00
|
|
|
// Subtract the proposed fee from the appropriate balance, taking care
|
|
|
|
// not to persist the adjusted balance, as the feeRate may change
|
|
|
|
// during the channel closing process.
|
2017-11-10 10:06:10 +03:00
|
|
|
localCommit := lc.channelState.LocalCommitment
|
|
|
|
ourBalance := localCommit.LocalBalance.ToSatoshis()
|
|
|
|
theirBalance := localCommit.RemoteBalance.ToSatoshis()
|
2017-05-01 21:45:02 +03:00
|
|
|
|
2017-11-30 03:14:17 +03:00
|
|
|
// We'll make sure we account for the complete balance by adding the
|
|
|
|
// current dangling commitment fee to the balance of the initiator.
|
|
|
|
commitFee := localCommit.CommitFee
|
2017-05-01 21:45:02 +03:00
|
|
|
if lc.channelState.IsInitiator {
|
2017-11-30 03:14:17 +03:00
|
|
|
ourBalance = ourBalance - proposedFee + commitFee
|
2017-05-01 21:45:02 +03:00
|
|
|
} else {
|
2017-11-30 03:14:17 +03:00
|
|
|
theirBalance = theirBalance - proposedFee + commitFee
|
2017-05-01 21:45:02 +03:00
|
|
|
}
|
|
|
|
|
2020-01-06 13:42:02 +03:00
|
|
|
closeTx := CreateCooperativeCloseTx(
|
2020-01-06 13:42:03 +03:00
|
|
|
fundingTxIn(lc.channelState), lc.channelState.LocalChanCfg.DustLimit,
|
2020-01-06 13:42:02 +03:00
|
|
|
lc.channelState.RemoteChanCfg.DustLimit, ourBalance, theirBalance,
|
2020-01-06 13:42:02 +03:00
|
|
|
localDeliveryScript, remoteDeliveryScript,
|
|
|
|
)
|
2017-02-28 06:00:18 +03:00
|
|
|
|
2017-03-15 08:53:15 +03:00
|
|
|
// Ensure that the transaction doesn't explicitly violate any
|
2017-02-28 06:00:18 +03:00
|
|
|
// consensus rules such as being too big, or having any value with a
|
|
|
|
// negative output.
|
|
|
|
tx := btcutil.NewTx(closeTx)
|
|
|
|
if err := blockchain.CheckTransactionSanity(tx); err != nil {
|
2018-01-20 04:18:26 +03:00
|
|
|
return nil, nil, 0, err
|
2017-02-28 06:00:18 +03:00
|
|
|
}
|
2016-06-21 08:09:42 +03:00
|
|
|
|
|
|
|
// Finally, sign the completed cooperative closure transaction. As the
|
2017-01-13 05:29:55 +03:00
|
|
|
// initiator we'll simply send our signature over to the remote party,
|
2016-06-21 08:09:42 +03:00
|
|
|
// using the generated txid to be notified once the closure transaction
|
|
|
|
// has been confirmed.
|
2016-08-13 01:50:47 +03:00
|
|
|
lc.signDesc.SigHashes = txscript.NewTxSigHashes(closeTx)
|
2018-04-30 01:40:59 +03:00
|
|
|
sig, err := lc.Signer.SignOutputRaw(closeTx, lc.signDesc)
|
2016-06-21 08:09:42 +03:00
|
|
|
if err != nil {
|
2018-01-20 04:18:26 +03:00
|
|
|
return nil, nil, 0, err
|
2016-06-21 08:09:42 +03:00
|
|
|
}
|
|
|
|
|
2017-02-28 05:52:23 +03:00
|
|
|
// As everything checks out, indicate in the channel status that a
|
|
|
|
// channel closure has been initiated.
|
|
|
|
lc.status = channelClosing
|
|
|
|
|
2018-01-20 04:18:26 +03:00
|
|
|
closeTXID := closeTx.TxHash()
|
|
|
|
return sig, &closeTXID, ourBalance, nil
|
2016-06-21 08:09:42 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// CompleteCooperativeClose completes the cooperative closure of the target
|
2017-03-25 04:26:09 +03:00
|
|
|
// active lightning channel. A fully signed closure transaction as well as the
|
2018-01-09 04:42:13 +03:00
|
|
|
// signature itself are returned. Additionally, we also return our final
|
|
|
|
// settled balance, which reflects any fees we may have paid.
|
2016-08-13 01:50:47 +03:00
|
|
|
//
|
2017-03-25 04:26:09 +03:00
|
|
|
// NOTE: The passed local and remote sigs are expected to be fully complete
|
|
|
|
// signatures including the proper sighash byte.
|
2018-01-09 04:42:13 +03:00
|
|
|
func (lc *LightningChannel) CompleteCooperativeClose(localSig, remoteSig []byte,
|
2017-07-30 23:26:09 +03:00
|
|
|
localDeliveryScript, remoteDeliveryScript []byte,
|
2018-01-09 04:42:13 +03:00
|
|
|
proposedFee btcutil.Amount) (*wire.MsgTx, btcutil.Amount, error) {
|
2017-07-30 23:26:09 +03:00
|
|
|
|
2016-06-21 08:09:42 +03:00
|
|
|
lc.Lock()
|
2016-07-27 21:32:27 +03:00
|
|
|
defer lc.Unlock()
|
2016-06-21 08:09:42 +03:00
|
|
|
|
2017-03-25 04:26:09 +03:00
|
|
|
// If the channel is already closed, then ignore this request.
|
|
|
|
if lc.status == channelClosed {
|
2016-06-21 08:09:42 +03:00
|
|
|
// TODO(roasbeef): check to ensure no pending payments
|
2018-01-09 04:42:13 +03:00
|
|
|
return nil, 0, ErrChanClosing
|
2016-06-21 08:09:42 +03:00
|
|
|
}
|
|
|
|
|
2017-05-18 02:51:10 +03:00
|
|
|
// Subtract the proposed fee from the appropriate balance, taking care
|
|
|
|
// not to persist the adjusted balance, as the feeRate may change
|
|
|
|
// during the channel closing process.
|
2017-11-10 10:06:10 +03:00
|
|
|
localCommit := lc.channelState.LocalCommitment
|
|
|
|
ourBalance := localCommit.LocalBalance.ToSatoshis()
|
|
|
|
theirBalance := localCommit.RemoteBalance.ToSatoshis()
|
2017-05-18 02:51:10 +03:00
|
|
|
|
2017-11-30 03:14:17 +03:00
|
|
|
// We'll make sure we account for the complete balance by adding the
|
|
|
|
// current dangling commitment fee to the balance of the initiator.
|
|
|
|
commitFee := localCommit.CommitFee
|
2017-05-18 02:51:10 +03:00
|
|
|
if lc.channelState.IsInitiator {
|
2017-11-30 03:14:17 +03:00
|
|
|
ourBalance = ourBalance - proposedFee + commitFee
|
2017-05-18 02:51:10 +03:00
|
|
|
} else {
|
2017-11-30 03:14:17 +03:00
|
|
|
theirBalance = theirBalance - proposedFee + commitFee
|
2017-05-18 02:51:10 +03:00
|
|
|
}
|
|
|
|
|
2016-06-21 08:09:42 +03:00
|
|
|
// Create the transaction used to return the current settled balance
|
|
|
|
// on this active channel back to both parties. In this current model,
|
|
|
|
// the initiator pays full fees for the cooperative close transaction.
|
2020-01-06 13:42:02 +03:00
|
|
|
closeTx := CreateCooperativeCloseTx(
|
2020-01-06 13:42:03 +03:00
|
|
|
fundingTxIn(lc.channelState), lc.channelState.LocalChanCfg.DustLimit,
|
2020-01-06 13:42:02 +03:00
|
|
|
lc.channelState.RemoteChanCfg.DustLimit, ourBalance, theirBalance,
|
2020-01-06 13:42:02 +03:00
|
|
|
localDeliveryScript, remoteDeliveryScript,
|
|
|
|
)
|
2016-06-21 08:09:42 +03:00
|
|
|
|
2017-02-28 06:00:18 +03:00
|
|
|
// Ensure that the transaction doesn't explicitly validate any
|
|
|
|
// consensus rules such as being too big, or having any value with a
|
|
|
|
// negative output.
|
|
|
|
tx := btcutil.NewTx(closeTx)
|
|
|
|
if err := blockchain.CheckTransactionSanity(tx); err != nil {
|
2018-01-09 04:42:13 +03:00
|
|
|
return nil, 0, err
|
2017-02-28 06:00:18 +03:00
|
|
|
}
|
2016-06-21 08:09:42 +03:00
|
|
|
hashCache := txscript.NewTxSigHashes(closeTx)
|
|
|
|
|
|
|
|
// Finally, construct the witness stack minding the order of the
|
|
|
|
// pubkeys+sigs on the stack.
|
2020-01-06 13:42:02 +03:00
|
|
|
ourKey := lc.channelState.LocalChanCfg.MultiSigKey.PubKey.
|
|
|
|
SerializeCompressed()
|
|
|
|
theirKey := lc.channelState.RemoteChanCfg.MultiSigKey.PubKey.
|
|
|
|
SerializeCompressed()
|
2019-01-16 17:47:43 +03:00
|
|
|
witness := input.SpendMultiSig(lc.signDesc.WitnessScript, ourKey,
|
2017-03-25 04:26:09 +03:00
|
|
|
localSig, theirKey, remoteSig)
|
2016-06-21 08:09:42 +03:00
|
|
|
closeTx.TxIn[0].Witness = witness
|
|
|
|
|
2016-07-27 21:32:27 +03:00
|
|
|
// Validate the finalized transaction to ensure the output script is
|
|
|
|
// properly met, and that the remote peer supplied a valid signature.
|
2017-09-26 07:47:39 +03:00
|
|
|
prevOut := lc.signDesc.Output
|
|
|
|
vm, err := txscript.NewEngine(prevOut.PkScript, closeTx, 0,
|
|
|
|
txscript.StandardVerifyFlags, nil, hashCache, prevOut.Value)
|
2016-07-27 21:32:27 +03:00
|
|
|
if err != nil {
|
2018-01-09 04:42:13 +03:00
|
|
|
return nil, 0, err
|
2016-07-27 21:32:27 +03:00
|
|
|
}
|
|
|
|
if err := vm.Execute(); err != nil {
|
2018-01-09 04:42:13 +03:00
|
|
|
return nil, 0, err
|
2016-07-27 21:32:27 +03:00
|
|
|
}
|
2016-06-21 08:09:42 +03:00
|
|
|
|
2017-02-28 05:52:23 +03:00
|
|
|
// As the transaction is sane, and the scripts are valid we'll mark the
|
|
|
|
// channel now as closed as the closure transaction should get into the
|
|
|
|
// chain in a timely manner and possibly be re-broadcast by the wallet.
|
|
|
|
lc.status = channelClosed
|
|
|
|
|
2018-01-09 04:42:13 +03:00
|
|
|
return closeTx, ourBalance, nil
|
2016-06-21 08:09:42 +03:00
|
|
|
}
|
|
|
|
|
2019-12-13 13:14:22 +03:00
|
|
|
// NewAnchorResolutions returns the anchor resolutions for all currently valid
|
|
|
|
// commitment transactions. Because we have no view on the mempool, we can only
|
|
|
|
// blindly anchor all of these txes down.
|
|
|
|
func (lc *LightningChannel) NewAnchorResolutions() ([]*AnchorResolution,
|
|
|
|
error) {
|
|
|
|
|
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
|
|
|
var resolutions []*AnchorResolution
|
|
|
|
|
|
|
|
// Add anchor for local commitment tx, if any.
|
|
|
|
localRes, err := NewAnchorResolution(
|
|
|
|
lc.channelState, lc.channelState.LocalCommitment.CommitTx,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if localRes != nil {
|
|
|
|
resolutions = append(resolutions, localRes)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add anchor for remote commitment tx, if any.
|
|
|
|
remoteRes, err := NewAnchorResolution(
|
|
|
|
lc.channelState, lc.channelState.RemoteCommitment.CommitTx,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if remoteRes != nil {
|
|
|
|
resolutions = append(resolutions, remoteRes)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add anchor for remote pending commitment tx, if any.
|
|
|
|
remotePendingCommit, err := lc.channelState.RemoteCommitChainTip()
|
|
|
|
if err != nil && err != channeldb.ErrNoPendingCommit {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if remotePendingCommit != nil {
|
|
|
|
remotePendingRes, err := NewAnchorResolution(
|
|
|
|
lc.channelState,
|
|
|
|
remotePendingCommit.Commitment.CommitTx,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if remotePendingRes != nil {
|
|
|
|
resolutions = append(resolutions, remotePendingRes)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return resolutions, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewAnchorResolution returns the information that is required to sweep the
|
|
|
|
// local anchor.
|
|
|
|
func NewAnchorResolution(chanState *channeldb.OpenChannel,
|
|
|
|
commitTx *wire.MsgTx) (*AnchorResolution, error) {
|
|
|
|
|
|
|
|
// Return nil resolution if the channel has no anchors.
|
|
|
|
if !chanState.ChanType.HasAnchors() {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Derive our local anchor script.
|
|
|
|
localAnchor, _, err := CommitScriptAnchors(
|
|
|
|
&chanState.LocalChanCfg, &chanState.RemoteChanCfg,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Look up the script on the commitment transaction. It may not be
|
|
|
|
// present if there is no output paying to us.
|
|
|
|
found, index := input.FindScriptOutputIndex(commitTx, localAnchor.PkScript)
|
|
|
|
if !found {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
outPoint := &wire.OutPoint{
|
|
|
|
Hash: commitTx.TxHash(),
|
|
|
|
Index: index,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Instantiate the sign descriptor that allows sweeping of the anchor.
|
|
|
|
signDesc := &input.SignDescriptor{
|
|
|
|
KeyDesc: chanState.LocalChanCfg.MultiSigKey,
|
|
|
|
WitnessScript: localAnchor.WitnessScript,
|
|
|
|
Output: &wire.TxOut{
|
|
|
|
PkScript: localAnchor.PkScript,
|
|
|
|
Value: int64(anchorSize),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
}
|
|
|
|
|
|
|
|
return &AnchorResolution{
|
|
|
|
CommitAnchor: *outPoint,
|
|
|
|
AnchorSignDescriptor: *signDesc,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-02-19 14:27:41 +03:00
|
|
|
// AvailableBalance returns the current balance available for sending within
|
|
|
|
// the channel. By available balance, we mean that if at this very instance a
|
|
|
|
// new commitment were to be created which evals all the log entries, what
|
|
|
|
// would our available balance for adding an additional HTLC be. It takes into
|
|
|
|
// account the fee that must be paid for adding this HTLC (if we're the
|
|
|
|
// initiator), and that we cannot spend from the channel reserve. This method
|
|
|
|
// is useful when deciding if a given channel can accept an HTLC in the
|
|
|
|
// multi-hop forwarding scenario.
|
2017-11-10 10:08:50 +03:00
|
|
|
func (lc *LightningChannel) AvailableBalance() lnwire.MilliSatoshi {
|
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
2017-11-26 22:50:39 +03:00
|
|
|
bal, _ := lc.availableBalance()
|
|
|
|
return bal
|
2017-11-10 10:08:50 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// availableBalance is the private, non mutexed version of AvailableBalance.
|
|
|
|
// This method is provided so methods that already hold the lock can access
|
2017-11-26 22:50:39 +03:00
|
|
|
// this method. Additionally, the total weight of the next to be created
|
|
|
|
// commitment is returned for accounting purposes.
|
|
|
|
func (lc *LightningChannel) availableBalance() (lnwire.MilliSatoshi, int64) {
|
2018-01-09 18:42:07 +03:00
|
|
|
// We'll grab the current set of log updates that the remote has
|
|
|
|
// ACKed.
|
2018-01-16 23:19:04 +03:00
|
|
|
remoteACKedIndex := lc.localCommitChain.tip().theirMessageIndex
|
|
|
|
htlcView := lc.fetchHTLCView(remoteACKedIndex,
|
2017-11-10 10:08:50 +03:00
|
|
|
lc.localUpdateLog.logIndex)
|
|
|
|
|
2020-02-19 14:27:41 +03:00
|
|
|
// Calculate our available balance from our local commitment.
|
2020-02-19 14:27:42 +03:00
|
|
|
// TODO(halseth): could reuse parts validateCommitmentSanity to do this
|
|
|
|
// balance calculation, as most of the logic is the same.
|
2020-02-19 14:27:41 +03:00
|
|
|
//
|
|
|
|
// NOTE: This is not always accurate, since the remote node can always
|
|
|
|
// add updates concurrently, causing our balance to go down if we're
|
|
|
|
// the initiator, but this is a problem on the protocol level.
|
|
|
|
ourLocalCommitBalance, commitWeight := lc.availableCommitmentBalance(
|
2020-02-19 14:27:42 +03:00
|
|
|
htlcView, false,
|
2020-02-19 14:27:41 +03:00
|
|
|
)
|
|
|
|
|
2020-02-19 14:27:42 +03:00
|
|
|
// Do the same calculation from the remote commitment point of view.
|
|
|
|
ourRemoteCommitBalance, _ := lc.availableCommitmentBalance(
|
|
|
|
htlcView, true,
|
|
|
|
)
|
|
|
|
|
|
|
|
// Return which ever balance is lowest.
|
|
|
|
if ourRemoteCommitBalance < ourLocalCommitBalance {
|
|
|
|
return ourRemoteCommitBalance, commitWeight
|
|
|
|
}
|
|
|
|
|
2020-02-19 14:27:41 +03:00
|
|
|
return ourLocalCommitBalance, commitWeight
|
|
|
|
}
|
|
|
|
|
|
|
|
// availableCommitmentBalance attempts to calculate the balance we have
|
|
|
|
// available for HTLCs on the local/remote commitment given the htlcView. To
|
|
|
|
// account for sending HTLCs of different sizes, it will report the balance
|
|
|
|
// available for sending non-dust HTLCs, which will be manifested on the
|
|
|
|
// commitment, increasing the commitment fee we must pay as an initiator,
|
|
|
|
// eating into our balance. It will make sure we won't violate the channel
|
|
|
|
// reserve constraints for this amount.
|
2020-02-19 14:27:42 +03:00
|
|
|
func (lc *LightningChannel) availableCommitmentBalance(view *htlcView,
|
|
|
|
remoteChain bool) (lnwire.MilliSatoshi, int64) {
|
2020-02-19 14:27:41 +03:00
|
|
|
|
|
|
|
// Compute the current balances for this commitment. This will take
|
|
|
|
// into account HTLCs to determine the commit weight, which the
|
|
|
|
// initiator must pay the fee for.
|
2020-02-19 14:27:42 +03:00
|
|
|
ourBalance, theirBalance, commitWeight, filteredView, err := lc.computeView(
|
2020-02-19 14:27:42 +03:00
|
|
|
view, remoteChain, false,
|
2020-02-19 14:27:41 +03:00
|
|
|
)
|
2020-02-12 13:10:19 +03:00
|
|
|
if err != nil {
|
|
|
|
lc.log.Errorf("Unable to fetch available balance: %v", err)
|
|
|
|
return 0, 0
|
|
|
|
}
|
2017-11-10 10:08:50 +03:00
|
|
|
|
2020-02-19 14:27:42 +03:00
|
|
|
// We can never spend from the channel reserve, so we'll subtract it
|
|
|
|
// from our available balance.
|
|
|
|
ourReserve := lnwire.NewMSatFromSatoshis(
|
|
|
|
lc.channelState.LocalChanCfg.ChanReserve,
|
|
|
|
)
|
|
|
|
if ourReserve <= ourBalance {
|
|
|
|
ourBalance -= ourReserve
|
|
|
|
} else {
|
|
|
|
ourBalance = 0
|
|
|
|
}
|
|
|
|
|
2020-02-19 14:27:42 +03:00
|
|
|
// Calculate the commitment fee in the case where we would add another
|
|
|
|
// HTLC to the commitment, as only the balance remaining after this fee
|
|
|
|
// has been paid is actually available for sending.
|
2020-02-19 14:27:41 +03:00
|
|
|
feePerKw := filteredView.feePerKw
|
2020-02-19 14:27:42 +03:00
|
|
|
htlcCommitFee := lnwire.NewMSatFromSatoshis(
|
|
|
|
feePerKw.FeeForWeight(commitWeight + input.HTLCWeight),
|
2020-02-19 14:27:41 +03:00
|
|
|
)
|
|
|
|
|
2020-02-19 14:27:42 +03:00
|
|
|
// If we are the channel initiator, we must to subtract this commitment
|
|
|
|
// fee from our available balance in order to ensure we can afford both
|
|
|
|
// the value of the HTLC and the additional commitment fee from adding
|
|
|
|
// the HTLC.
|
2017-11-10 10:08:50 +03:00
|
|
|
if lc.channelState.IsInitiator {
|
2020-02-19 14:27:42 +03:00
|
|
|
// There is an edge case where our non-zero balance is lower
|
|
|
|
// than the htlcCommitFee, where we could still be sending dust
|
|
|
|
// HTLCs, but we return 0 in this case. This is to avoid
|
|
|
|
// lowering our balance even further, as this takes us into a
|
|
|
|
// bad state wehere neither we nor our channel counterparty can
|
|
|
|
// add HTLCs.
|
|
|
|
if ourBalance < htlcCommitFee {
|
2020-02-19 14:27:42 +03:00
|
|
|
return 0, commitWeight
|
|
|
|
}
|
2020-02-19 14:27:42 +03:00
|
|
|
|
2020-02-19 14:27:42 +03:00
|
|
|
return ourBalance - htlcCommitFee, commitWeight
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we're not the initiator, we must check whether the remote has
|
|
|
|
// enough balance to pay for the fee of our HTLC. We'll start by also
|
|
|
|
// subtracting our counterparty's reserve from their balance.
|
|
|
|
theirReserve := lnwire.NewMSatFromSatoshis(
|
|
|
|
lc.channelState.RemoteChanCfg.ChanReserve,
|
|
|
|
)
|
|
|
|
if theirReserve <= theirBalance {
|
|
|
|
theirBalance -= theirReserve
|
|
|
|
} else {
|
|
|
|
theirBalance = 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// We'll use the dustlimit and htlcFee to find the largest HTLC value
|
|
|
|
// that will be considered dust on the commitment.
|
|
|
|
dustlimit := lnwire.NewMSatFromSatoshis(
|
|
|
|
lc.channelState.LocalChanCfg.DustLimit,
|
|
|
|
)
|
|
|
|
|
|
|
|
// For an extra HTLC fee to be paid on our commitment, the HTLC must be
|
|
|
|
// large enough to make a non-dust HTLC timeout transaction.
|
|
|
|
htlcFee := lnwire.NewMSatFromSatoshis(
|
2020-03-06 18:11:49 +03:00
|
|
|
HtlcTimeoutFee(lc.channelState.ChanType, feePerKw),
|
2020-02-19 14:27:42 +03:00
|
|
|
)
|
|
|
|
|
2020-02-19 14:27:42 +03:00
|
|
|
// If we are looking at the remote commitment, we must use the remote
|
|
|
|
// dust limit and the fee for adding an HTLC success transaction.
|
|
|
|
if remoteChain {
|
|
|
|
dustlimit = lnwire.NewMSatFromSatoshis(
|
|
|
|
lc.channelState.RemoteChanCfg.DustLimit,
|
|
|
|
)
|
|
|
|
htlcFee = lnwire.NewMSatFromSatoshis(
|
2020-03-06 18:11:49 +03:00
|
|
|
HtlcSuccessFee(lc.channelState.ChanType, feePerKw),
|
2020-02-19 14:27:42 +03:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-02-19 14:27:42 +03:00
|
|
|
// The HTLC output will be manifested on the commitment if it
|
|
|
|
// is non-dust after paying the HTLC fee.
|
|
|
|
nonDustHtlcAmt := dustlimit + htlcFee
|
|
|
|
|
|
|
|
// If they cannot pay the fee if we add another non-dust HTLC, we'll
|
|
|
|
// report our available balance just below the non-dust amount, to
|
|
|
|
// avoid attempting HTLCs larger than this size.
|
|
|
|
if theirBalance < htlcCommitFee && ourBalance >= nonDustHtlcAmt {
|
|
|
|
ourBalance = nonDustHtlcAmt - 1
|
2017-11-10 10:08:50 +03:00
|
|
|
}
|
|
|
|
|
2018-01-09 18:42:07 +03:00
|
|
|
return ourBalance, commitWeight
|
2017-11-10 10:08:50 +03:00
|
|
|
}
|
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// StateSnapshot returns a snapshot of the current fully committed state within
|
|
|
|
// the channel.
|
2016-06-23 08:12:28 +03:00
|
|
|
func (lc *LightningChannel) StateSnapshot() *channeldb.ChannelSnapshot {
|
2017-06-09 08:24:10 +03:00
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
2016-06-23 08:12:28 +03:00
|
|
|
|
|
|
|
return lc.channelState.Snapshot()
|
|
|
|
}
|
|
|
|
|
2017-11-26 22:50:39 +03:00
|
|
|
// validateFeeRate ensures that if the passed fee is applied to the channel,
|
|
|
|
// and a new commitment is created (which evaluates this fee), then the
|
|
|
|
// initiator of the channel does not dip below their reserve.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (lc *LightningChannel) validateFeeRate(feePerKw chainfee.SatPerKWeight) error {
|
2017-11-26 22:50:39 +03:00
|
|
|
// We'll ensure that we can accommodate this new fee change, yet still
|
|
|
|
// be above our reserve balance. Otherwise, we'll reject the fee
|
|
|
|
// update.
|
|
|
|
availableBalance, txWeight := lc.availableBalance()
|
2018-05-02 03:34:52 +03:00
|
|
|
oldFee := lnwire.NewMSatFromSatoshis(lc.localCommitChain.tip().fee)
|
|
|
|
|
|
|
|
// Our base balance is the total amount of satoshis we can commit
|
|
|
|
// towards fees before factoring in the channel reserve.
|
|
|
|
baseBalance := availableBalance + oldFee
|
2017-11-26 22:50:39 +03:00
|
|
|
|
|
|
|
// Using the weight of the commitment transaction if we were to create
|
|
|
|
// a commitment now, we'll compute our remaining balance if we apply
|
|
|
|
// this new fee update.
|
|
|
|
newFee := lnwire.NewMSatFromSatoshis(
|
2018-02-13 16:43:58 +03:00
|
|
|
feePerKw.FeeForWeight(txWeight),
|
2017-11-26 22:50:39 +03:00
|
|
|
)
|
2018-02-25 06:19:46 +03:00
|
|
|
|
2018-05-02 03:34:52 +03:00
|
|
|
// If the total fee exceeds our available balance (taking into account
|
|
|
|
// the fee from the last state), then we'll reject this update as it
|
|
|
|
// would mean we need to trim our entire output.
|
|
|
|
if newFee > baseBalance {
|
2018-02-25 06:19:46 +03:00
|
|
|
return fmt.Errorf("cannot apply fee_update=%v sat/kw, new fee "+
|
|
|
|
"of %v is greater than balance of %v", int64(feePerKw),
|
2018-05-02 03:34:52 +03:00
|
|
|
newFee, baseBalance)
|
2018-02-25 06:19:46 +03:00
|
|
|
}
|
2017-11-26 22:50:39 +03:00
|
|
|
|
|
|
|
// If this new balance is below our reserve, then we can't accommodate
|
|
|
|
// the fee change, so we'll reject it.
|
2018-05-02 03:34:52 +03:00
|
|
|
balanceAfterFee := baseBalance - newFee
|
2017-11-26 22:50:39 +03:00
|
|
|
if balanceAfterFee.ToSatoshis() < lc.channelState.LocalChanCfg.ChanReserve {
|
|
|
|
return fmt.Errorf("cannot apply fee_update=%v sat/kw, "+
|
2018-04-29 14:36:59 +03:00
|
|
|
"new balance=%v would dip below channel reserve=%v",
|
2017-11-26 22:50:39 +03:00
|
|
|
int64(feePerKw),
|
2018-05-02 03:34:52 +03:00
|
|
|
balanceAfterFee.ToSatoshis(),
|
|
|
|
lc.channelState.LocalChanCfg.ChanReserve)
|
2017-11-26 22:50:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(halseth): should fail if fee update is unreasonable,
|
|
|
|
// as specified in BOLT#2.
|
|
|
|
// * COMMENT(roasbeef): can cross-check with our ideal fee rate
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-07-14 21:38:35 +03:00
|
|
|
// UpdateFee initiates a fee update for this channel. Must only be called by
|
|
|
|
// the channel initiator, and must be called before sending update_fee to
|
|
|
|
// the remote.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (lc *LightningChannel) UpdateFee(feePerKw chainfee.SatPerKWeight) error {
|
2017-07-14 21:38:35 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
|
|
|
// Only initiator can send fee update, so trying to send one as
|
2017-07-30 22:25:41 +03:00
|
|
|
// non-initiator will fail.
|
2017-07-14 21:38:35 +03:00
|
|
|
if !lc.channelState.IsInitiator {
|
2017-07-30 22:25:41 +03:00
|
|
|
return fmt.Errorf("local fee update as non-initiator")
|
2017-07-14 21:38:35 +03:00
|
|
|
}
|
|
|
|
|
2017-11-26 22:50:39 +03:00
|
|
|
// Ensure that the passed fee rate meets our current requirements.
|
|
|
|
if err := lc.validateFeeRate(feePerKw); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-01-10 14:23:57 +03:00
|
|
|
pd := &PaymentDescriptor{
|
|
|
|
LogIndex: lc.localUpdateLog.logIndex,
|
|
|
|
Amount: lnwire.NewMSatFromSatoshis(btcutil.Amount(feePerKw)),
|
|
|
|
EntryType: FeeUpdate,
|
|
|
|
}
|
|
|
|
|
|
|
|
lc.localUpdateLog.appendUpdate(pd)
|
2017-07-14 21:38:35 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReceiveUpdateFee handles an updated fee sent from remote. This method will
|
|
|
|
// return an error if called as channel initiator.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (lc *LightningChannel) ReceiveUpdateFee(feePerKw chainfee.SatPerKWeight) error {
|
2017-07-14 21:38:35 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
|
|
|
// Only initiator can send fee update, and we must fail if we receive
|
2017-07-30 22:25:41 +03:00
|
|
|
// fee update as initiator
|
2017-07-14 21:38:35 +03:00
|
|
|
if lc.channelState.IsInitiator {
|
2017-07-30 22:25:41 +03:00
|
|
|
return fmt.Errorf("received fee update as initiator")
|
2017-07-14 21:38:35 +03:00
|
|
|
}
|
|
|
|
|
2017-11-27 23:24:00 +03:00
|
|
|
// TODO(roasbeef): or just modify to use the other balance?
|
2019-01-10 14:23:57 +03:00
|
|
|
pd := &PaymentDescriptor{
|
|
|
|
LogIndex: lc.remoteUpdateLog.logIndex,
|
|
|
|
Amount: lnwire.NewMSatFromSatoshis(btcutil.Amount(feePerKw)),
|
|
|
|
EntryType: FeeUpdate,
|
|
|
|
}
|
2017-11-26 22:50:39 +03:00
|
|
|
|
2019-01-10 14:23:57 +03:00
|
|
|
lc.remoteUpdateLog.appendUpdate(pd)
|
2017-07-14 21:38:35 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-11-10 10:06:10 +03:00
|
|
|
// generateRevocation generates the revocation message for a given height.
|
2017-07-09 02:30:20 +03:00
|
|
|
func (lc *LightningChannel) generateRevocation(height uint64) (*lnwire.RevokeAndAck,
|
|
|
|
error) {
|
|
|
|
|
|
|
|
// Now that we've accept a new state transition, we send the remote
|
|
|
|
// party the revocation for our current commitment state.
|
|
|
|
revocationMsg := &lnwire.RevokeAndAck{}
|
|
|
|
commitSecret, err := lc.channelState.RevocationProducer.AtIndex(height)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
copy(revocationMsg.Revocation[:], commitSecret[:])
|
|
|
|
|
|
|
|
// Along with this revocation, we'll also send the _next_ commitment
|
|
|
|
// point that the remote party should use to create our next commitment
|
|
|
|
// transaction. We use a +2 here as we already gave them a look ahead
|
|
|
|
// of size one after the FundingLocked message was sent:
|
|
|
|
//
|
|
|
|
// 0: current revocation, 1: their "next" revocation, 2: this revocation
|
|
|
|
//
|
|
|
|
// We're revoking the current revocation. Once they receive this
|
|
|
|
// message they'll set the "current" revocation for us to their stored
|
|
|
|
// "next" revocation, and this revocation will become their new "next"
|
|
|
|
// revocation.
|
|
|
|
//
|
|
|
|
// Put simply in the window slides to the left by one.
|
|
|
|
nextCommitSecret, err := lc.channelState.RevocationProducer.AtIndex(
|
|
|
|
height + 2,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
revocationMsg.NextRevocationKey = input.ComputeCommitmentPoint(nextCommitSecret[:])
|
2017-07-09 02:30:20 +03:00
|
|
|
revocationMsg.ChanID = lnwire.NewChanIDFromOutPoint(
|
|
|
|
&lc.channelState.FundingOutpoint)
|
|
|
|
|
|
|
|
return revocationMsg, nil
|
|
|
|
}
|
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// CreateCooperativeCloseTx creates a transaction which if signed by both
|
2016-06-21 08:09:42 +03:00
|
|
|
// parties, then broadcast cooperatively closes an active channel. The creation
|
|
|
|
// of the closure transaction is modified by a boolean indicating if the party
|
|
|
|
// constructing the channel is the initiator of the closure. Currently it is
|
|
|
|
// expected that the initiator pays the transaction fees for the closing
|
|
|
|
// transaction in full.
|
2017-12-22 21:26:16 +03:00
|
|
|
func CreateCooperativeCloseTx(fundingTxIn wire.TxIn,
|
2017-03-25 02:20:05 +03:00
|
|
|
localDust, remoteDust, ourBalance, theirBalance btcutil.Amount,
|
2020-01-06 13:42:02 +03:00
|
|
|
ourDeliveryScript, theirDeliveryScript []byte) *wire.MsgTx {
|
2016-06-21 08:09:42 +03:00
|
|
|
|
|
|
|
// Construct the transaction to perform a cooperative closure of the
|
|
|
|
// channel. In the event that one side doesn't have any settled funds
|
|
|
|
// within the channel then a refund output for that particular side can
|
|
|
|
// be omitted.
|
2017-01-06 00:56:27 +03:00
|
|
|
closeTx := wire.NewMsgTx(2)
|
2017-12-22 21:26:16 +03:00
|
|
|
closeTx.AddTxIn(&fundingTxIn)
|
2016-06-21 08:09:42 +03:00
|
|
|
|
2017-03-25 02:20:05 +03:00
|
|
|
// Create both cooperative closure outputs, properly respecting the
|
|
|
|
// dust limits of both parties.
|
|
|
|
if ourBalance >= localDust {
|
2016-06-21 08:09:42 +03:00
|
|
|
closeTx.AddTxOut(&wire.TxOut{
|
|
|
|
PkScript: ourDeliveryScript,
|
|
|
|
Value: int64(ourBalance),
|
|
|
|
})
|
|
|
|
}
|
2017-03-25 02:20:05 +03:00
|
|
|
if theirBalance >= remoteDust {
|
2016-06-21 08:09:42 +03:00
|
|
|
closeTx.AddTxOut(&wire.TxOut{
|
|
|
|
PkScript: theirDeliveryScript,
|
|
|
|
Value: int64(theirBalance),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
txsort.InPlaceSort(closeTx)
|
|
|
|
|
|
|
|
return closeTx
|
|
|
|
}
|
2017-07-14 22:04:29 +03:00
|
|
|
|
|
|
|
// CalcFee returns the commitment fee to use for the given
|
|
|
|
// fee rate (fee-per-kw).
|
2019-10-31 05:43:05 +03:00
|
|
|
func (lc *LightningChannel) CalcFee(feeRate chainfee.SatPerKWeight) btcutil.Amount {
|
2020-03-06 18:11:46 +03:00
|
|
|
return feeRate.FeeForWeight(CommitWeight(lc.channelState.ChanType))
|
2017-07-14 22:04:29 +03:00
|
|
|
}
|
2017-09-13 15:07:51 +03:00
|
|
|
|
2019-08-24 02:04:30 +03:00
|
|
|
// MaxFeeRate returns the maximum fee rate given an allocation of the channel
|
|
|
|
// initiator's spendable balance. This can be useful to determine when we should
|
|
|
|
// stop proposing fee updates that exceed our maximum allocation.
|
|
|
|
//
|
|
|
|
// NOTE: This should only be used for channels in which the local commitment is
|
|
|
|
// the initiator.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (lc *LightningChannel) MaxFeeRate(maxAllocation float64) chainfee.SatPerKWeight {
|
2019-08-24 02:04:30 +03:00
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
// The maximum fee depends of the available balance that can be
|
|
|
|
// committed towards fees.
|
2020-02-19 14:27:42 +03:00
|
|
|
commit := lc.channelState.LocalCommitment
|
2019-08-24 02:04:30 +03:00
|
|
|
feeBalance := float64(
|
2020-02-19 14:27:42 +03:00
|
|
|
commit.LocalBalance.ToSatoshis() + commit.CommitFee,
|
2019-08-24 02:04:30 +03:00
|
|
|
)
|
|
|
|
maxFee := feeBalance * maxAllocation
|
2019-10-04 00:10:18 +03:00
|
|
|
|
|
|
|
// Ensure the fee rate doesn't dip below the fee floor.
|
2020-02-19 14:27:42 +03:00
|
|
|
_, weight := lc.availableBalance()
|
2019-10-04 00:10:18 +03:00
|
|
|
maxFeeRate := maxFee / (float64(weight) / 1000)
|
2019-10-31 05:43:05 +03:00
|
|
|
return chainfee.SatPerKWeight(
|
|
|
|
math.Max(maxFeeRate, float64(chainfee.FeePerKwFloor)),
|
|
|
|
)
|
2019-08-24 02:04:30 +03:00
|
|
|
}
|
|
|
|
|
2017-09-13 15:07:51 +03:00
|
|
|
// RemoteNextRevocation returns the channelState's RemoteNextRevocation.
|
|
|
|
func (lc *LightningChannel) RemoteNextRevocation() *btcec.PublicKey {
|
2017-11-24 07:02:55 +03:00
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
2017-09-13 15:07:51 +03:00
|
|
|
|
|
|
|
return lc.channelState.RemoteNextRevocation
|
|
|
|
}
|
2017-11-24 07:02:55 +03:00
|
|
|
|
|
|
|
// IsInitiator returns true if we were the ones that initiated the funding
|
|
|
|
// workflow which led to the creation of this channel. Otherwise, it returns
|
|
|
|
// false.
|
|
|
|
func (lc *LightningChannel) IsInitiator() bool {
|
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
return lc.channelState.IsInitiator
|
|
|
|
}
|
|
|
|
|
|
|
|
// CommitFeeRate returns the current fee rate of the commitment transaction in
|
|
|
|
// units of sat-per-kw.
|
2019-10-31 05:43:05 +03:00
|
|
|
func (lc *LightningChannel) CommitFeeRate() chainfee.SatPerKWeight {
|
2017-11-24 07:02:55 +03:00
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
2019-10-31 05:43:05 +03:00
|
|
|
return chainfee.SatPerKWeight(lc.channelState.LocalCommitment.FeePerKw)
|
2017-11-24 07:02:55 +03:00
|
|
|
}
|
2017-12-07 03:31:52 +03:00
|
|
|
|
|
|
|
// IsPending returns true if the channel's funding transaction has been fully
|
|
|
|
// confirmed, and false otherwise.
|
|
|
|
func (lc *LightningChannel) IsPending() bool {
|
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
return lc.channelState.IsPending
|
|
|
|
}
|
2017-11-21 10:57:33 +03:00
|
|
|
|
2018-11-20 17:09:45 +03:00
|
|
|
// State provides access to the channel's internal state.
|
2017-11-21 10:57:33 +03:00
|
|
|
func (lc *LightningChannel) State() *channeldb.OpenChannel {
|
|
|
|
return lc.channelState
|
|
|
|
}
|
|
|
|
|
2019-09-06 14:14:40 +03:00
|
|
|
// MarkBorked marks the event when the channel as reached an irreconcilable
|
|
|
|
// state, such as a channel breach or state desynchronization. Borked channels
|
|
|
|
// should never be added to the switch.
|
|
|
|
func (lc *LightningChannel) MarkBorked() error {
|
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
|
|
|
return lc.channelState.MarkBorked()
|
|
|
|
}
|
|
|
|
|
2018-05-18 16:19:40 +03:00
|
|
|
// MarkCommitmentBroadcasted marks the channel as a commitment transaction has
|
|
|
|
// been broadcast, either our own or the remote, and we should watch the chain
|
2020-02-21 14:24:23 +03:00
|
|
|
// for it to confirm before taking any further action. It takes a boolean which
|
|
|
|
// indicates whether we initiated the close.
|
|
|
|
func (lc *LightningChannel) MarkCommitmentBroadcasted(tx *wire.MsgTx,
|
|
|
|
locallyInitiated bool) error {
|
|
|
|
|
2018-05-18 16:19:40 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2020-02-21 14:24:23 +03:00
|
|
|
return lc.channelState.MarkCommitmentBroadcasted(tx, locallyInitiated)
|
2018-05-18 16:19:40 +03:00
|
|
|
}
|
|
|
|
|
2019-12-05 00:30:15 +03:00
|
|
|
// MarkCoopBroadcasted marks the channel as a cooperative close transaction has
|
|
|
|
// been broadcast, and that we should watch the chain for it to confirm before
|
2020-02-21 14:24:23 +03:00
|
|
|
// taking any further action. It takes a locally initiated bool which is true
|
|
|
|
// if we initiated the cooperative close.
|
|
|
|
func (lc *LightningChannel) MarkCoopBroadcasted(tx *wire.MsgTx,
|
|
|
|
localInitiated bool) error {
|
|
|
|
|
2019-12-05 00:30:15 +03:00
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
2020-02-21 14:24:23 +03:00
|
|
|
return lc.channelState.MarkCoopBroadcasted(tx, localInitiated)
|
2019-12-05 00:30:15 +03:00
|
|
|
}
|
|
|
|
|
2019-09-06 14:14:40 +03:00
|
|
|
// MarkDataLoss marks sets the channel status to LocalDataLoss and stores the
|
|
|
|
// passed commitPoint for use to retrieve funds in case the remote force closes
|
|
|
|
// the channel.
|
|
|
|
func (lc *LightningChannel) MarkDataLoss(commitPoint *btcec.PublicKey) error {
|
|
|
|
lc.Lock()
|
|
|
|
defer lc.Unlock()
|
|
|
|
|
|
|
|
return lc.channelState.MarkDataLoss(commitPoint)
|
|
|
|
}
|
|
|
|
|
2018-01-17 05:10:58 +03:00
|
|
|
// ActiveHtlcs returns a slice of HTLC's which are currently active on *both*
|
|
|
|
// commitment transactions.
|
|
|
|
func (lc *LightningChannel) ActiveHtlcs() []channeldb.HTLC {
|
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
// We'll only return HTLC's that are locked into *both* commitment
|
|
|
|
// transactions. So we'll iterate through their set of HTLC's to note
|
2018-02-07 06:11:11 +03:00
|
|
|
// which ones are present on their commitment.
|
2018-01-17 05:10:58 +03:00
|
|
|
remoteHtlcs := make(map[[32]byte]struct{})
|
|
|
|
for _, htlc := range lc.channelState.RemoteCommitment.Htlcs {
|
|
|
|
onionHash := sha256.Sum256(htlc.OnionBlob[:])
|
|
|
|
remoteHtlcs[onionHash] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2018-01-17 05:17:18 +03:00
|
|
|
// Now that we know which HTLC's they have, we'll only mark the HTLC's
|
2018-01-17 05:10:58 +03:00
|
|
|
// as active if *we* know them as well.
|
|
|
|
activeHtlcs := make([]channeldb.HTLC, 0, len(remoteHtlcs))
|
|
|
|
for _, htlc := range lc.channelState.LocalCommitment.Htlcs {
|
|
|
|
if _, ok := remoteHtlcs[sha256.Sum256(htlc.OnionBlob[:])]; !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
activeHtlcs = append(activeHtlcs, htlc)
|
|
|
|
}
|
|
|
|
|
|
|
|
return activeHtlcs
|
|
|
|
}
|
2017-11-29 16:20:02 +03:00
|
|
|
|
|
|
|
// LocalChanReserve returns our local ChanReserve requirement for the remote party.
|
|
|
|
func (lc *LightningChannel) LocalChanReserve() btcutil.Amount {
|
2020-01-06 13:42:02 +03:00
|
|
|
return lc.channelState.LocalChanCfg.ChanReserve
|
2017-11-29 16:20:02 +03:00
|
|
|
}
|
2018-02-28 07:01:41 +03:00
|
|
|
|
2018-04-24 08:08:03 +03:00
|
|
|
// NextLocalHtlcIndex returns the next unallocated local htlc index. To ensure
|
|
|
|
// this always returns the next index that has been not been allocated, this
|
|
|
|
// will first try to examine any pending commitments, before falling back to the
|
|
|
|
// last locked-in local commitment.
|
|
|
|
func (lc *LightningChannel) NextLocalHtlcIndex() (uint64, error) {
|
2018-02-28 07:01:41 +03:00
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
2018-04-24 08:08:03 +03:00
|
|
|
return lc.channelState.NextLocalHtlcIndex()
|
2018-02-28 07:01:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// RemoteCommitHeight returns the commitment height of the remote chain.
|
|
|
|
func (lc *LightningChannel) RemoteCommitHeight() uint64 {
|
|
|
|
lc.RLock()
|
|
|
|
defer lc.RUnlock()
|
|
|
|
|
|
|
|
return lc.channelState.RemoteCommitment.CommitHeight
|
|
|
|
}
|
2018-08-22 10:32:43 +03:00
|
|
|
|
|
|
|
// FwdMinHtlc returns the minimum HTLC value required by the remote node, i.e.
|
|
|
|
// the minimum value HTLC we can forward on this channel.
|
|
|
|
func (lc *LightningChannel) FwdMinHtlc() lnwire.MilliSatoshi {
|
2020-01-06 13:42:02 +03:00
|
|
|
return lc.channelState.LocalChanCfg.MinHTLC
|
2018-08-22 10:32:43 +03:00
|
|
|
}
|