• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 10418626636

16 Aug 2024 10:36AM UTC coverage: 58.722% (+0.2%) from 58.558%
10418626636

Pull #9011

github

ziggie1984
docs: update release-notes.
Pull Request #9011: Fix TimeStamp issue in the Gossip Syncer

58 of 70 new or added lines in 3 files covered. (82.86%)

117 existing lines in 15 files now uncovered.

126269 of 215030 relevant lines covered (58.72%)

28151.42 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.4
/contractcourt/channel_arbitrator.go
1
package contractcourt
2

3
import (
4
        "bytes"
5
        "context"
6
        "errors"
7
        "fmt"
8
        "math"
9
        "sync"
10
        "sync/atomic"
11
        "time"
12

13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/chaincfg/chainhash"
15
        "github.com/btcsuite/btcd/txscript"
16
        "github.com/btcsuite/btcd/wire"
17
        "github.com/lightningnetwork/lnd/channeldb"
18
        "github.com/lightningnetwork/lnd/channeldb/models"
19
        "github.com/lightningnetwork/lnd/fn"
20
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
21
        "github.com/lightningnetwork/lnd/input"
22
        "github.com/lightningnetwork/lnd/invoices"
23
        "github.com/lightningnetwork/lnd/kvdb"
24
        "github.com/lightningnetwork/lnd/labels"
25
        "github.com/lightningnetwork/lnd/lntypes"
26
        "github.com/lightningnetwork/lnd/lnutils"
27
        "github.com/lightningnetwork/lnd/lnwallet"
28
        "github.com/lightningnetwork/lnd/lnwire"
29
        "github.com/lightningnetwork/lnd/sweep"
30
)
31

32
var (
33
        // errAlreadyForceClosed is an error returned when we attempt to force
34
        // close a channel that's already in the process of doing so.
35
        errAlreadyForceClosed = errors.New("channel is already in the " +
36
                "process of being force closed")
37
)
38

39
const (
40
        // arbitratorBlockBufferSize is the size of the buffer we give to each
41
        // channel arbitrator.
42
        arbitratorBlockBufferSize = 20
43

44
        // AnchorOutputValue is the output value for the anchor output of an
45
        // anchor channel.
46
        // See BOLT 03 for more details:
47
        // https://github.com/lightning/bolts/blob/master/03-transactions.md
48
        AnchorOutputValue = btcutil.Amount(330)
49
)
50

51
// WitnessSubscription represents an intent to be notified once new witnesses
52
// are discovered by various active contract resolvers. A contract resolver may
53
// use this to be notified of when it can satisfy an incoming contract after we
54
// discover the witness for an outgoing contract.
55
type WitnessSubscription struct {
56
        // WitnessUpdates is a channel that newly discovered witnesses will be
57
        // sent over.
58
        //
59
        // TODO(roasbeef): couple with WitnessType?
60
        WitnessUpdates <-chan lntypes.Preimage
61

62
        // CancelSubscription is a function closure that should be used by a
63
        // client to cancel the subscription once they are no longer interested
64
        // in receiving new updates.
65
        CancelSubscription func()
66
}
67

68
// WitnessBeacon is a global beacon of witnesses. Contract resolvers will use
69
// this interface to lookup witnesses (preimages typically) of contracts
70
// they're trying to resolve, add new preimages they resolve, and finally
71
// receive new updates each new time a preimage is discovered.
72
//
73
// TODO(roasbeef): need to delete the pre-images once we've used them
74
// and have been sufficiently confirmed?
75
type WitnessBeacon interface {
76
        // SubscribeUpdates returns a channel that will be sent upon *each* time
77
        // a new preimage is discovered.
78
        SubscribeUpdates(chanID lnwire.ShortChannelID, htlc *channeldb.HTLC,
79
                payload *hop.Payload,
80
                nextHopOnionBlob []byte) (*WitnessSubscription, error)
81

82
        // LookupPreImage attempts to lookup a preimage in the global cache.
83
        // True is returned for the second argument if the preimage is found.
84
        LookupPreimage(payhash lntypes.Hash) (lntypes.Preimage, bool)
85

86
        // AddPreimages adds a batch of newly discovered preimages to the global
87
        // cache, and also signals any subscribers of the newly discovered
88
        // witness.
89
        AddPreimages(preimages ...lntypes.Preimage) error
90
}
91

92
// ArbChannel is an abstraction that allows the channel arbitrator to interact
93
// with an open channel.
94
type ArbChannel interface {
95
        // ForceCloseChan should force close the contract that this attendant
96
        // is watching over. We'll use this when we decide that we need to go
97
        // to chain. It should in addition tell the switch to remove the
98
        // corresponding link, such that we won't accept any new updates. The
99
        // returned summary contains all items needed to eventually resolve all
100
        // outputs on chain.
101
        ForceCloseChan() (*lnwallet.LocalForceCloseSummary, error)
102

103
        // NewAnchorResolutions returns the anchor resolutions for currently
104
        // valid commitment transactions.
105
        NewAnchorResolutions() (*lnwallet.AnchorResolutions, error)
106
}
107

108
// ChannelArbitratorConfig contains all the functionality that the
109
// ChannelArbitrator needs in order to properly arbitrate any contract dispute
110
// on chain.
111
type ChannelArbitratorConfig struct {
112
        // ChanPoint is the channel point that uniquely identifies this
113
        // channel.
114
        ChanPoint wire.OutPoint
115

116
        // Channel is the full channel data structure. For legacy channels, this
117
        // field may not always be set after a restart.
118
        Channel ArbChannel
119

120
        // ShortChanID describes the exact location of the channel within the
121
        // chain. We'll use this to address any messages that we need to send
122
        // to the switch during contract resolution.
123
        ShortChanID lnwire.ShortChannelID
124

125
        // ChainEvents is an active subscription to the chain watcher for this
126
        // channel to be notified of any on-chain activity related to this
127
        // channel.
128
        ChainEvents *ChainEventSubscription
129

130
        // MarkCommitmentBroadcasted should mark the channel as the commitment
131
        // being broadcast, and we are waiting for the commitment to confirm.
132
        MarkCommitmentBroadcasted func(*wire.MsgTx, lntypes.ChannelParty) error
133

134
        // MarkChannelClosed marks the channel closed in the database, with the
135
        // passed close summary. After this method successfully returns we can
136
        // no longer expect to receive chain events for this channel, and must
137
        // be able to recover from a failure without getting the close event
138
        // again. It takes an optional channel status which will update the
139
        // channel status in the record that we keep of historical channels.
140
        MarkChannelClosed func(*channeldb.ChannelCloseSummary,
141
                ...channeldb.ChannelStatus) error
142

143
        // IsPendingClose is a boolean indicating whether the channel is marked
144
        // as pending close in the database.
145
        IsPendingClose bool
146

147
        // ClosingHeight is the height at which the channel was closed. Note
148
        // that this value is only valid if IsPendingClose is true.
149
        ClosingHeight uint32
150

151
        // CloseType is the type of the close event in case IsPendingClose is
152
        // true. Otherwise this value is unset.
153
        CloseType channeldb.ClosureType
154

155
        // MarkChannelResolved is a function closure that serves to mark a
156
        // channel as "fully resolved". A channel itself can be considered
157
        // fully resolved once all active contracts have individually been
158
        // fully resolved.
159
        //
160
        // TODO(roasbeef): need RPC's to combine for pendingchannels RPC
161
        MarkChannelResolved func() error
162

163
        // PutResolverReport records a resolver report for the channel. If the
164
        // transaction provided is nil, the function should write the report
165
        // in a new transaction.
166
        PutResolverReport func(tx kvdb.RwTx,
167
                report *channeldb.ResolverReport) error
168

169
        // FetchHistoricalChannel retrieves the historical state of a channel.
170
        // This is mostly used to supplement the ContractResolvers with
171
        // additional information required for proper contract resolution.
172
        FetchHistoricalChannel func() (*channeldb.OpenChannel, error)
173

174
        // FindOutgoingHTLCDeadline returns the deadline in absolute block
175
        // height for the specified outgoing HTLC. For an outgoing HTLC, its
176
        // deadline is defined by the timeout height of its corresponding
177
        // incoming HTLC - this is the expiry height the that remote peer can
178
        // spend his/her outgoing HTLC via the timeout path.
179
        FindOutgoingHTLCDeadline func(htlc channeldb.HTLC) fn.Option[int32]
180

181
        ChainArbitratorConfig
182
}
183

184
// ReportOutputType describes the type of output that is being reported
185
// on.
186
type ReportOutputType uint8
187

188
const (
189
        // ReportOutputIncomingHtlc is an incoming hash time locked contract on
190
        // the commitment tx.
191
        ReportOutputIncomingHtlc ReportOutputType = iota
192

193
        // ReportOutputOutgoingHtlc is an outgoing hash time locked contract on
194
        // the commitment tx.
195
        ReportOutputOutgoingHtlc
196

197
        // ReportOutputUnencumbered is an uncontested output on the commitment
198
        // transaction paying to us directly.
199
        ReportOutputUnencumbered
200

201
        // ReportOutputAnchor is an anchor output on the commitment tx.
202
        ReportOutputAnchor
203
)
204

205
// ContractReport provides a summary of a commitment tx output.
206
type ContractReport struct {
207
        // Outpoint is the final output that will be swept back to the wallet.
208
        Outpoint wire.OutPoint
209

210
        // Type indicates the type of the reported output.
211
        Type ReportOutputType
212

213
        // Amount is the final value that will be swept in back to the wallet.
214
        Amount btcutil.Amount
215

216
        // MaturityHeight is the absolute block height that this output will
217
        // mature at.
218
        MaturityHeight uint32
219

220
        // Stage indicates whether the htlc is in the CLTV-timeout stage (1) or
221
        // the CSV-delay stage (2). A stage 1 htlc's maturity height will be set
222
        // to its expiry height, while a stage 2 htlc's maturity height will be
223
        // set to its confirmation height plus the maturity requirement.
224
        Stage uint32
225

226
        // LimboBalance is the total number of frozen coins within this
227
        // contract.
228
        LimboBalance btcutil.Amount
229

230
        // RecoveredBalance is the total value that has been successfully swept
231
        // back to the user's wallet.
232
        RecoveredBalance btcutil.Amount
233
}
234

235
// resolverReport creates a resolve report using some of the information in the
236
// contract report.
237
func (c *ContractReport) resolverReport(spendTx *chainhash.Hash,
238
        resolverType channeldb.ResolverType,
239
        outcome channeldb.ResolverOutcome) *channeldb.ResolverReport {
13✔
240

13✔
241
        return &channeldb.ResolverReport{
13✔
242
                OutPoint:        c.Outpoint,
13✔
243
                Amount:          c.Amount,
13✔
244
                ResolverType:    resolverType,
13✔
245
                ResolverOutcome: outcome,
13✔
246
                SpendTxID:       spendTx,
13✔
247
        }
13✔
248
}
13✔
249

250
// htlcSet represents the set of active HTLCs on a given commitment
251
// transaction.
252
type htlcSet struct {
253
        // incomingHTLCs is a map of all incoming HTLCs on the target
254
        // commitment transaction. We may potentially go onchain to claim the
255
        // funds sent to us within this set.
256
        incomingHTLCs map[uint64]channeldb.HTLC
257

258
        // outgoingHTLCs is a map of all outgoing HTLCs on the target
259
        // commitment transaction. We may potentially go onchain to reclaim the
260
        // funds that are currently in limbo.
261
        outgoingHTLCs map[uint64]channeldb.HTLC
262
}
263

264
// newHtlcSet constructs a new HTLC set from a slice of HTLC's.
265
func newHtlcSet(htlcs []channeldb.HTLC) htlcSet {
49✔
266
        outHTLCs := make(map[uint64]channeldb.HTLC)
49✔
267
        inHTLCs := make(map[uint64]channeldb.HTLC)
49✔
268
        for _, htlc := range htlcs {
83✔
269
                if htlc.Incoming {
43✔
270
                        inHTLCs[htlc.HtlcIndex] = htlc
9✔
271
                        continue
9✔
272
                }
273

274
                outHTLCs[htlc.HtlcIndex] = htlc
28✔
275
        }
276

277
        return htlcSet{
49✔
278
                incomingHTLCs: inHTLCs,
49✔
279
                outgoingHTLCs: outHTLCs,
49✔
280
        }
49✔
281
}
282

283
// HtlcSetKey is a two-tuple that uniquely identifies a set of HTLCs on a
284
// commitment transaction.
285
type HtlcSetKey struct {
286
        // IsRemote denotes if the HTLCs are on the remote commitment
287
        // transaction.
288
        IsRemote bool
289

290
        // IsPending denotes if the commitment transaction that HTLCS are on
291
        // are pending (the higher of two unrevoked commitments).
292
        IsPending bool
293
}
294

295
var (
296
        // LocalHtlcSet is the HtlcSetKey used for local commitments.
297
        LocalHtlcSet = HtlcSetKey{IsRemote: false, IsPending: false}
298

299
        // RemoteHtlcSet is the HtlcSetKey used for remote commitments.
300
        RemoteHtlcSet = HtlcSetKey{IsRemote: true, IsPending: false}
301

302
        // RemotePendingHtlcSet is the HtlcSetKey used for dangling remote
303
        // commitment transactions.
304
        RemotePendingHtlcSet = HtlcSetKey{IsRemote: true, IsPending: true}
305
)
306

307
// String returns a human readable string describing the target HtlcSetKey.
308
func (h HtlcSetKey) String() string {
11✔
309
        switch h {
11✔
310
        case LocalHtlcSet:
7✔
311
                return "LocalHtlcSet"
7✔
312
        case RemoteHtlcSet:
5✔
313
                return "RemoteHtlcSet"
5✔
314
        case RemotePendingHtlcSet:
2✔
315
                return "RemotePendingHtlcSet"
2✔
316
        default:
×
317
                return "unknown HtlcSetKey"
×
318
        }
319
}
320

321
// ChannelArbitrator is the on-chain arbitrator for a particular channel. The
322
// struct will keep in sync with the current set of HTLCs on the commitment
323
// transaction. The job of the attendant is to go on-chain to either settle or
324
// cancel an HTLC as necessary iff: an HTLC times out, or we known the
325
// pre-image to an HTLC, but it wasn't settled by the link off-chain. The
326
// ChannelArbitrator will factor in an expected confirmation delta when
327
// broadcasting to ensure that we avoid any possibility of race conditions, and
328
// sweep the output(s) without contest.
329
type ChannelArbitrator struct {
330
        started int32 // To be used atomically.
331
        stopped int32 // To be used atomically.
332

333
        // startTimestamp is the time when this ChannelArbitrator was started.
334
        startTimestamp time.Time
335

336
        // log is a persistent log that the attendant will use to checkpoint
337
        // its next action, and the state of any unresolved contracts.
338
        log ArbitratorLog
339

340
        // activeHTLCs is the set of active incoming/outgoing HTLC's on all
341
        // currently valid commitment transactions.
342
        activeHTLCs map[HtlcSetKey]htlcSet
343

344
        // unmergedSet is used to update the activeHTLCs map in two callsites:
345
        // checkLocalChainActions and sweepAnchors. It contains the latest
346
        // updates from the link. It is not deleted from, its entries may be
347
        // replaced on subsequent calls to notifyContractUpdate.
348
        unmergedSet map[HtlcSetKey]htlcSet
349
        unmergedMtx sync.RWMutex
350

351
        // cfg contains all the functionality that the ChannelArbitrator requires
352
        // to do its duty.
353
        cfg ChannelArbitratorConfig
354

355
        // blocks is a channel that the arbitrator will receive new blocks on.
356
        // This channel should be buffered by so that it does not block the
357
        // sender.
358
        blocks chan int32
359

360
        // signalUpdates is a channel that any new live signals for the channel
361
        // we're watching over will be sent.
362
        signalUpdates chan *signalUpdateMsg
363

364
        // activeResolvers is a slice of any active resolvers. This is used to
365
        // be able to signal them for shutdown in the case that we shutdown.
366
        activeResolvers []ContractResolver
367

368
        // activeResolversLock prevents simultaneous read and write to the
369
        // resolvers slice.
370
        activeResolversLock sync.RWMutex
371

372
        // resolutionSignal is a channel that will be sent upon by contract
373
        // resolvers once their contract has been fully resolved. With each
374
        // send, we'll check to see if the contract is fully resolved.
375
        resolutionSignal chan struct{}
376

377
        // forceCloseReqs is a channel that requests to forcibly close the
378
        // contract will be sent over.
379
        forceCloseReqs chan *forceCloseReq
380

381
        // state is the current state of the arbitrator. This state is examined
382
        // upon start up to decide which actions to take.
383
        state ArbitratorState
384

385
        wg   sync.WaitGroup
386
        quit chan struct{}
387
}
388

389
// NewChannelArbitrator returns a new instance of a ChannelArbitrator backed by
390
// the passed config struct.
391
func NewChannelArbitrator(cfg ChannelArbitratorConfig,
392
        htlcSets map[HtlcSetKey]htlcSet, log ArbitratorLog) *ChannelArbitrator {
53✔
393

53✔
394
        // Create a new map for unmerged HTLC's as we will overwrite the values
53✔
395
        // and want to avoid modifying activeHTLCs directly. This soft copying
53✔
396
        // is done to ensure that activeHTLCs isn't reset as an empty map later
53✔
397
        // on.
53✔
398
        unmerged := make(map[HtlcSetKey]htlcSet)
53✔
399
        unmerged[LocalHtlcSet] = htlcSets[LocalHtlcSet]
53✔
400
        unmerged[RemoteHtlcSet] = htlcSets[RemoteHtlcSet]
53✔
401

53✔
402
        // If the pending set exists, write that as well.
53✔
403
        if _, ok := htlcSets[RemotePendingHtlcSet]; ok {
53✔
404
                unmerged[RemotePendingHtlcSet] = htlcSets[RemotePendingHtlcSet]
×
405
        }
×
406

407
        return &ChannelArbitrator{
53✔
408
                log:              log,
53✔
409
                blocks:           make(chan int32, arbitratorBlockBufferSize),
53✔
410
                signalUpdates:    make(chan *signalUpdateMsg),
53✔
411
                resolutionSignal: make(chan struct{}),
53✔
412
                forceCloseReqs:   make(chan *forceCloseReq),
53✔
413
                activeHTLCs:      htlcSets,
53✔
414
                unmergedSet:      unmerged,
53✔
415
                cfg:              cfg,
53✔
416
                quit:             make(chan struct{}),
53✔
417
        }
53✔
418
}
419

420
// chanArbStartState contains the information from disk that we need to start
421
// up a channel arbitrator.
422
type chanArbStartState struct {
423
        currentState ArbitratorState
424
        commitSet    *CommitSet
425
}
426

427
// getStartState retrieves the information from disk that our channel arbitrator
428
// requires to start.
429
func (c *ChannelArbitrator) getStartState(tx kvdb.RTx) (*chanArbStartState,
430
        error) {
51✔
431

51✔
432
        // First, we'll read our last state from disk, so our internal state
51✔
433
        // machine can act accordingly.
51✔
434
        state, err := c.log.CurrentState(tx)
51✔
435
        if err != nil {
51✔
436
                return nil, err
×
437
        }
×
438

439
        // Next we'll fetch our confirmed commitment set. This will only exist
440
        // if the channel has been closed out on chain for modern nodes. For
441
        // older nodes, this won't be found at all, and will rely on the
442
        // existing written chain actions. Additionally, if this channel hasn't
443
        // logged any actions in the log, then this field won't be present.
444
        commitSet, err := c.log.FetchConfirmedCommitSet(tx)
51✔
445
        if err != nil && err != errNoCommitSet && err != errScopeBucketNoExist {
51✔
446
                return nil, err
×
447
        }
×
448

449
        return &chanArbStartState{
51✔
450
                currentState: state,
51✔
451
                commitSet:    commitSet,
51✔
452
        }, nil
51✔
453
}
454

455
// Start starts all the goroutines that the ChannelArbitrator needs to operate.
456
// If takes a start state, which will be looked up on disk if it is not
457
// provided.
458
func (c *ChannelArbitrator) Start(state *chanArbStartState) error {
51✔
459
        if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
51✔
460
                return nil
×
461
        }
×
462
        c.startTimestamp = c.cfg.Clock.Now()
51✔
463

51✔
464
        // If the state passed in is nil, we look it up now.
51✔
465
        if state == nil {
91✔
466
                var err error
40✔
467
                state, err = c.getStartState(nil)
40✔
468
                if err != nil {
40✔
469
                        return err
×
470
                }
×
471
        }
472

473
        log.Debugf("Starting ChannelArbitrator(%v), htlc_set=%v, state=%v",
51✔
474
                c.cfg.ChanPoint, lnutils.SpewLogClosure(c.activeHTLCs),
51✔
475
                state.currentState)
51✔
476

51✔
477
        // Set our state from our starting state.
51✔
478
        c.state = state.currentState
51✔
479

51✔
480
        _, bestHeight, err := c.cfg.ChainIO.GetBestBlock()
51✔
481
        if err != nil {
51✔
482
                return err
×
483
        }
×
484

485
        // If the channel has been marked pending close in the database, and we
486
        // haven't transitioned the state machine to StateContractClosed (or a
487
        // succeeding state), then a state transition most likely failed. We'll
488
        // try to recover from this by manually advancing the state by setting
489
        // the corresponding close trigger.
490
        trigger := chainTrigger
51✔
491
        triggerHeight := uint32(bestHeight)
51✔
492
        if c.cfg.IsPendingClose {
59✔
493
                switch c.state {
8✔
494
                case StateDefault:
4✔
495
                        fallthrough
4✔
496
                case StateBroadcastCommit:
5✔
497
                        fallthrough
5✔
498
                case StateCommitmentBroadcasted:
5✔
499
                        switch c.cfg.CloseType {
5✔
500

501
                        case channeldb.CooperativeClose:
1✔
502
                                trigger = coopCloseTrigger
1✔
503

504
                        case channeldb.BreachClose:
1✔
505
                                trigger = breachCloseTrigger
1✔
506

507
                        case channeldb.LocalForceClose:
1✔
508
                                trigger = localCloseTrigger
1✔
509

510
                        case channeldb.RemoteForceClose:
2✔
511
                                trigger = remoteCloseTrigger
2✔
512
                        }
513

514
                        log.Warnf("ChannelArbitrator(%v): detected stalled "+
5✔
515
                                "state=%v for closed channel",
5✔
516
                                c.cfg.ChanPoint, c.state)
5✔
517
                }
518

519
                triggerHeight = c.cfg.ClosingHeight
8✔
520
        }
521

522
        log.Infof("ChannelArbitrator(%v): starting state=%v, trigger=%v, "+
51✔
523
                "triggerHeight=%v", c.cfg.ChanPoint, c.state, trigger,
51✔
524
                triggerHeight)
51✔
525

51✔
526
        // We'll now attempt to advance our state forward based on the current
51✔
527
        // on-chain state, and our set of active contracts.
51✔
528
        startingState := c.state
51✔
529
        nextState, _, err := c.advanceState(
51✔
530
                triggerHeight, trigger, state.commitSet,
51✔
531
        )
51✔
532
        if err != nil {
53✔
533
                switch err {
2✔
534

535
                // If we detect that we tried to fetch resolutions, but failed,
536
                // this channel was marked closed in the database before
537
                // resolutions successfully written. In this case there is not
538
                // much we can do, so we don't return the error.
539
                case errScopeBucketNoExist:
×
540
                        fallthrough
×
541
                case errNoResolutions:
1✔
542
                        log.Warnf("ChannelArbitrator(%v): detected closed"+
1✔
543
                                "channel with no contract resolutions written.",
1✔
544
                                c.cfg.ChanPoint)
1✔
545

546
                default:
1✔
547
                        return err
1✔
548
                }
549
        }
550

551
        // If we start and ended at the awaiting full resolution state, then
552
        // we'll relaunch our set of unresolved contracts.
553
        if startingState == StateWaitingFullResolution &&
50✔
554
                nextState == StateWaitingFullResolution {
54✔
555

4✔
556
                // In order to relaunch the resolvers, we'll need to fetch the
4✔
557
                // set of HTLCs that were present in the commitment transaction
4✔
558
                // at the time it was confirmed. commitSet.ConfCommitKey can't
4✔
559
                // be nil at this point since we're in
4✔
560
                // StateWaitingFullResolution. We can only be in
4✔
561
                // StateWaitingFullResolution after we've transitioned from
4✔
562
                // StateContractClosed which can only be triggered by the local
4✔
563
                // or remote close trigger. This trigger is only fired when we
4✔
564
                // receive a chain event from the chain watcher that the
4✔
565
                // commitment has been confirmed on chain, and before we
4✔
566
                // advance our state step, we call InsertConfirmedCommitSet.
4✔
567
                err := c.relaunchResolvers(state.commitSet, triggerHeight)
4✔
568
                if err != nil {
4✔
569
                        return err
×
570
                }
×
571
        }
572

573
        c.wg.Add(1)
50✔
574
        go c.channelAttendant(bestHeight)
50✔
575
        return nil
50✔
576
}
577

578
// maybeAugmentTaprootResolvers will update the contract resolution information
579
// for taproot channels. This ensures that all the resolvers have the latest
580
// resolution, which may also include data such as the control block and tap
581
// tweaks.
582
func maybeAugmentTaprootResolvers(chanType channeldb.ChannelType,
583
        resolver ContractResolver,
584
        contractResolutions *ContractResolutions) {
4✔
585

4✔
586
        if !chanType.IsTaproot() {
8✔
587
                return
4✔
588
        }
4✔
589

590
        // The on disk resolutions contains all the ctrl block
591
        // information, so we'll set that now for the relevant
592
        // resolvers.
593
        switch r := resolver.(type) {
3✔
594
        case *commitSweepResolver:
3✔
595
                if contractResolutions.CommitResolution != nil {
6✔
596
                        //nolint:lll
3✔
597
                        r.commitResolution = *contractResolutions.CommitResolution
3✔
598
                }
3✔
599
        case *htlcOutgoingContestResolver:
3✔
600
                //nolint:lll
3✔
601
                htlcResolutions := contractResolutions.HtlcResolutions.OutgoingHTLCs
3✔
602
                for _, htlcRes := range htlcResolutions {
6✔
603
                        htlcRes := htlcRes
3✔
604

3✔
605
                        if r.htlcResolution.ClaimOutpoint ==
3✔
606
                                htlcRes.ClaimOutpoint {
6✔
607

3✔
608
                                r.htlcResolution = htlcRes
3✔
609
                        }
3✔
610
                }
611

612
        case *htlcTimeoutResolver:
3✔
613
                //nolint:lll
3✔
614
                htlcResolutions := contractResolutions.HtlcResolutions.OutgoingHTLCs
3✔
615
                for _, htlcRes := range htlcResolutions {
6✔
616
                        htlcRes := htlcRes
3✔
617

3✔
618
                        if r.htlcResolution.ClaimOutpoint ==
3✔
619
                                htlcRes.ClaimOutpoint {
6✔
620

3✔
621
                                r.htlcResolution = htlcRes
3✔
622
                        }
3✔
623
                }
624

625
        case *htlcIncomingContestResolver:
3✔
626
                //nolint:lll
3✔
627
                htlcResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs
3✔
628
                for _, htlcRes := range htlcResolutions {
6✔
629
                        htlcRes := htlcRes
3✔
630

3✔
631
                        if r.htlcResolution.ClaimOutpoint ==
3✔
632
                                htlcRes.ClaimOutpoint {
6✔
633

3✔
634
                                r.htlcResolution = htlcRes
3✔
635
                        }
3✔
636
                }
637
        case *htlcSuccessResolver:
×
638
                //nolint:lll
×
639
                htlcResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs
×
640
                for _, htlcRes := range htlcResolutions {
×
641
                        htlcRes := htlcRes
×
642

×
643
                        if r.htlcResolution.ClaimOutpoint ==
×
644
                                htlcRes.ClaimOutpoint {
×
645

×
646
                                r.htlcResolution = htlcRes
×
647
                        }
×
648
                }
649
        }
650
}
651

652
// relauchResolvers relaunches the set of resolvers for unresolved contracts in
653
// order to provide them with information that's not immediately available upon
654
// starting the ChannelArbitrator. This information should ideally be stored in
655
// the database, so this only serves as a intermediate work-around to prevent a
656
// migration.
657
func (c *ChannelArbitrator) relaunchResolvers(commitSet *CommitSet,
658
        heightHint uint32) error {
4✔
659

4✔
660
        // We'll now query our log to see if there are any active unresolved
4✔
661
        // contracts. If this is the case, then we'll relaunch all contract
4✔
662
        // resolvers.
4✔
663
        unresolvedContracts, err := c.log.FetchUnresolvedContracts()
4✔
664
        if err != nil {
4✔
665
                return err
×
666
        }
×
667

668
        // Retrieve the commitment tx hash from the log.
669
        contractResolutions, err := c.log.FetchContractResolutions()
4✔
670
        if err != nil {
4✔
671
                log.Errorf("unable to fetch contract resolutions: %v",
×
672
                        err)
×
673
                return err
×
674
        }
×
675
        commitHash := contractResolutions.CommitHash
4✔
676

4✔
677
        // In prior versions of lnd, the information needed to supplement the
4✔
678
        // resolvers (in most cases, the full amount of the HTLC) was found in
4✔
679
        // the chain action map, which is now deprecated.  As a result, if the
4✔
680
        // commitSet is nil (an older node with unresolved HTLCs at time of
4✔
681
        // upgrade), then we'll use the chain action information in place. The
4✔
682
        // chain actions may exclude some information, but we cannot recover it
4✔
683
        // for these older nodes at the moment.
4✔
684
        var confirmedHTLCs []channeldb.HTLC
4✔
685
        if commitSet != nil {
8✔
686
                confirmedHTLCs = commitSet.HtlcSets[*commitSet.ConfCommitKey]
4✔
687
        } else {
4✔
688
                chainActions, err := c.log.FetchChainActions()
×
689
                if err != nil {
×
690
                        log.Errorf("unable to fetch chain actions: %v", err)
×
691
                        return err
×
692
                }
×
693
                for _, htlcs := range chainActions {
×
694
                        confirmedHTLCs = append(confirmedHTLCs, htlcs...)
×
695
                }
×
696
        }
697

698
        // Reconstruct the htlc outpoints and data from the chain action log.
699
        // The purpose of the constructed htlc map is to supplement to
700
        // resolvers restored from database with extra data. Ideally this data
701
        // is stored as part of the resolver in the log. This is a workaround
702
        // to prevent a db migration. We use all available htlc sets here in
703
        // order to ensure we have complete coverage.
704
        htlcMap := make(map[wire.OutPoint]*channeldb.HTLC)
4✔
705
        for _, htlc := range confirmedHTLCs {
10✔
706
                htlc := htlc
6✔
707
                outpoint := wire.OutPoint{
6✔
708
                        Hash:  commitHash,
6✔
709
                        Index: uint32(htlc.OutputIndex),
6✔
710
                }
6✔
711
                htlcMap[outpoint] = &htlc
6✔
712
        }
6✔
713

714
        // We'll also fetch the historical state of this channel, as it should
715
        // have been marked as closed by now, and supplement it to each resolver
716
        // such that we can properly resolve our pending contracts.
717
        var chanState *channeldb.OpenChannel
4✔
718
        chanState, err = c.cfg.FetchHistoricalChannel()
4✔
719
        switch {
4✔
720
        // If we don't find this channel, then it may be the case that it
721
        // was closed before we started to retain the final state
722
        // information for open channels.
723
        case err == channeldb.ErrNoHistoricalBucket:
×
724
                fallthrough
×
725
        case err == channeldb.ErrChannelNotFound:
×
726
                log.Warnf("ChannelArbitrator(%v): unable to fetch historical "+
×
727
                        "state", c.cfg.ChanPoint)
×
728

729
        case err != nil:
×
730
                return err
×
731
        }
732

733
        log.Infof("ChannelArbitrator(%v): relaunching %v contract "+
4✔
734
                "resolvers", c.cfg.ChanPoint, len(unresolvedContracts))
4✔
735

4✔
736
        for i := range unresolvedContracts {
8✔
737
                resolver := unresolvedContracts[i]
4✔
738

4✔
739
                if chanState != nil {
8✔
740
                        resolver.SupplementState(chanState)
4✔
741

4✔
742
                        // For taproot channels, we'll need to also make sure
4✔
743
                        // the control block information was set properly.
4✔
744
                        maybeAugmentTaprootResolvers(
4✔
745
                                chanState.ChanType, resolver,
4✔
746
                                contractResolutions,
4✔
747
                        )
4✔
748
                }
4✔
749

750
                unresolvedContracts[i] = resolver
4✔
751

4✔
752
                htlcResolver, ok := resolver.(htlcContractResolver)
4✔
753
                if !ok {
7✔
754
                        continue
3✔
755
                }
756

757
                htlcPoint := htlcResolver.HtlcPoint()
4✔
758
                htlc, ok := htlcMap[htlcPoint]
4✔
759
                if !ok {
4✔
760
                        return fmt.Errorf(
×
761
                                "htlc resolver %T unavailable", resolver,
×
762
                        )
×
763
                }
×
764

765
                htlcResolver.Supplement(*htlc)
4✔
766

4✔
767
                // If this is an outgoing HTLC, we will also need to supplement
4✔
768
                // the resolver with the expiry block height of its
4✔
769
                // corresponding incoming HTLC.
4✔
770
                if !htlc.Incoming {
8✔
771
                        deadline := c.cfg.FindOutgoingHTLCDeadline(*htlc)
4✔
772
                        htlcResolver.SupplementDeadline(deadline)
4✔
773
                }
4✔
774
        }
775

776
        // The anchor resolver is stateless and can always be re-instantiated.
777
        if contractResolutions.AnchorResolution != nil {
7✔
778
                anchorResolver := newAnchorResolver(
3✔
779
                        contractResolutions.AnchorResolution.AnchorSignDescriptor,
3✔
780
                        contractResolutions.AnchorResolution.CommitAnchor,
3✔
781
                        heightHint, c.cfg.ChanPoint,
3✔
782
                        ResolverConfig{
3✔
783
                                ChannelArbitratorConfig: c.cfg,
3✔
784
                        },
3✔
785
                )
3✔
786

3✔
787
                anchorResolver.SupplementState(chanState)
3✔
788

3✔
789
                unresolvedContracts = append(unresolvedContracts, anchorResolver)
3✔
790

3✔
791
                // TODO(roasbeef): this isn't re-launched?
3✔
792
        }
3✔
793

794
        c.launchResolvers(unresolvedContracts, true)
4✔
795

4✔
796
        return nil
4✔
797
}
798

799
// Report returns htlc reports for the active resolvers.
800
func (c *ChannelArbitrator) Report() []*ContractReport {
3✔
801
        c.activeResolversLock.RLock()
3✔
802
        defer c.activeResolversLock.RUnlock()
3✔
803

3✔
804
        var reports []*ContractReport
3✔
805
        for _, resolver := range c.activeResolvers {
6✔
806
                r, ok := resolver.(reportingContractResolver)
3✔
807
                if !ok {
3✔
808
                        continue
×
809
                }
810

811
                report := r.report()
3✔
812
                if report == nil {
6✔
813
                        continue
3✔
814
                }
815

816
                reports = append(reports, report)
3✔
817
        }
818

819
        return reports
3✔
820
}
821

822
// Stop signals the ChannelArbitrator for a graceful shutdown.
823
func (c *ChannelArbitrator) Stop() error {
53✔
824
        if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
59✔
825
                return nil
6✔
826
        }
6✔
827

828
        log.Debugf("Stopping ChannelArbitrator(%v)", c.cfg.ChanPoint)
47✔
829

47✔
830
        if c.cfg.ChainEvents.Cancel != nil {
61✔
831
                go c.cfg.ChainEvents.Cancel()
14✔
832
        }
14✔
833

834
        c.activeResolversLock.RLock()
47✔
835
        for _, activeResolver := range c.activeResolvers {
56✔
836
                activeResolver.Stop()
9✔
837
        }
9✔
838
        c.activeResolversLock.RUnlock()
47✔
839

47✔
840
        close(c.quit)
47✔
841
        c.wg.Wait()
47✔
842

47✔
843
        return nil
47✔
844
}
845

846
// transitionTrigger is an enum that denotes exactly *why* a state transition
847
// was initiated. This is useful as depending on the initial trigger, we may
848
// skip certain states as those actions are expected to have already taken
849
// place as a result of the external trigger.
850
type transitionTrigger uint8
851

852
const (
853
        // chainTrigger is a transition trigger that has been attempted due to
854
        // changing on-chain conditions such as a block which times out HTLC's
855
        // being attached.
856
        chainTrigger transitionTrigger = iota
857

858
        // userTrigger is a transition trigger driven by user action. Examples
859
        // of such a trigger include a user requesting a force closure of the
860
        // channel.
861
        userTrigger
862

863
        // remoteCloseTrigger is a transition trigger driven by the remote
864
        // peer's commitment being confirmed.
865
        remoteCloseTrigger
866

867
        // localCloseTrigger is a transition trigger driven by our commitment
868
        // being confirmed.
869
        localCloseTrigger
870

871
        // coopCloseTrigger is a transition trigger driven by a cooperative
872
        // close transaction being confirmed.
873
        coopCloseTrigger
874

875
        // breachCloseTrigger is a transition trigger driven by a remote breach
876
        // being confirmed. In this case the channel arbitrator will wait for
877
        // the BreachArbitrator to finish and then clean up gracefully.
878
        breachCloseTrigger
879
)
880

881
// String returns a human readable string describing the passed
882
// transitionTrigger.
883
func (t transitionTrigger) String() string {
3✔
884
        switch t {
3✔
885
        case chainTrigger:
3✔
886
                return "chainTrigger"
3✔
887

888
        case remoteCloseTrigger:
3✔
889
                return "remoteCloseTrigger"
3✔
890

891
        case userTrigger:
3✔
892
                return "userTrigger"
3✔
893

894
        case localCloseTrigger:
3✔
895
                return "localCloseTrigger"
3✔
896

897
        case coopCloseTrigger:
3✔
898
                return "coopCloseTrigger"
3✔
899

900
        case breachCloseTrigger:
3✔
901
                return "breachCloseTrigger"
3✔
902

903
        default:
×
904
                return "unknown trigger"
×
905
        }
906
}
907

908
// stateStep is a help method that examines our internal state, and attempts
909
// the appropriate state transition if necessary. The next state we transition
910
// to is returned, Additionally, if the next transition results in a commitment
911
// broadcast, the commitment transaction itself is returned.
912
func (c *ChannelArbitrator) stateStep(
913
        triggerHeight uint32, trigger transitionTrigger,
914
        confCommitSet *CommitSet) (ArbitratorState, *wire.MsgTx, error) {
178✔
915

178✔
916
        var (
178✔
917
                nextState ArbitratorState
178✔
918
                closeTx   *wire.MsgTx
178✔
919
        )
178✔
920
        switch c.state {
178✔
921

922
        // If we're in the default state, then we'll check our set of actions
923
        // to see if while we were down, conditions have changed.
924
        case StateDefault:
67✔
925
                log.Debugf("ChannelArbitrator(%v): new block (height=%v) "+
67✔
926
                        "examining active HTLC's", c.cfg.ChanPoint,
67✔
927
                        triggerHeight)
67✔
928

67✔
929
                // As a new block has been connected to the end of the main
67✔
930
                // chain, we'll check to see if we need to make any on-chain
67✔
931
                // claims on behalf of the channel contract that we're
67✔
932
                // arbitrating for. If a commitment has confirmed, then we'll
67✔
933
                // use the set snapshot from the chain, otherwise we'll use our
67✔
934
                // current set.
67✔
935
                var htlcs map[HtlcSetKey]htlcSet
67✔
936
                if confCommitSet != nil {
79✔
937
                        htlcs = confCommitSet.toActiveHTLCSets()
12✔
938
                } else {
70✔
939
                        // Update the set of activeHTLCs so
58✔
940
                        // checkLocalChainActions has an up-to-date view of the
58✔
941
                        // commitments.
58✔
942
                        c.updateActiveHTLCs()
58✔
943
                        htlcs = c.activeHTLCs
58✔
944
                }
58✔
945
                chainActions, err := c.checkLocalChainActions(
67✔
946
                        triggerHeight, trigger, htlcs, false,
67✔
947
                )
67✔
948
                if err != nil {
67✔
949
                        return StateDefault, nil, err
×
950
                }
×
951

952
                // If there are no actions to be made, then we'll remain in the
953
                // default state. If this isn't a self initiated event (we're
954
                // checking due to a chain update), then we'll exit now.
955
                if len(chainActions) == 0 && trigger == chainTrigger {
107✔
956
                        log.Debugf("ChannelArbitrator(%v): no actions for "+
40✔
957
                                "chain trigger, terminating", c.cfg.ChanPoint)
40✔
958

40✔
959
                        return StateDefault, closeTx, nil
40✔
960
                }
40✔
961

962
                // Otherwise, we'll log that we checked the HTLC actions as the
963
                // commitment transaction has already been broadcast.
964
                log.Tracef("ChannelArbitrator(%v): logging chain_actions=%v",
30✔
965
                        c.cfg.ChanPoint, lnutils.SpewLogClosure(chainActions))
30✔
966

30✔
967
                // Depending on the type of trigger, we'll either "tunnel"
30✔
968
                // through to a farther state, or just proceed linearly to the
30✔
969
                // next state.
30✔
970
                switch trigger {
30✔
971

972
                // If this is a chain trigger, then we'll go straight to the
973
                // next state, as we still need to broadcast the commitment
974
                // transaction.
975
                case chainTrigger:
8✔
976
                        fallthrough
8✔
977
                case userTrigger:
18✔
978
                        nextState = StateBroadcastCommit
18✔
979

980
                // If the trigger is a cooperative close being confirmed, then
981
                // we can go straight to StateFullyResolved, as there won't be
982
                // any contracts to resolve.
983
                case coopCloseTrigger:
6✔
984
                        nextState = StateFullyResolved
6✔
985

986
                // Otherwise, if this state advance was triggered by a
987
                // commitment being confirmed on chain, then we'll jump
988
                // straight to the state where the contract has already been
989
                // closed, and we will inspect the set of unresolved contracts.
990
                case localCloseTrigger:
5✔
991
                        log.Errorf("ChannelArbitrator(%v): unexpected local "+
5✔
992
                                "commitment confirmed while in StateDefault",
5✔
993
                                c.cfg.ChanPoint)
5✔
994
                        fallthrough
5✔
995
                case remoteCloseTrigger:
11✔
996
                        nextState = StateContractClosed
11✔
997

998
                case breachCloseTrigger:
4✔
999
                        nextContractState, err := c.checkLegacyBreach()
4✔
1000
                        if nextContractState == StateError {
4✔
1001
                                return nextContractState, nil, err
×
1002
                        }
×
1003

1004
                        nextState = nextContractState
4✔
1005
                }
1006

1007
        // If we're in this state, then we've decided to broadcast the
1008
        // commitment transaction. We enter this state either due to an outside
1009
        // sub-system, or because an on-chain action has been triggered.
1010
        case StateBroadcastCommit:
23✔
1011
                // Under normal operation, we can only enter
23✔
1012
                // StateBroadcastCommit via a user or chain trigger. On restart,
23✔
1013
                // this state may be reexecuted after closing the channel, but
23✔
1014
                // failing to commit to StateContractClosed or
23✔
1015
                // StateFullyResolved. In that case, one of the four close
23✔
1016
                // triggers will be presented, signifying that we should skip
23✔
1017
                // rebroadcasting, and go straight to resolving the on-chain
23✔
1018
                // contract or marking the channel resolved.
23✔
1019
                switch trigger {
23✔
1020
                case localCloseTrigger, remoteCloseTrigger:
×
1021
                        log.Infof("ChannelArbitrator(%v): detected %s "+
×
1022
                                "close after closing channel, fast-forwarding "+
×
1023
                                "to %s to resolve contract",
×
1024
                                c.cfg.ChanPoint, trigger, StateContractClosed)
×
1025
                        return StateContractClosed, closeTx, nil
×
1026

1027
                case breachCloseTrigger:
4✔
1028
                        nextContractState, err := c.checkLegacyBreach()
4✔
1029
                        if nextContractState == StateError {
4✔
1030
                                log.Infof("ChannelArbitrator(%v): unable to "+
×
1031
                                        "advance breach close resolution: %v",
×
1032
                                        c.cfg.ChanPoint, nextContractState)
×
1033
                                return StateError, closeTx, err
×
1034
                        }
×
1035

1036
                        log.Infof("ChannelArbitrator(%v): detected %s close "+
4✔
1037
                                "after closing channel, fast-forwarding to %s"+
4✔
1038
                                " to resolve contract", c.cfg.ChanPoint,
4✔
1039
                                trigger, nextContractState)
4✔
1040

4✔
1041
                        return nextContractState, closeTx, nil
4✔
1042

1043
                case coopCloseTrigger:
×
1044
                        log.Infof("ChannelArbitrator(%v): detected %s "+
×
1045
                                "close after closing channel, fast-forwarding "+
×
1046
                                "to %s to resolve contract",
×
1047
                                c.cfg.ChanPoint, trigger, StateFullyResolved)
×
1048
                        return StateFullyResolved, closeTx, nil
×
1049
                }
1050

1051
                log.Infof("ChannelArbitrator(%v): force closing "+
22✔
1052
                        "chan", c.cfg.ChanPoint)
22✔
1053

22✔
1054
                // Now that we have all the actions decided for the set of
22✔
1055
                // HTLC's, we'll broadcast the commitment transaction, and
22✔
1056
                // signal the link to exit.
22✔
1057

22✔
1058
                // We'll tell the switch that it should remove the link for
22✔
1059
                // this channel, in addition to fetching the force close
22✔
1060
                // summary needed to close this channel on chain.
22✔
1061
                closeSummary, err := c.cfg.Channel.ForceCloseChan()
22✔
1062
                if err != nil {
23✔
1063
                        log.Errorf("ChannelArbitrator(%v): unable to "+
1✔
1064
                                "force close: %v", c.cfg.ChanPoint, err)
1✔
1065

1✔
1066
                        // We tried to force close (HTLC may be expiring from
1✔
1067
                        // our PoV, etc), but we think we've lost data. In this
1✔
1068
                        // case, we'll not force close, but terminate the state
1✔
1069
                        // machine here to wait to see what confirms on chain.
1✔
1070
                        if errors.Is(err, lnwallet.ErrForceCloseLocalDataLoss) {
2✔
1071
                                log.Error("ChannelArbitrator(%v): broadcast "+
1✔
1072
                                        "failed due to local data loss, "+
1✔
1073
                                        "waiting for on chain confimation...",
1✔
1074
                                        c.cfg.ChanPoint)
1✔
1075

1✔
1076
                                return StateBroadcastCommit, nil, nil
1✔
1077
                        }
1✔
1078

1079
                        return StateError, closeTx, err
×
1080
                }
1081
                closeTx = closeSummary.CloseTx
21✔
1082

21✔
1083
                // Before publishing the transaction, we store it to the
21✔
1084
                // database, such that we can re-publish later in case it
21✔
1085
                // didn't propagate. We initiated the force close, so we
21✔
1086
                // mark broadcast with local initiator set to true.
21✔
1087
                err = c.cfg.MarkCommitmentBroadcasted(closeTx, lntypes.Local)
21✔
1088
                if err != nil {
21✔
1089
                        log.Errorf("ChannelArbitrator(%v): unable to "+
×
1090
                                "mark commitment broadcasted: %v",
×
1091
                                c.cfg.ChanPoint, err)
×
1092
                        return StateError, closeTx, err
×
1093
                }
×
1094

1095
                // With the close transaction in hand, broadcast the
1096
                // transaction to the network, thereby entering the post
1097
                // channel resolution state.
1098
                log.Infof("Broadcasting force close transaction %v, "+
21✔
1099
                        "ChannelPoint(%v): %v", closeTx.TxHash(),
21✔
1100
                        c.cfg.ChanPoint, lnutils.SpewLogClosure(closeTx))
21✔
1101

21✔
1102
                // At this point, we'll now broadcast the commitment
21✔
1103
                // transaction itself.
21✔
1104
                label := labels.MakeLabel(
21✔
1105
                        labels.LabelTypeChannelClose, &c.cfg.ShortChanID,
21✔
1106
                )
21✔
1107
                if err := c.cfg.PublishTx(closeTx, label); err != nil {
29✔
1108
                        log.Errorf("ChannelArbitrator(%v): unable to broadcast "+
8✔
1109
                                "close tx: %v", c.cfg.ChanPoint, err)
8✔
1110

8✔
1111
                        // This makes sure we don't fail at startup if the
8✔
1112
                        // commitment transaction has too low fees to make it
8✔
1113
                        // into mempool. The rebroadcaster makes sure this
8✔
1114
                        // transaction is republished regularly until confirmed
8✔
1115
                        // or replaced.
8✔
1116
                        if !errors.Is(err, lnwallet.ErrDoubleSpend) &&
8✔
1117
                                !errors.Is(err, lnwallet.ErrMempoolFee) {
13✔
1118

5✔
1119
                                return StateError, closeTx, err
5✔
1120
                        }
5✔
1121
                }
1122

1123
                // We go to the StateCommitmentBroadcasted state, where we'll
1124
                // be waiting for the commitment to be confirmed.
1125
                nextState = StateCommitmentBroadcasted
19✔
1126

1127
        // In this state we have broadcasted our own commitment, and will need
1128
        // to wait for a commitment (not necessarily the one we broadcasted!)
1129
        // to be confirmed.
1130
        case StateCommitmentBroadcasted:
33✔
1131
                switch trigger {
33✔
1132

1133
                // We are waiting for a commitment to be confirmed.
1134
                case chainTrigger, userTrigger:
20✔
1135
                        // The commitment transaction has been broadcast, but it
20✔
1136
                        // doesn't necessarily need to be the commitment
20✔
1137
                        // transaction version that is going to be confirmed. To
20✔
1138
                        // be sure that any of those versions can be anchored
20✔
1139
                        // down, we now submit all anchor resolutions to the
20✔
1140
                        // sweeper. The sweeper will keep trying to sweep all of
20✔
1141
                        // them.
20✔
1142
                        //
20✔
1143
                        // Note that the sweeper is idempotent. If we ever
20✔
1144
                        // happen to end up at this point in the code again, no
20✔
1145
                        // harm is done by re-offering the anchors to the
20✔
1146
                        // sweeper.
20✔
1147
                        anchors, err := c.cfg.Channel.NewAnchorResolutions()
20✔
1148
                        if err != nil {
20✔
1149
                                return StateError, closeTx, err
×
1150
                        }
×
1151

1152
                        err = c.sweepAnchors(anchors, triggerHeight)
20✔
1153
                        if err != nil {
20✔
1154
                                return StateError, closeTx, err
×
1155
                        }
×
1156

1157
                        nextState = StateCommitmentBroadcasted
20✔
1158

1159
                // If this state advance was triggered by any of the
1160
                // commitments being confirmed, then we'll jump to the state
1161
                // where the contract has been closed.
1162
                case localCloseTrigger, remoteCloseTrigger:
16✔
1163
                        nextState = StateContractClosed
16✔
1164

1165
                // If a coop close was confirmed, jump straight to the fully
1166
                // resolved state.
1167
                case coopCloseTrigger:
×
1168
                        nextState = StateFullyResolved
×
1169

UNCOV
1170
                case breachCloseTrigger:
×
UNCOV
1171
                        nextContractState, err := c.checkLegacyBreach()
×
UNCOV
1172
                        if nextContractState == StateError {
×
1173
                                return nextContractState, closeTx, err
×
1174
                        }
×
1175

UNCOV
1176
                        nextState = nextContractState
×
1177
                }
1178

1179
                log.Infof("ChannelArbitrator(%v): trigger %v moving from "+
33✔
1180
                        "state %v to %v", c.cfg.ChanPoint, trigger, c.state,
33✔
1181
                        nextState)
33✔
1182

1183
        // If we're in this state, then the contract has been fully closed to
1184
        // outside sub-systems, so we'll process the prior set of on-chain
1185
        // contract actions and launch a set of resolvers.
1186
        case StateContractClosed:
25✔
1187
                // First, we'll fetch our chain actions, and both sets of
25✔
1188
                // resolutions so we can process them.
25✔
1189
                contractResolutions, err := c.log.FetchContractResolutions()
25✔
1190
                if err != nil {
27✔
1191
                        log.Errorf("unable to fetch contract resolutions: %v",
2✔
1192
                                err)
2✔
1193
                        return StateError, closeTx, err
2✔
1194
                }
2✔
1195

1196
                // If the resolution is empty, and we have no HTLCs at all to
1197
                // send to, then we're done here. We don't need to launch any
1198
                // resolvers, and can go straight to our final state.
1199
                if contractResolutions.IsEmpty() && confCommitSet.IsEmpty() {
34✔
1200
                        log.Infof("ChannelArbitrator(%v): contract "+
11✔
1201
                                "resolutions empty, marking channel as fully resolved!",
11✔
1202
                                c.cfg.ChanPoint)
11✔
1203
                        nextState = StateFullyResolved
11✔
1204
                        break
11✔
1205
                }
1206

1207
                // Now that we know we'll need to act, we'll process all the
1208
                // resolvers, then create the structures we need to resolve all
1209
                // outstanding contracts.
1210
                resolvers, pktsToSend, err := c.prepContractResolutions(
15✔
1211
                        contractResolutions, triggerHeight, trigger,
15✔
1212
                        confCommitSet,
15✔
1213
                )
15✔
1214
                if err != nil {
15✔
1215
                        log.Errorf("ChannelArbitrator(%v): unable to "+
×
1216
                                "resolve contracts: %v", c.cfg.ChanPoint, err)
×
1217
                        return StateError, closeTx, err
×
1218
                }
×
1219

1220
                // With the commitment broadcast, we'll then send over all
1221
                // messages we can send immediately.
1222
                if len(pktsToSend) != 0 {
28✔
1223
                        log.Debugf("ChannelArbitrator(%v): sending "+
13✔
1224
                                "resolution message=%v", c.cfg.ChanPoint,
13✔
1225
                                lnutils.SpewLogClosure(pktsToSend))
13✔
1226

13✔
1227
                        err := c.cfg.DeliverResolutionMsg(pktsToSend...)
13✔
1228
                        if err != nil {
13✔
1229
                                log.Errorf("unable to send pkts: %v", err)
×
1230
                                return StateError, closeTx, err
×
1231
                        }
×
1232
                }
1233

1234
                log.Debugf("ChannelArbitrator(%v): inserting %v contract "+
15✔
1235
                        "resolvers", c.cfg.ChanPoint, len(resolvers))
15✔
1236

15✔
1237
                err = c.log.InsertUnresolvedContracts(nil, resolvers...)
15✔
1238
                if err != nil {
15✔
1239
                        return StateError, closeTx, err
×
1240
                }
×
1241

1242
                // Finally, we'll launch all the required contract resolvers.
1243
                // Once they're all resolved, we're no longer needed.
1244
                c.launchResolvers(resolvers, false)
15✔
1245

15✔
1246
                nextState = StateWaitingFullResolution
15✔
1247

1248
        // This is our terminal state. We'll keep returning this state until
1249
        // all contracts are fully resolved.
1250
        case StateWaitingFullResolution:
20✔
1251
                log.Infof("ChannelArbitrator(%v): still awaiting contract "+
20✔
1252
                        "resolution", c.cfg.ChanPoint)
20✔
1253

20✔
1254
                unresolved, err := c.log.FetchUnresolvedContracts()
20✔
1255
                if err != nil {
20✔
1256
                        return StateError, closeTx, err
×
1257
                }
×
1258

1259
                // If we have no unresolved contracts, then we can move to the
1260
                // final state.
1261
                if len(unresolved) == 0 {
35✔
1262
                        nextState = StateFullyResolved
15✔
1263
                        break
15✔
1264
                }
1265

1266
                // Otherwise we still have unresolved contracts, then we'll
1267
                // stay alive to oversee their resolution.
1268
                nextState = StateWaitingFullResolution
8✔
1269

8✔
1270
                // Add debug logs.
8✔
1271
                for _, r := range unresolved {
16✔
1272
                        log.Debugf("ChannelArbitrator(%v): still have "+
8✔
1273
                                "unresolved contract: %T", c.cfg.ChanPoint, r)
8✔
1274
                }
8✔
1275

1276
        // If we start as fully resolved, then we'll end as fully resolved.
1277
        case StateFullyResolved:
25✔
1278
                // To ensure that the state of the contract in persistent
25✔
1279
                // storage is properly reflected, we'll mark the contract as
25✔
1280
                // fully resolved now.
25✔
1281
                nextState = StateFullyResolved
25✔
1282

25✔
1283
                log.Infof("ChannelPoint(%v) has been fully resolved "+
25✔
1284
                        "on-chain at height=%v", c.cfg.ChanPoint, triggerHeight)
25✔
1285

25✔
1286
                if err := c.cfg.MarkChannelResolved(); err != nil {
25✔
1287
                        log.Errorf("unable to mark channel resolved: %v", err)
×
1288
                        return StateError, closeTx, err
×
1289
                }
×
1290
        }
1291

1292
        log.Tracef("ChannelArbitrator(%v): next_state=%v", c.cfg.ChanPoint,
135✔
1293
                nextState)
135✔
1294

135✔
1295
        return nextState, closeTx, nil
135✔
1296
}
1297

1298
// sweepAnchors offers all given anchor resolutions to the sweeper. It requests
1299
// sweeping at the minimum fee rate. This fee rate can be upped manually by the
1300
// user via the BumpFee rpc.
1301
func (c *ChannelArbitrator) sweepAnchors(anchors *lnwallet.AnchorResolutions,
1302
        heightHint uint32) error {
21✔
1303

21✔
1304
        // Use the chan id as the exclusive group. This prevents any of the
21✔
1305
        // anchors from being batched together.
21✔
1306
        exclusiveGroup := c.cfg.ShortChanID.ToUint64()
21✔
1307

21✔
1308
        // sweepWithDeadline is a helper closure that takes an anchor
21✔
1309
        // resolution and sweeps it with its corresponding deadline.
21✔
1310
        sweepWithDeadline := func(anchor *lnwallet.AnchorResolution,
21✔
1311
                htlcs htlcSet, anchorPath string) error {
29✔
1312

8✔
1313
                // Find the deadline for this specific anchor.
8✔
1314
                deadline, value, err := c.findCommitmentDeadlineAndValue(
8✔
1315
                        heightHint, htlcs,
8✔
1316
                )
8✔
1317
                if err != nil {
8✔
1318
                        return err
×
1319
                }
×
1320

1321
                // If we cannot find a deadline, it means there's no HTLCs at
1322
                // stake, which means we can relax our anchor sweeping
1323
                // conditions as we don't have any time sensitive outputs to
1324
                // sweep. However we need to register the anchor output with the
1325
                // sweeper so we are later able to bump the close fee.
1326
                if deadline.IsNone() {
12✔
1327
                        log.Infof("ChannelArbitrator(%v): no HTLCs at stake, "+
4✔
1328
                                "sweeping anchor with default deadline",
4✔
1329
                                c.cfg.ChanPoint)
4✔
1330
                }
4✔
1331

1332
                witnessType := input.CommitmentAnchor
8✔
1333

8✔
1334
                // For taproot channels, we need to use the proper witness
8✔
1335
                // type.
8✔
1336
                if txscript.IsPayToTaproot(
8✔
1337
                        anchor.AnchorSignDescriptor.Output.PkScript,
8✔
1338
                ) {
11✔
1339

3✔
1340
                        witnessType = input.TaprootAnchorSweepSpend
3✔
1341
                }
3✔
1342

1343
                // Prepare anchor output for sweeping.
1344
                anchorInput := input.MakeBaseInput(
8✔
1345
                        &anchor.CommitAnchor,
8✔
1346
                        witnessType,
8✔
1347
                        &anchor.AnchorSignDescriptor,
8✔
1348
                        heightHint,
8✔
1349
                        &input.TxInfo{
8✔
1350
                                Fee:    anchor.CommitFee,
8✔
1351
                                Weight: anchor.CommitWeight,
8✔
1352
                        },
8✔
1353
                )
8✔
1354

8✔
1355
                // If we have a deadline, we'll use it to calculate the
8✔
1356
                // deadline height, otherwise default to none.
8✔
1357
                deadlineDesc := "None"
8✔
1358
                deadlineHeight := fn.MapOption(func(d int32) int32 {
15✔
1359
                        deadlineDesc = fmt.Sprintf("%d", d)
7✔
1360

7✔
1361
                        return d + int32(heightHint)
7✔
1362
                })(deadline)
7✔
1363

1364
                // Calculate the budget based on the value under protection,
1365
                // which is the sum of all HTLCs on this commitment subtracted
1366
                // by their budgets.
1367
                // The anchor output in itself has a small output value of 330
1368
                // sats so we also include it in the budget to pay for the
1369
                // cpfp transaction.
1370
                budget := calculateBudget(
8✔
1371
                        value, c.cfg.Budget.AnchorCPFPRatio,
8✔
1372
                        c.cfg.Budget.AnchorCPFP,
8✔
1373
                ) + AnchorOutputValue
8✔
1374

8✔
1375
                log.Infof("ChannelArbitrator(%v): offering anchor from %s "+
8✔
1376
                        "commitment %v to sweeper with deadline=%v, budget=%v",
8✔
1377
                        c.cfg.ChanPoint, anchorPath, anchor.CommitAnchor,
8✔
1378
                        deadlineDesc, budget)
8✔
1379

8✔
1380
                // Sweep anchor output with a confirmation target fee
8✔
1381
                // preference. Because this is a cpfp-operation, the anchor
8✔
1382
                // will only be attempted to sweep when the current fee
8✔
1383
                // estimate for the confirmation target exceeds the commit fee
8✔
1384
                // rate.
8✔
1385
                _, err = c.cfg.Sweeper.SweepInput(
8✔
1386
                        &anchorInput,
8✔
1387
                        sweep.Params{
8✔
1388
                                ExclusiveGroup: &exclusiveGroup,
8✔
1389
                                Budget:         budget,
8✔
1390
                                DeadlineHeight: deadlineHeight,
8✔
1391
                        },
8✔
1392
                )
8✔
1393
                if err != nil {
8✔
1394
                        return err
×
1395
                }
×
1396

1397
                return nil
8✔
1398
        }
1399

1400
        // Update the set of activeHTLCs so that the sweeping routine has an
1401
        // up-to-date view of the set of commitments.
1402
        c.updateActiveHTLCs()
21✔
1403

21✔
1404
        // Sweep anchors based on different HTLC sets. Notice the HTLC sets may
21✔
1405
        // differ across commitments, thus their deadline values could vary.
21✔
1406
        for htlcSet, htlcs := range c.activeHTLCs {
65✔
1407
                switch {
44✔
1408
                case htlcSet == LocalHtlcSet && anchors.Local != nil:
5✔
1409
                        err := sweepWithDeadline(anchors.Local, htlcs, "local")
5✔
1410
                        if err != nil {
5✔
1411
                                return err
×
1412
                        }
×
1413

1414
                case htlcSet == RemoteHtlcSet && anchors.Remote != nil:
5✔
1415
                        err := sweepWithDeadline(
5✔
1416
                                anchors.Remote, htlcs, "remote",
5✔
1417
                        )
5✔
1418
                        if err != nil {
5✔
1419
                                return err
×
1420
                        }
×
1421

1422
                case htlcSet == RemotePendingHtlcSet &&
1423
                        anchors.RemotePending != nil:
1✔
1424

1✔
1425
                        err := sweepWithDeadline(
1✔
1426
                                anchors.RemotePending, htlcs, "remote pending",
1✔
1427
                        )
1✔
1428
                        if err != nil {
1✔
1429
                                return err
×
1430
                        }
×
1431
                }
1432
        }
1433

1434
        return nil
21✔
1435
}
1436

1437
// findCommitmentDeadlineAndValue finds the deadline (relative block height)
1438
// for a commitment transaction by extracting the minimum CLTV from its HTLCs.
1439
// From our PoV, the deadline delta is defined to be the smaller of,
1440
//   - half of the least CLTV from outgoing HTLCs' corresponding incoming
1441
//     HTLCs,  or,
1442
//   - half of the least CLTV from incoming HTLCs if the preimage is available.
1443
//
1444
// We use half of the CTLV value to ensure that we have enough time to sweep
1445
// the second-level HTLCs.
1446
//
1447
// It also finds the total value that are time-sensitive, which is the sum of
1448
// all the outgoing HTLCs plus incoming HTLCs whose preimages are known. It
1449
// then returns the value left after subtracting the budget used for sweeping
1450
// the time-sensitive HTLCs.
1451
//
1452
// NOTE: when the deadline turns out to be 0 blocks, we will replace it with 1
1453
// block because our fee estimator doesn't allow a 0 conf target. This also
1454
// means we've left behind and should increase our fee to make the transaction
1455
// confirmed asap.
1456
func (c *ChannelArbitrator) findCommitmentDeadlineAndValue(heightHint uint32,
1457
        htlcs htlcSet) (fn.Option[int32], btcutil.Amount, error) {
13✔
1458

13✔
1459
        deadlineMinHeight := uint32(math.MaxUint32)
13✔
1460
        totalValue := btcutil.Amount(0)
13✔
1461

13✔
1462
        // First, iterate through the outgoingHTLCs to find the lowest CLTV
13✔
1463
        // value.
13✔
1464
        for _, htlc := range htlcs.outgoingHTLCs {
25✔
1465
                // Skip if the HTLC is dust.
12✔
1466
                if htlc.OutputIndex < 0 {
18✔
1467
                        log.Debugf("ChannelArbitrator(%v): skipped deadline "+
6✔
1468
                                "for dust htlc=%x",
6✔
1469
                                c.cfg.ChanPoint, htlc.RHash[:])
6✔
1470

6✔
1471
                        continue
6✔
1472
                }
1473

1474
                value := htlc.Amt.ToSatoshis()
9✔
1475

9✔
1476
                // Find the expiry height for this outgoing HTLC's incoming
9✔
1477
                // HTLC.
9✔
1478
                deadlineOpt := c.cfg.FindOutgoingHTLCDeadline(htlc)
9✔
1479

9✔
1480
                // The deadline is default to the current deadlineMinHeight,
9✔
1481
                // and it's overwritten when it's not none.
9✔
1482
                deadline := deadlineMinHeight
9✔
1483
                deadlineOpt.WhenSome(func(d int32) {
16✔
1484
                        deadline = uint32(d)
7✔
1485

7✔
1486
                        // We only consider the value is under protection when
7✔
1487
                        // it's time-sensitive.
7✔
1488
                        totalValue += value
7✔
1489
                })
7✔
1490

1491
                if deadline < deadlineMinHeight {
16✔
1492
                        deadlineMinHeight = deadline
7✔
1493

7✔
1494
                        log.Tracef("ChannelArbitrator(%v): outgoing HTLC has "+
7✔
1495
                                "deadline=%v, value=%v", c.cfg.ChanPoint,
7✔
1496
                                deadlineMinHeight, value)
7✔
1497
                }
7✔
1498
        }
1499

1500
        // Then going through the incomingHTLCs, and update the minHeight when
1501
        // conditions met.
1502
        for _, htlc := range htlcs.incomingHTLCs {
25✔
1503
                // Skip if the HTLC is dust.
12✔
1504
                if htlc.OutputIndex < 0 {
13✔
1505
                        log.Debugf("ChannelArbitrator(%v): skipped deadline "+
1✔
1506
                                "for dust htlc=%x",
1✔
1507
                                c.cfg.ChanPoint, htlc.RHash[:])
1✔
1508

1✔
1509
                        continue
1✔
1510
                }
1511

1512
                // Since it's an HTLC sent to us, check if we have preimage for
1513
                // this HTLC.
1514
                preimageAvailable, err := c.isPreimageAvailable(htlc.RHash)
11✔
1515
                if err != nil {
11✔
1516
                        return fn.None[int32](), 0, err
×
1517
                }
×
1518

1519
                if !preimageAvailable {
16✔
1520
                        continue
5✔
1521
                }
1522

1523
                value := htlc.Amt.ToSatoshis()
9✔
1524
                totalValue += value
9✔
1525

9✔
1526
                if htlc.RefundTimeout < deadlineMinHeight {
17✔
1527
                        deadlineMinHeight = htlc.RefundTimeout
8✔
1528

8✔
1529
                        log.Tracef("ChannelArbitrator(%v): incoming HTLC has "+
8✔
1530
                                "deadline=%v, amt=%v", c.cfg.ChanPoint,
8✔
1531
                                deadlineMinHeight, value)
8✔
1532
                }
8✔
1533
        }
1534

1535
        // Calculate the deadline. There are two cases to be handled here,
1536
        //   - when the deadlineMinHeight never gets updated, which could
1537
        //     happen when we have no outgoing HTLCs, and, for incoming HTLCs,
1538
        //       * either we have none, or,
1539
        //       * none of the HTLCs are preimageAvailable.
1540
        //   - when our deadlineMinHeight is no greater than the heightHint,
1541
        //     which means we are behind our schedule.
1542
        var deadline uint32
13✔
1543
        switch {
13✔
1544
        // When we couldn't find a deadline height from our HTLCs, we will fall
1545
        // back to the default value as there's no time pressure here.
1546
        case deadlineMinHeight == math.MaxUint32:
5✔
1547
                return fn.None[int32](), 0, nil
5✔
1548

1549
        // When the deadline is passed, we will fall back to the smallest conf
1550
        // target (1 block).
1551
        case deadlineMinHeight <= heightHint:
1✔
1552
                log.Warnf("ChannelArbitrator(%v): deadline is passed with "+
1✔
1553
                        "deadlineMinHeight=%d, heightHint=%d",
1✔
1554
                        c.cfg.ChanPoint, deadlineMinHeight, heightHint)
1✔
1555
                deadline = 1
1✔
1556

1557
        // Use half of the deadline delta, and leave the other half to be used
1558
        // to sweep the HTLCs.
1559
        default:
10✔
1560
                deadline = (deadlineMinHeight - heightHint) / 2
10✔
1561
        }
1562

1563
        // Calculate the value left after subtracting the budget used for
1564
        // sweeping the time-sensitive HTLCs.
1565
        valueLeft := totalValue - calculateBudget(
11✔
1566
                totalValue, c.cfg.Budget.DeadlineHTLCRatio,
11✔
1567
                c.cfg.Budget.DeadlineHTLC,
11✔
1568
        )
11✔
1569

11✔
1570
        log.Debugf("ChannelArbitrator(%v): calculated valueLeft=%v, "+
11✔
1571
                "deadline=%d, using deadlineMinHeight=%d, heightHint=%d",
11✔
1572
                c.cfg.ChanPoint, valueLeft, deadline, deadlineMinHeight,
11✔
1573
                heightHint)
11✔
1574

11✔
1575
        return fn.Some(int32(deadline)), valueLeft, nil
11✔
1576
}
1577

1578
// launchResolvers updates the activeResolvers list and starts the resolvers.
1579
func (c *ChannelArbitrator) launchResolvers(resolvers []ContractResolver,
1580
        immediate bool) {
16✔
1581

16✔
1582
        c.activeResolversLock.Lock()
16✔
1583
        defer c.activeResolversLock.Unlock()
16✔
1584

16✔
1585
        c.activeResolvers = resolvers
16✔
1586
        for _, contract := range resolvers {
25✔
1587
                c.wg.Add(1)
9✔
1588
                go c.resolveContract(contract, immediate)
9✔
1589
        }
9✔
1590
}
1591

1592
// advanceState is the main driver of our state machine. This method is an
1593
// iterative function which repeatedly attempts to advance the internal state
1594
// of the channel arbitrator. The state will be advanced until we reach a
1595
// redundant transition, meaning that the state transition is a noop. The final
1596
// param is a callback that allows the caller to execute an arbitrary action
1597
// after each state transition.
1598
func (c *ChannelArbitrator) advanceState(
1599
        triggerHeight uint32, trigger transitionTrigger,
1600
        confCommitSet *CommitSet) (ArbitratorState, *wire.MsgTx, error) {
92✔
1601

92✔
1602
        var (
92✔
1603
                priorState   ArbitratorState
92✔
1604
                forceCloseTx *wire.MsgTx
92✔
1605
        )
92✔
1606

92✔
1607
        // We'll continue to advance our state forward until the state we
92✔
1608
        // transition to is that same state that we started at.
92✔
1609
        for {
270✔
1610
                priorState = c.state
178✔
1611
                log.Debugf("ChannelArbitrator(%v): attempting state step with "+
178✔
1612
                        "trigger=%v from state=%v", c.cfg.ChanPoint, trigger,
178✔
1613
                        priorState)
178✔
1614

178✔
1615
                nextState, closeTx, err := c.stateStep(
178✔
1616
                        triggerHeight, trigger, confCommitSet,
178✔
1617
                )
178✔
1618
                if err != nil {
185✔
1619
                        log.Errorf("ChannelArbitrator(%v): unable to advance "+
7✔
1620
                                "state: %v", c.cfg.ChanPoint, err)
7✔
1621
                        return priorState, nil, err
7✔
1622
                }
7✔
1623

1624
                if forceCloseTx == nil && closeTx != nil {
193✔
1625
                        forceCloseTx = closeTx
19✔
1626
                }
19✔
1627

1628
                // Our termination transition is a noop transition. If we get
1629
                // our prior state back as the next state, then we'll
1630
                // terminate.
1631
                if nextState == priorState {
259✔
1632
                        log.Debugf("ChannelArbitrator(%v): terminating at "+
85✔
1633
                                "state=%v", c.cfg.ChanPoint, nextState)
85✔
1634
                        return nextState, forceCloseTx, nil
85✔
1635
                }
85✔
1636

1637
                // As the prior state was successfully executed, we can now
1638
                // commit the next state. This ensures that we will re-execute
1639
                // the prior state if anything fails.
1640
                if err := c.log.CommitState(nextState); err != nil {
95✔
1641
                        log.Errorf("ChannelArbitrator(%v): unable to commit "+
3✔
1642
                                "next state(%v): %v", c.cfg.ChanPoint,
3✔
1643
                                nextState, err)
3✔
1644
                        return priorState, nil, err
3✔
1645
                }
3✔
1646
                c.state = nextState
89✔
1647
        }
1648
}
1649

1650
// ChainAction is an enum that encompasses all possible on-chain actions
1651
// we'll take for a set of HTLC's.
1652
type ChainAction uint8
1653

1654
const (
1655
        // NoAction is the min chainAction type, indicating that no action
1656
        // needs to be taken for a given HTLC.
1657
        NoAction ChainAction = 0
1658

1659
        // HtlcTimeoutAction indicates that the HTLC will timeout soon. As a
1660
        // result, we should get ready to sweep it on chain after the timeout.
1661
        HtlcTimeoutAction = 1
1662

1663
        // HtlcClaimAction indicates that we should claim the HTLC on chain
1664
        // before its timeout period.
1665
        HtlcClaimAction = 2
1666

1667
        // HtlcFailNowAction indicates that we should fail an outgoing HTLC
1668
        // immediately by cancelling it backwards as it has no corresponding
1669
        // output in our commitment transaction.
1670
        HtlcFailNowAction = 3
1671

1672
        // HtlcOutgoingWatchAction indicates that we can't yet timeout this
1673
        // HTLC, but we had to go to chain on order to resolve an existing
1674
        // HTLC.  In this case, we'll either: time it out once it expires, or
1675
        // will learn the pre-image if the remote party claims the output. In
1676
        // this case, well add the pre-image to our global store.
1677
        HtlcOutgoingWatchAction = 4
1678

1679
        // HtlcIncomingWatchAction indicates that we don't yet have the
1680
        // pre-image to claim incoming HTLC, but we had to go to chain in order
1681
        // to resolve and existing HTLC. In this case, we'll either: let the
1682
        // other party time it out, or eventually learn of the pre-image, in
1683
        // which case we'll claim on chain.
1684
        HtlcIncomingWatchAction = 5
1685

1686
        // HtlcIncomingDustFinalAction indicates that we should mark an incoming
1687
        // dust htlc as final because it can't be claimed on-chain.
1688
        HtlcIncomingDustFinalAction = 6
1689
)
1690

1691
// String returns a human readable string describing a chain action.
1692
func (c ChainAction) String() string {
×
1693
        switch c {
×
1694
        case NoAction:
×
1695
                return "NoAction"
×
1696

1697
        case HtlcTimeoutAction:
×
1698
                return "HtlcTimeoutAction"
×
1699

1700
        case HtlcClaimAction:
×
1701
                return "HtlcClaimAction"
×
1702

1703
        case HtlcFailNowAction:
×
1704
                return "HtlcFailNowAction"
×
1705

1706
        case HtlcOutgoingWatchAction:
×
1707
                return "HtlcOutgoingWatchAction"
×
1708

1709
        case HtlcIncomingWatchAction:
×
1710
                return "HtlcIncomingWatchAction"
×
1711

1712
        case HtlcIncomingDustFinalAction:
×
1713
                return "HtlcIncomingDustFinalAction"
×
1714

1715
        default:
×
1716
                return "<unknown action>"
×
1717
        }
1718
}
1719

1720
// ChainActionMap is a map of a chain action, to the set of HTLC's that need to
1721
// be acted upon for a given action type. The channel
1722
type ChainActionMap map[ChainAction][]channeldb.HTLC
1723

1724
// Merge merges the passed chain actions with the target chain action map.
1725
func (c ChainActionMap) Merge(actions ChainActionMap) {
79✔
1726
        for chainAction, htlcs := range actions {
95✔
1727
                c[chainAction] = append(c[chainAction], htlcs...)
16✔
1728
        }
16✔
1729
}
1730

1731
// shouldGoOnChain takes into account the absolute timeout of the HTLC, if the
1732
// confirmation delta that we need is close, and returns a bool indicating if
1733
// we should go on chain to claim.  We do this rather than waiting up until the
1734
// last minute as we want to ensure that when we *need* (HTLC is timed out) to
1735
// sweep, the commitment is already confirmed.
1736
func (c *ChannelArbitrator) shouldGoOnChain(htlc channeldb.HTLC,
1737
        broadcastDelta, currentHeight uint32) bool {
30✔
1738

30✔
1739
        // We'll calculate the broadcast cut off for this HTLC. This is the
30✔
1740
        // height that (based on our current fee estimation) we should
30✔
1741
        // broadcast in order to ensure the commitment transaction is confirmed
30✔
1742
        // before the HTLC fully expires.
30✔
1743
        broadcastCutOff := htlc.RefundTimeout - broadcastDelta
30✔
1744

30✔
1745
        log.Tracef("ChannelArbitrator(%v): examining outgoing contract: "+
30✔
1746
                "expiry=%v, cutoff=%v, height=%v", c.cfg.ChanPoint, htlc.RefundTimeout,
30✔
1747
                broadcastCutOff, currentHeight)
30✔
1748

30✔
1749
        // TODO(roasbeef): take into account default HTLC delta, don't need to
30✔
1750
        // broadcast immediately
30✔
1751
        //  * can then batch with SINGLE | ANYONECANPAY
30✔
1752

30✔
1753
        // We should on-chain for this HTLC, iff we're within out broadcast
30✔
1754
        // cutoff window.
30✔
1755
        if currentHeight < broadcastCutOff {
53✔
1756
                return false
23✔
1757
        }
23✔
1758

1759
        // In case of incoming htlc we should go to chain.
1760
        if htlc.Incoming {
13✔
1761
                return true
3✔
1762
        }
3✔
1763

1764
        // For htlcs that are result of our initiated payments we give some grace
1765
        // period before force closing the channel. During this time we expect
1766
        // both nodes to connect and give a chance to the other node to send its
1767
        // updates and cancel the htlc.
1768
        // This shouldn't add any security risk as there is no incoming htlc to
1769
        // fulfill at this case and the expectation is that when the channel is
1770
        // active the other node will send update_fail_htlc to remove the htlc
1771
        // without closing the channel. It is up to the user to force close the
1772
        // channel if the peer misbehaves and doesn't send the update_fail_htlc.
1773
        // It is useful when this node is most of the time not online and is
1774
        // likely to miss the time slot where the htlc may be cancelled.
1775
        isForwarded := c.cfg.IsForwardedHTLC(c.cfg.ShortChanID, htlc.HtlcIndex)
10✔
1776
        upTime := c.cfg.Clock.Now().Sub(c.startTimestamp)
10✔
1777
        return isForwarded || upTime > c.cfg.PaymentsExpirationGracePeriod
10✔
1778
}
1779

1780
// checkCommitChainActions is called for each new block connected to the end of
1781
// the main chain. Given the new block height, this new method will examine all
1782
// active HTLC's, and determine if we need to go on-chain to claim any of them.
1783
// A map of action -> []htlc is returned, detailing what action (if any) should
1784
// be performed for each HTLC. For timed out HTLC's, once the commitment has
1785
// been sufficiently confirmed, the HTLC's should be canceled backwards. For
1786
// redeemed HTLC's, we should send the pre-image back to the incoming link.
1787
func (c *ChannelArbitrator) checkCommitChainActions(height uint32,
1788
        trigger transitionTrigger, htlcs htlcSet) (ChainActionMap, error) {
79✔
1789

79✔
1790
        // TODO(roasbeef): would need to lock channel? channel totem?
79✔
1791
        //  * race condition if adding and we broadcast, etc
79✔
1792
        //  * or would make each instance sync?
79✔
1793

79✔
1794
        log.Debugf("ChannelArbitrator(%v): checking commit chain actions at "+
79✔
1795
                "height=%v, in_htlc_count=%v, out_htlc_count=%v",
79✔
1796
                c.cfg.ChanPoint, height,
79✔
1797
                len(htlcs.incomingHTLCs), len(htlcs.outgoingHTLCs))
79✔
1798

79✔
1799
        actionMap := make(ChainActionMap)
79✔
1800

79✔
1801
        // First, we'll make an initial pass over the set of incoming and
79✔
1802
        // outgoing HTLC's to decide if we need to go on chain at all.
79✔
1803
        haveChainActions := false
79✔
1804
        for _, htlc := range htlcs.outgoingHTLCs {
89✔
1805
                // We'll need to go on-chain for an outgoing HTLC if it was
10✔
1806
                // never resolved downstream, and it's "close" to timing out.
10✔
1807
                //
10✔
1808
                // TODO(yy): If there's no corresponding incoming HTLC, it
10✔
1809
                // means we are the first hop, hence the payer. This is a
10✔
1810
                // tricky case - unlike a forwarding hop, we don't have an
10✔
1811
                // incoming HTLC that will time out, which means as long as we
10✔
1812
                // can learn the preimage, we can settle the invoice (before it
10✔
1813
                // expires?).
10✔
1814
                toChain := c.shouldGoOnChain(
10✔
1815
                        htlc, c.cfg.OutgoingBroadcastDelta, height,
10✔
1816
                )
10✔
1817

10✔
1818
                if toChain {
13✔
1819
                        // Convert to int64 in case of overflow.
3✔
1820
                        remainingBlocks := int64(htlc.RefundTimeout) -
3✔
1821
                                int64(height)
3✔
1822

3✔
1823
                        log.Infof("ChannelArbitrator(%v): go to chain for "+
3✔
1824
                                "outgoing htlc %x: timeout=%v, amount=%v, "+
3✔
1825
                                "blocks_until_expiry=%v, broadcast_delta=%v",
3✔
1826
                                c.cfg.ChanPoint, htlc.RHash[:],
3✔
1827
                                htlc.RefundTimeout, htlc.Amt, remainingBlocks,
3✔
1828
                                c.cfg.OutgoingBroadcastDelta,
3✔
1829
                        )
3✔
1830
                }
3✔
1831

1832
                haveChainActions = haveChainActions || toChain
10✔
1833
        }
1834

1835
        for _, htlc := range htlcs.incomingHTLCs {
87✔
1836
                // We'll need to go on-chain to pull an incoming HTLC iff we
8✔
1837
                // know the pre-image and it's close to timing out. We need to
8✔
1838
                // ensure that we claim the funds that are rightfully ours
8✔
1839
                // on-chain.
8✔
1840
                preimageAvailable, err := c.isPreimageAvailable(htlc.RHash)
8✔
1841
                if err != nil {
8✔
1842
                        return nil, err
×
1843
                }
×
1844

1845
                if !preimageAvailable {
14✔
1846
                        continue
6✔
1847
                }
1848

1849
                toChain := c.shouldGoOnChain(
5✔
1850
                        htlc, c.cfg.IncomingBroadcastDelta, height,
5✔
1851
                )
5✔
1852

5✔
1853
                if toChain {
8✔
1854
                        // Convert to int64 in case of overflow.
3✔
1855
                        remainingBlocks := int64(htlc.RefundTimeout) -
3✔
1856
                                int64(height)
3✔
1857

3✔
1858
                        log.Infof("ChannelArbitrator(%v): go to chain for "+
3✔
1859
                                "incoming htlc %x: timeout=%v, amount=%v, "+
3✔
1860
                                "blocks_until_expiry=%v, broadcast_delta=%v",
3✔
1861
                                c.cfg.ChanPoint, htlc.RHash[:],
3✔
1862
                                htlc.RefundTimeout, htlc.Amt, remainingBlocks,
3✔
1863
                                c.cfg.IncomingBroadcastDelta,
3✔
1864
                        )
3✔
1865
                }
3✔
1866

1867
                haveChainActions = haveChainActions || toChain
5✔
1868
        }
1869

1870
        // If we don't have any actions to make, then we'll return an empty
1871
        // action map. We only do this if this was a chain trigger though, as
1872
        // if we're going to broadcast the commitment (or the remote party did)
1873
        // we're *forced* to act on each HTLC.
1874
        if !haveChainActions && trigger == chainTrigger {
124✔
1875
                log.Tracef("ChannelArbitrator(%v): no actions to take at "+
45✔
1876
                        "height=%v", c.cfg.ChanPoint, height)
45✔
1877
                return actionMap, nil
45✔
1878
        }
45✔
1879

1880
        // Now that we know we'll need to go on-chain, we'll examine all of our
1881
        // active outgoing HTLC's to see if we either need to: sweep them after
1882
        // a timeout (then cancel backwards), cancel them backwards
1883
        // immediately, or watch them as they're still active contracts.
1884
        for _, htlc := range htlcs.outgoingHTLCs {
46✔
1885
                switch {
9✔
1886
                // If the HTLC is dust, then we can cancel it backwards
1887
                // immediately as there's no matching contract to arbitrate
1888
                // on-chain. We know the HTLC is dust, if the OutputIndex
1889
                // negative.
1890
                case htlc.OutputIndex < 0:
5✔
1891
                        log.Tracef("ChannelArbitrator(%v): immediately "+
5✔
1892
                                "failing dust htlc=%x", c.cfg.ChanPoint,
5✔
1893
                                htlc.RHash[:])
5✔
1894

5✔
1895
                        actionMap[HtlcFailNowAction] = append(
5✔
1896
                                actionMap[HtlcFailNowAction], htlc,
5✔
1897
                        )
5✔
1898

1899
                // If we don't need to immediately act on this HTLC, then we'll
1900
                // mark it still "live". After we broadcast, we'll monitor it
1901
                // until the HTLC times out to see if we can also redeem it
1902
                // on-chain.
1903
                case !c.shouldGoOnChain(htlc, c.cfg.OutgoingBroadcastDelta,
1904
                        height,
1905
                ):
7✔
1906
                        // TODO(roasbeef): also need to be able to query
7✔
1907
                        // circuit map to see if HTLC hasn't been fully
7✔
1908
                        // resolved
7✔
1909
                        //
7✔
1910
                        //  * can't fail incoming until if outgoing not yet
7✔
1911
                        //  failed
7✔
1912

7✔
1913
                        log.Tracef("ChannelArbitrator(%v): watching chain to "+
7✔
1914
                                "decide action for outgoing htlc=%x",
7✔
1915
                                c.cfg.ChanPoint, htlc.RHash[:])
7✔
1916

7✔
1917
                        actionMap[HtlcOutgoingWatchAction] = append(
7✔
1918
                                actionMap[HtlcOutgoingWatchAction], htlc,
7✔
1919
                        )
7✔
1920

1921
                // Otherwise, we'll update our actionMap to mark that we need
1922
                // to sweep this HTLC on-chain
1923
                default:
3✔
1924
                        log.Tracef("ChannelArbitrator(%v): going on-chain to "+
3✔
1925
                                "timeout htlc=%x", c.cfg.ChanPoint, htlc.RHash[:])
3✔
1926

3✔
1927
                        actionMap[HtlcTimeoutAction] = append(
3✔
1928
                                actionMap[HtlcTimeoutAction], htlc,
3✔
1929
                        )
3✔
1930
                }
1931
        }
1932

1933
        // Similarly, for each incoming HTLC, now that we need to go on-chain,
1934
        // we'll either: sweep it immediately if we know the pre-image, or
1935
        // observe the output on-chain if we don't In this last, case we'll
1936
        // either learn of it eventually from the outgoing HTLC, or the sender
1937
        // will timeout the HTLC.
1938
        for _, htlc := range htlcs.incomingHTLCs {
44✔
1939
                // If the HTLC is dust, there is no action to be taken.
7✔
1940
                if htlc.OutputIndex < 0 {
12✔
1941
                        log.Debugf("ChannelArbitrator(%v): no resolution "+
5✔
1942
                                "needed for incoming dust htlc=%x",
5✔
1943
                                c.cfg.ChanPoint, htlc.RHash[:])
5✔
1944

5✔
1945
                        actionMap[HtlcIncomingDustFinalAction] = append(
5✔
1946
                                actionMap[HtlcIncomingDustFinalAction], htlc,
5✔
1947
                        )
5✔
1948

5✔
1949
                        continue
5✔
1950
                }
1951

1952
                log.Tracef("ChannelArbitrator(%v): watching chain to decide "+
5✔
1953
                        "action for incoming htlc=%x", c.cfg.ChanPoint,
5✔
1954
                        htlc.RHash[:])
5✔
1955

5✔
1956
                actionMap[HtlcIncomingWatchAction] = append(
5✔
1957
                        actionMap[HtlcIncomingWatchAction], htlc,
5✔
1958
                )
5✔
1959
        }
1960

1961
        return actionMap, nil
37✔
1962
}
1963

1964
// isPreimageAvailable returns whether the hash preimage is available in either
1965
// the preimage cache or the invoice database.
1966
func (c *ChannelArbitrator) isPreimageAvailable(hash lntypes.Hash) (bool,
1967
        error) {
20✔
1968

20✔
1969
        // Start by checking the preimage cache for preimages of
20✔
1970
        // forwarded HTLCs.
20✔
1971
        _, preimageAvailable := c.cfg.PreimageDB.LookupPreimage(
20✔
1972
                hash,
20✔
1973
        )
20✔
1974
        if preimageAvailable {
31✔
1975
                return true, nil
11✔
1976
        }
11✔
1977

1978
        // Then check if we have an invoice that can be settled by this HTLC.
1979
        //
1980
        // TODO(joostjager): Check that there are still more blocks remaining
1981
        // than the invoice cltv delta. We don't want to go to chain only to
1982
        // have the incoming contest resolver decide that we don't want to
1983
        // settle this invoice.
1984
        invoice, err := c.cfg.Registry.LookupInvoice(context.Background(), hash)
12✔
1985
        switch err {
12✔
1986
        case nil:
3✔
1987
        case invoices.ErrInvoiceNotFound, invoices.ErrNoInvoicesCreated:
12✔
1988
                return false, nil
12✔
1989
        default:
×
1990
                return false, err
×
1991
        }
1992

1993
        preimageAvailable = invoice.Terms.PaymentPreimage != nil
3✔
1994

3✔
1995
        return preimageAvailable, nil
3✔
1996
}
1997

1998
// checkLocalChainActions is similar to checkCommitChainActions, but it also
1999
// examines the set of HTLCs on the remote party's commitment. This allows us
2000
// to ensure we're able to satisfy the HTLC timeout constraints for incoming vs
2001
// outgoing HTLCs.
2002
func (c *ChannelArbitrator) checkLocalChainActions(
2003
        height uint32, trigger transitionTrigger,
2004
        activeHTLCs map[HtlcSetKey]htlcSet,
2005
        commitsConfirmed bool) (ChainActionMap, error) {
73✔
2006

73✔
2007
        // First, we'll check our local chain actions as normal. This will only
73✔
2008
        // examine HTLCs on our local commitment (timeout or settle).
73✔
2009
        localCommitActions, err := c.checkCommitChainActions(
73✔
2010
                height, trigger, activeHTLCs[LocalHtlcSet],
73✔
2011
        )
73✔
2012
        if err != nil {
73✔
2013
                return nil, err
×
2014
        }
×
2015

2016
        // Next, we'll examine the remote commitment (and maybe a dangling one)
2017
        // to see if the set difference of our HTLCs is non-empty. If so, then
2018
        // we may need to cancel back some HTLCs if we decide go to chain.
2019
        remoteDanglingActions := c.checkRemoteDanglingActions(
73✔
2020
                height, activeHTLCs, commitsConfirmed,
73✔
2021
        )
73✔
2022

73✔
2023
        // Finally, we'll merge the two set of chain actions.
73✔
2024
        localCommitActions.Merge(remoteDanglingActions)
73✔
2025

73✔
2026
        return localCommitActions, nil
73✔
2027
}
2028

2029
// checkRemoteDanglingActions examines the set of remote commitments for any
2030
// HTLCs that are close to timing out. If we find any, then we'll return a set
2031
// of chain actions for HTLCs that are on our commitment, but not theirs to
2032
// cancel immediately.
2033
func (c *ChannelArbitrator) checkRemoteDanglingActions(
2034
        height uint32, activeHTLCs map[HtlcSetKey]htlcSet,
2035
        commitsConfirmed bool) ChainActionMap {
73✔
2036

73✔
2037
        var (
73✔
2038
                pendingRemoteHTLCs []channeldb.HTLC
73✔
2039
                localHTLCs         = make(map[uint64]struct{})
73✔
2040
                remoteHTLCs        = make(map[uint64]channeldb.HTLC)
73✔
2041
                actionMap          = make(ChainActionMap)
73✔
2042
        )
73✔
2043

73✔
2044
        // First, we'll construct two sets of the outgoing HTLCs: those on our
73✔
2045
        // local commitment, and those that are on the remote commitment(s).
73✔
2046
        for htlcSetKey, htlcs := range activeHTLCs {
196✔
2047
                if htlcSetKey.IsRemote {
190✔
2048
                        for _, htlc := range htlcs.outgoingHTLCs {
86✔
2049
                                remoteHTLCs[htlc.HtlcIndex] = htlc
19✔
2050
                        }
19✔
2051
                } else {
59✔
2052
                        for _, htlc := range htlcs.outgoingHTLCs {
68✔
2053
                                localHTLCs[htlc.HtlcIndex] = struct{}{}
9✔
2054
                        }
9✔
2055
                }
2056
        }
2057

2058
        // With both sets constructed, we'll now compute the set difference of
2059
        // our two sets of HTLCs. This'll give us the HTLCs that exist on the
2060
        // remote commitment transaction, but not on ours.
2061
        for htlcIndex, htlc := range remoteHTLCs {
92✔
2062
                if _, ok := localHTLCs[htlcIndex]; ok {
24✔
2063
                        continue
5✔
2064
                }
2065

2066
                pendingRemoteHTLCs = append(pendingRemoteHTLCs, htlc)
17✔
2067
        }
2068

2069
        // Finally, we'll examine all the pending remote HTLCs for those that
2070
        // have expired. If we find any, then we'll recommend that they be
2071
        // failed now so we can free up the incoming HTLC.
2072
        for _, htlc := range pendingRemoteHTLCs {
90✔
2073
                // We'll now check if we need to go to chain in order to cancel
17✔
2074
                // the incoming HTLC.
17✔
2075
                goToChain := c.shouldGoOnChain(htlc, c.cfg.OutgoingBroadcastDelta,
17✔
2076
                        height,
17✔
2077
                )
17✔
2078

17✔
2079
                // If we don't need to go to chain, and no commitments have
17✔
2080
                // been confirmed, then we can move on. Otherwise, if
17✔
2081
                // commitments have been confirmed, then we need to cancel back
17✔
2082
                // *all* of the pending remote HTLCS.
17✔
2083
                if !goToChain && !commitsConfirmed {
25✔
2084
                        continue
8✔
2085
                }
2086

2087
                log.Infof("ChannelArbitrator(%v): fail dangling htlc=%x from "+
12✔
2088
                        "local/remote commitments diff",
12✔
2089
                        c.cfg.ChanPoint, htlc.RHash[:])
12✔
2090

12✔
2091
                actionMap[HtlcFailNowAction] = append(
12✔
2092
                        actionMap[HtlcFailNowAction], htlc,
12✔
2093
                )
12✔
2094
        }
2095

2096
        return actionMap
73✔
2097
}
2098

2099
// checkRemoteChainActions examines the two possible remote commitment chains
2100
// and returns the set of chain actions we need to carry out if the remote
2101
// commitment (non pending) confirms. The pendingConf indicates if the pending
2102
// remote commitment confirmed. This is similar to checkCommitChainActions, but
2103
// we'll immediately fail any HTLCs on the pending remote commit, but not the
2104
// remote commit (or the other way around).
2105
func (c *ChannelArbitrator) checkRemoteChainActions(
2106
        height uint32, trigger transitionTrigger,
2107
        activeHTLCs map[HtlcSetKey]htlcSet,
2108
        pendingConf bool) (ChainActionMap, error) {
9✔
2109

9✔
2110
        // First, we'll examine all the normal chain actions on the remote
9✔
2111
        // commitment that confirmed.
9✔
2112
        confHTLCs := activeHTLCs[RemoteHtlcSet]
9✔
2113
        if pendingConf {
11✔
2114
                confHTLCs = activeHTLCs[RemotePendingHtlcSet]
2✔
2115
        }
2✔
2116
        remoteCommitActions, err := c.checkCommitChainActions(
9✔
2117
                height, trigger, confHTLCs,
9✔
2118
        )
9✔
2119
        if err != nil {
9✔
2120
                return nil, err
×
2121
        }
×
2122

2123
        // With these actions computed, we'll now check the diff of the HTLCs on
2124
        // the commitments, and cancel back any that are on the pending but not
2125
        // the non-pending.
2126
        remoteDiffActions := c.checkRemoteDiffActions(
9✔
2127
                activeHTLCs, pendingConf,
9✔
2128
        )
9✔
2129

9✔
2130
        // Finally, we'll merge all the chain actions and the final set of
9✔
2131
        // chain actions.
9✔
2132
        remoteCommitActions.Merge(remoteDiffActions)
9✔
2133
        return remoteCommitActions, nil
9✔
2134
}
2135

2136
// checkRemoteDiffActions checks the set difference of the HTLCs on the remote
2137
// confirmed commit and remote dangling commit for HTLCS that we need to cancel
2138
// back. If we find any HTLCs on the remote pending but not the remote, then
2139
// we'll mark them to be failed immediately.
2140
func (c *ChannelArbitrator) checkRemoteDiffActions(
2141
        activeHTLCs map[HtlcSetKey]htlcSet,
2142
        pendingConf bool) ChainActionMap {
9✔
2143

9✔
2144
        // First, we'll partition the HTLCs into those that are present on the
9✔
2145
        // confirmed commitment, and those on the dangling commitment.
9✔
2146
        confHTLCs := activeHTLCs[RemoteHtlcSet]
9✔
2147
        danglingHTLCs := activeHTLCs[RemotePendingHtlcSet]
9✔
2148
        if pendingConf {
11✔
2149
                confHTLCs = activeHTLCs[RemotePendingHtlcSet]
2✔
2150
                danglingHTLCs = activeHTLCs[RemoteHtlcSet]
2✔
2151
        }
2✔
2152

2153
        // Next, we'll create a set of all the HTLCs confirmed commitment.
2154
        remoteHtlcs := make(map[uint64]struct{})
9✔
2155
        for _, htlc := range confHTLCs.outgoingHTLCs {
13✔
2156
                remoteHtlcs[htlc.HtlcIndex] = struct{}{}
4✔
2157
        }
4✔
2158

2159
        // With the remote HTLCs assembled, we'll mark any HTLCs only on the
2160
        // remote dangling commitment to be failed asap.
2161
        actionMap := make(ChainActionMap)
9✔
2162
        for _, htlc := range danglingHTLCs.outgoingHTLCs {
16✔
2163
                if _, ok := remoteHtlcs[htlc.HtlcIndex]; ok {
10✔
2164
                        continue
3✔
2165
                }
2166

2167
                preimageAvailable, err := c.isPreimageAvailable(htlc.RHash)
4✔
2168
                if err != nil {
4✔
2169
                        log.Errorf("ChannelArbitrator(%v): failed to query "+
×
2170
                                "preimage for dangling htlc=%x from remote "+
×
2171
                                "commitments diff", c.cfg.ChanPoint,
×
2172
                                htlc.RHash[:])
×
2173

×
2174
                        continue
×
2175
                }
2176

2177
                if preimageAvailable {
4✔
2178
                        continue
×
2179
                }
2180

2181
                actionMap[HtlcFailNowAction] = append(
4✔
2182
                        actionMap[HtlcFailNowAction], htlc,
4✔
2183
                )
4✔
2184

4✔
2185
                log.Infof("ChannelArbitrator(%v): fail dangling htlc=%x from "+
4✔
2186
                        "remote commitments diff",
4✔
2187
                        c.cfg.ChanPoint, htlc.RHash[:])
4✔
2188
        }
2189

2190
        return actionMap
9✔
2191
}
2192

2193
// constructChainActions returns the set of actions that should be taken for
2194
// confirmed HTLCs at the specified height. Our actions will depend on the set
2195
// of HTLCs that were active across all channels at the time of channel
2196
// closure.
2197
func (c *ChannelArbitrator) constructChainActions(confCommitSet *CommitSet,
2198
        height uint32, trigger transitionTrigger) (ChainActionMap, error) {
15✔
2199

15✔
2200
        // If we've reached this point and have not confirmed commitment set,
15✔
2201
        // then this is an older node that had a pending close channel before
15✔
2202
        // the CommitSet was introduced. In this case, we'll just return the
15✔
2203
        // existing ChainActionMap they had on disk.
15✔
2204
        if confCommitSet == nil {
15✔
2205
                return c.log.FetchChainActions()
×
2206
        }
×
2207

2208
        // Otherwise, we have the full commitment set written to disk, and can
2209
        // proceed as normal.
2210
        htlcSets := confCommitSet.toActiveHTLCSets()
15✔
2211
        switch *confCommitSet.ConfCommitKey {
15✔
2212

2213
        // If the local commitment transaction confirmed, then we'll examine
2214
        // that as well as their commitments to the set of chain actions.
2215
        case LocalHtlcSet:
9✔
2216
                return c.checkLocalChainActions(
9✔
2217
                        height, trigger, htlcSets, true,
9✔
2218
                )
9✔
2219

2220
        // If the remote commitment confirmed, then we'll grab all the chain
2221
        // actions for the remote commit, and check the pending commit for any
2222
        // HTLCS we need to handle immediately (dust).
2223
        case RemoteHtlcSet:
7✔
2224
                return c.checkRemoteChainActions(
7✔
2225
                        height, trigger, htlcSets, false,
7✔
2226
                )
7✔
2227

2228
        // Otherwise, the remote pending commitment confirmed, so we'll examine
2229
        // the HTLCs on that unrevoked dangling commitment.
2230
        case RemotePendingHtlcSet:
2✔
2231
                return c.checkRemoteChainActions(
2✔
2232
                        height, trigger, htlcSets, true,
2✔
2233
                )
2✔
2234
        }
2235

2236
        return nil, fmt.Errorf("unable to locate chain actions")
×
2237
}
2238

2239
// prepContractResolutions is called either in the case that we decide we need
2240
// to go to chain, or the remote party goes to chain. Given a set of actions we
2241
// need to take for each HTLC, this method will return a set of contract
2242
// resolvers that will resolve the contracts on-chain if needed, and also a set
2243
// of packets to send to the htlcswitch in order to ensure all incoming HTLC's
2244
// are properly resolved.
2245
func (c *ChannelArbitrator) prepContractResolutions(
2246
        contractResolutions *ContractResolutions, height uint32,
2247
        trigger transitionTrigger,
2248
        confCommitSet *CommitSet) ([]ContractResolver, []ResolutionMsg, error) {
15✔
2249

15✔
2250
        // First, we'll reconstruct a fresh set of chain actions as the set of
15✔
2251
        // actions we need to act on may differ based on if it was our
15✔
2252
        // commitment, or they're commitment that hit the chain.
15✔
2253
        htlcActions, err := c.constructChainActions(
15✔
2254
                confCommitSet, height, trigger,
15✔
2255
        )
15✔
2256
        if err != nil {
15✔
2257
                return nil, nil, err
×
2258
        }
×
2259

2260
        // We'll also fetch the historical state of this channel, as it should
2261
        // have been marked as closed by now, and supplement it to each resolver
2262
        // such that we can properly resolve our pending contracts.
2263
        var chanState *channeldb.OpenChannel
15✔
2264
        chanState, err = c.cfg.FetchHistoricalChannel()
15✔
2265
        switch {
15✔
2266
        // If we don't find this channel, then it may be the case that it
2267
        // was closed before we started to retain the final state
2268
        // information for open channels.
2269
        case err == channeldb.ErrNoHistoricalBucket:
×
2270
                fallthrough
×
2271
        case err == channeldb.ErrChannelNotFound:
×
2272
                log.Warnf("ChannelArbitrator(%v): unable to fetch historical "+
×
2273
                        "state", c.cfg.ChanPoint)
×
2274

2275
        case err != nil:
×
2276
                return nil, nil, err
×
2277
        }
2278

2279
        // There may be a class of HTLC's which we can fail back immediately,
2280
        // for those we'll prepare a slice of packets to add to our outbox. Any
2281
        // packets we need to send, will be cancels.
2282
        var (
15✔
2283
                msgsToSend []ResolutionMsg
15✔
2284
        )
15✔
2285

15✔
2286
        incomingResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs
15✔
2287
        outgoingResolutions := contractResolutions.HtlcResolutions.OutgoingHTLCs
15✔
2288

15✔
2289
        // We'll use these two maps to quickly look up an active HTLC with its
15✔
2290
        // matching HTLC resolution.
15✔
2291
        outResolutionMap := make(map[wire.OutPoint]lnwallet.OutgoingHtlcResolution)
15✔
2292
        inResolutionMap := make(map[wire.OutPoint]lnwallet.IncomingHtlcResolution)
15✔
2293
        for i := 0; i < len(incomingResolutions); i++ {
18✔
2294
                inRes := incomingResolutions[i]
3✔
2295
                inResolutionMap[inRes.HtlcPoint()] = inRes
3✔
2296
        }
3✔
2297
        for i := 0; i < len(outgoingResolutions); i++ {
19✔
2298
                outRes := outgoingResolutions[i]
4✔
2299
                outResolutionMap[outRes.HtlcPoint()] = outRes
4✔
2300
        }
4✔
2301

2302
        // We'll create the resolver kit that we'll be cloning for each
2303
        // resolver so they each can do their duty.
2304
        resolverCfg := ResolverConfig{
15✔
2305
                ChannelArbitratorConfig: c.cfg,
15✔
2306
                Checkpoint: func(res ContractResolver,
15✔
2307
                        reports ...*channeldb.ResolverReport) error {
20✔
2308

5✔
2309
                        return c.log.InsertUnresolvedContracts(reports, res)
5✔
2310
                },
5✔
2311
        }
2312

2313
        commitHash := contractResolutions.CommitHash
15✔
2314
        failureMsg := &lnwire.FailPermanentChannelFailure{}
15✔
2315

15✔
2316
        var htlcResolvers []ContractResolver
15✔
2317

15✔
2318
        // We instantiate an anchor resolver if the commitment tx has an
15✔
2319
        // anchor.
15✔
2320
        if contractResolutions.AnchorResolution != nil {
20✔
2321
                anchorResolver := newAnchorResolver(
5✔
2322
                        contractResolutions.AnchorResolution.AnchorSignDescriptor,
5✔
2323
                        contractResolutions.AnchorResolution.CommitAnchor,
5✔
2324
                        height, c.cfg.ChanPoint, resolverCfg,
5✔
2325
                )
5✔
2326
                anchorResolver.SupplementState(chanState)
5✔
2327

5✔
2328
                htlcResolvers = append(htlcResolvers, anchorResolver)
5✔
2329
        }
5✔
2330

2331
        // If this is a breach close, we'll create a breach resolver, determine
2332
        // the htlc's to fail back, and exit. This is done because the other
2333
        // steps taken for non-breach-closes do not matter for breach-closes.
2334
        if contractResolutions.BreachResolution != nil {
20✔
2335
                breachResolver := newBreachResolver(resolverCfg)
5✔
2336
                htlcResolvers = append(htlcResolvers, breachResolver)
5✔
2337

5✔
2338
                // We'll use the CommitSet, we'll fail back all outgoing HTLC's
5✔
2339
                // that exist on either of the remote commitments. The map is
5✔
2340
                // used to deduplicate any shared htlc's.
5✔
2341
                remoteOutgoing := make(map[uint64]channeldb.HTLC)
5✔
2342
                for htlcSetKey, htlcs := range confCommitSet.HtlcSets {
10✔
2343
                        if !htlcSetKey.IsRemote {
8✔
2344
                                continue
3✔
2345
                        }
2346

2347
                        for _, htlc := range htlcs {
10✔
2348
                                if htlc.Incoming {
9✔
2349
                                        continue
4✔
2350
                                }
2351

2352
                                remoteOutgoing[htlc.HtlcIndex] = htlc
4✔
2353
                        }
2354
                }
2355

2356
                // Now we'll loop over the map and create ResolutionMsgs for
2357
                // each of them.
2358
                for _, htlc := range remoteOutgoing {
9✔
2359
                        failMsg := ResolutionMsg{
4✔
2360
                                SourceChan: c.cfg.ShortChanID,
4✔
2361
                                HtlcIndex:  htlc.HtlcIndex,
4✔
2362
                                Failure:    failureMsg,
4✔
2363
                        }
4✔
2364

4✔
2365
                        msgsToSend = append(msgsToSend, failMsg)
4✔
2366
                }
4✔
2367

2368
                return htlcResolvers, msgsToSend, nil
5✔
2369
        }
2370

2371
        // For each HTLC, we'll either act immediately, meaning we'll instantly
2372
        // fail the HTLC, or we'll act only once the transaction has been
2373
        // confirmed, in which case we'll need an HTLC resolver.
2374
        for htlcAction, htlcs := range htlcActions {
27✔
2375
                switch htlcAction {
14✔
2376

2377
                // If we can fail an HTLC immediately (an outgoing HTLC with no
2378
                // contract), then we'll assemble an HTLC fail packet to send.
2379
                case HtlcFailNowAction:
12✔
2380
                        for _, htlc := range htlcs {
24✔
2381
                                failMsg := ResolutionMsg{
12✔
2382
                                        SourceChan: c.cfg.ShortChanID,
12✔
2383
                                        HtlcIndex:  htlc.HtlcIndex,
12✔
2384
                                        Failure:    failureMsg,
12✔
2385
                                }
12✔
2386

12✔
2387
                                msgsToSend = append(msgsToSend, failMsg)
12✔
2388
                        }
12✔
2389

2390
                // If we can claim this HTLC, we'll create an HTLC resolver to
2391
                // claim the HTLC (second-level or directly), then add the pre
2392
                case HtlcClaimAction:
×
2393
                        for _, htlc := range htlcs {
×
2394
                                htlc := htlc
×
2395

×
2396
                                htlcOp := wire.OutPoint{
×
2397
                                        Hash:  commitHash,
×
2398
                                        Index: uint32(htlc.OutputIndex),
×
2399
                                }
×
2400

×
2401
                                resolution, ok := inResolutionMap[htlcOp]
×
2402
                                if !ok {
×
2403
                                        // TODO(roasbeef): panic?
×
2404
                                        log.Errorf("ChannelArbitrator(%v) unable to find "+
×
2405
                                                "incoming resolution: %v",
×
2406
                                                c.cfg.ChanPoint, htlcOp)
×
2407
                                        continue
×
2408
                                }
2409

2410
                                resolver := newSuccessResolver(
×
2411
                                        resolution, height, htlc, resolverCfg,
×
2412
                                )
×
2413
                                if chanState != nil {
×
2414
                                        resolver.SupplementState(chanState)
×
2415
                                }
×
2416
                                htlcResolvers = append(htlcResolvers, resolver)
×
2417
                        }
2418

2419
                // If we can timeout the HTLC directly, then we'll create the
2420
                // proper resolver to do so, who will then cancel the packet
2421
                // backwards.
2422
                case HtlcTimeoutAction:
3✔
2423
                        for _, htlc := range htlcs {
6✔
2424
                                htlc := htlc
3✔
2425

3✔
2426
                                htlcOp := wire.OutPoint{
3✔
2427
                                        Hash:  commitHash,
3✔
2428
                                        Index: uint32(htlc.OutputIndex),
3✔
2429
                                }
3✔
2430

3✔
2431
                                resolution, ok := outResolutionMap[htlcOp]
3✔
2432
                                if !ok {
3✔
2433
                                        log.Errorf("ChannelArbitrator(%v) unable to find "+
×
2434
                                                "outgoing resolution: %v", c.cfg.ChanPoint, htlcOp)
×
2435
                                        continue
×
2436
                                }
2437

2438
                                resolver := newTimeoutResolver(
3✔
2439
                                        resolution, height, htlc, resolverCfg,
3✔
2440
                                )
3✔
2441
                                if chanState != nil {
6✔
2442
                                        resolver.SupplementState(chanState)
3✔
2443
                                }
3✔
2444

2445
                                // For outgoing HTLCs, we will also need to
2446
                                // supplement the resolver with the expiry
2447
                                // block height of its corresponding incoming
2448
                                // HTLC.
2449
                                deadline := c.cfg.FindOutgoingHTLCDeadline(htlc)
3✔
2450
                                resolver.SupplementDeadline(deadline)
3✔
2451

3✔
2452
                                htlcResolvers = append(htlcResolvers, resolver)
3✔
2453
                        }
2454

2455
                // If this is an incoming HTLC, but we can't act yet, then
2456
                // we'll create an incoming resolver to redeem the HTLC if we
2457
                // learn of the pre-image, or let the remote party time out.
2458
                case HtlcIncomingWatchAction:
3✔
2459
                        for _, htlc := range htlcs {
6✔
2460
                                htlc := htlc
3✔
2461

3✔
2462
                                htlcOp := wire.OutPoint{
3✔
2463
                                        Hash:  commitHash,
3✔
2464
                                        Index: uint32(htlc.OutputIndex),
3✔
2465
                                }
3✔
2466

3✔
2467
                                // TODO(roasbeef): need to handle incoming dust...
3✔
2468

3✔
2469
                                // TODO(roasbeef): can't be negative!!!
3✔
2470
                                resolution, ok := inResolutionMap[htlcOp]
3✔
2471
                                if !ok {
3✔
2472
                                        log.Errorf("ChannelArbitrator(%v) unable to find "+
×
2473
                                                "incoming resolution: %v",
×
2474
                                                c.cfg.ChanPoint, htlcOp)
×
2475
                                        continue
×
2476
                                }
2477

2478
                                resolver := newIncomingContestResolver(
3✔
2479
                                        resolution, height, htlc,
3✔
2480
                                        resolverCfg,
3✔
2481
                                )
3✔
2482
                                if chanState != nil {
6✔
2483
                                        resolver.SupplementState(chanState)
3✔
2484
                                }
3✔
2485
                                htlcResolvers = append(htlcResolvers, resolver)
3✔
2486
                        }
2487

2488
                // We've lost an htlc because it isn't manifested on the
2489
                // commitment transaction that closed the channel.
2490
                case HtlcIncomingDustFinalAction:
4✔
2491
                        for _, htlc := range htlcs {
8✔
2492
                                htlc := htlc
4✔
2493

4✔
2494
                                key := models.CircuitKey{
4✔
2495
                                        ChanID: c.cfg.ShortChanID,
4✔
2496
                                        HtlcID: htlc.HtlcIndex,
4✔
2497
                                }
4✔
2498

4✔
2499
                                // Mark this dust htlc as final failed.
4✔
2500
                                chainArbCfg := c.cfg.ChainArbitratorConfig
4✔
2501
                                err := chainArbCfg.PutFinalHtlcOutcome(
4✔
2502
                                        key.ChanID, key.HtlcID, false,
4✔
2503
                                )
4✔
2504
                                if err != nil {
4✔
2505
                                        return nil, nil, err
×
2506
                                }
×
2507

2508
                                // Send notification.
2509
                                chainArbCfg.HtlcNotifier.NotifyFinalHtlcEvent(
4✔
2510
                                        key,
4✔
2511
                                        channeldb.FinalHtlcInfo{
4✔
2512
                                                Settled:  false,
4✔
2513
                                                Offchain: false,
4✔
2514
                                        },
4✔
2515
                                )
4✔
2516
                        }
2517

2518
                // Finally, if this is an outgoing HTLC we've sent, then we'll
2519
                // launch a resolver to watch for the pre-image (and settle
2520
                // backwards), or just timeout.
2521
                case HtlcOutgoingWatchAction:
4✔
2522
                        for _, htlc := range htlcs {
8✔
2523
                                htlc := htlc
4✔
2524

4✔
2525
                                htlcOp := wire.OutPoint{
4✔
2526
                                        Hash:  commitHash,
4✔
2527
                                        Index: uint32(htlc.OutputIndex),
4✔
2528
                                }
4✔
2529

4✔
2530
                                resolution, ok := outResolutionMap[htlcOp]
4✔
2531
                                if !ok {
4✔
2532
                                        log.Errorf("ChannelArbitrator(%v) unable to find "+
×
2533
                                                "outgoing resolution: %v",
×
2534
                                                c.cfg.ChanPoint, htlcOp)
×
2535
                                        continue
×
2536
                                }
2537

2538
                                resolver := newOutgoingContestResolver(
4✔
2539
                                        resolution, height, htlc, resolverCfg,
4✔
2540
                                )
4✔
2541
                                if chanState != nil {
8✔
2542
                                        resolver.SupplementState(chanState)
4✔
2543
                                }
4✔
2544

2545
                                // For outgoing HTLCs, we will also need to
2546
                                // supplement the resolver with the expiry
2547
                                // block height of its corresponding incoming
2548
                                // HTLC.
2549
                                deadline := c.cfg.FindOutgoingHTLCDeadline(htlc)
4✔
2550
                                resolver.SupplementDeadline(deadline)
4✔
2551

4✔
2552
                                htlcResolvers = append(htlcResolvers, resolver)
4✔
2553
                        }
2554
                }
2555
        }
2556

2557
        // If this is was an unilateral closure, then we'll also create a
2558
        // resolver to sweep our commitment output (but only if it wasn't
2559
        // trimmed).
2560
        if contractResolutions.CommitResolution != nil {
16✔
2561
                resolver := newCommitSweepResolver(
3✔
2562
                        *contractResolutions.CommitResolution, height,
3✔
2563
                        c.cfg.ChanPoint, resolverCfg,
3✔
2564
                )
3✔
2565
                if chanState != nil {
6✔
2566
                        resolver.SupplementState(chanState)
3✔
2567
                }
3✔
2568
                htlcResolvers = append(htlcResolvers, resolver)
3✔
2569
        }
2570

2571
        return htlcResolvers, msgsToSend, nil
13✔
2572
}
2573

2574
// replaceResolver replaces a in the list of active resolvers. If the resolver
2575
// to be replaced is not found, it returns an error.
2576
func (c *ChannelArbitrator) replaceResolver(oldResolver,
2577
        newResolver ContractResolver) error {
4✔
2578

4✔
2579
        c.activeResolversLock.Lock()
4✔
2580
        defer c.activeResolversLock.Unlock()
4✔
2581

4✔
2582
        oldKey := oldResolver.ResolverKey()
4✔
2583
        for i, r := range c.activeResolvers {
8✔
2584
                if bytes.Equal(r.ResolverKey(), oldKey) {
8✔
2585
                        c.activeResolvers[i] = newResolver
4✔
2586
                        return nil
4✔
2587
                }
4✔
2588
        }
2589

2590
        return errors.New("resolver to be replaced not found")
×
2591
}
2592

2593
// resolveContract is a goroutine tasked with fully resolving an unresolved
2594
// contract. Either the initial contract will be resolved after a single step,
2595
// or the contract will itself create another contract to be resolved. In
2596
// either case, one the contract has been fully resolved, we'll signal back to
2597
// the main goroutine so it can properly keep track of the set of unresolved
2598
// contracts.
2599
//
2600
// NOTE: This MUST be run as a goroutine.
2601
func (c *ChannelArbitrator) resolveContract(currentContract ContractResolver,
2602
        immediate bool) {
9✔
2603

9✔
2604
        defer c.wg.Done()
9✔
2605

9✔
2606
        log.Debugf("ChannelArbitrator(%v): attempting to resolve %T",
9✔
2607
                c.cfg.ChanPoint, currentContract)
9✔
2608

9✔
2609
        // Until the contract is fully resolved, we'll continue to iteratively
9✔
2610
        // resolve the contract one step at a time.
9✔
2611
        for !currentContract.IsResolved() {
19✔
2612
                log.Debugf("ChannelArbitrator(%v): contract %T not yet resolved",
10✔
2613
                        c.cfg.ChanPoint, currentContract)
10✔
2614

10✔
2615
                select {
10✔
2616

2617
                // If we've been signalled to quit, then we'll exit early.
2618
                case <-c.quit:
×
2619
                        return
×
2620

2621
                default:
10✔
2622
                        // Otherwise, we'll attempt to resolve the current
10✔
2623
                        // contract.
10✔
2624
                        nextContract, err := currentContract.Resolve(immediate)
10✔
2625
                        if err != nil {
14✔
2626
                                if err == errResolverShuttingDown {
7✔
2627
                                        return
3✔
2628
                                }
3✔
2629

2630
                                log.Errorf("ChannelArbitrator(%v): unable to "+
4✔
2631
                                        "progress %T: %v",
4✔
2632
                                        c.cfg.ChanPoint, currentContract, err)
4✔
2633
                                return
4✔
2634
                        }
2635

2636
                        switch {
9✔
2637
                        // If this contract produced another, then this means
2638
                        // the current contract was only able to be partially
2639
                        // resolved in this step. So we'll do a contract swap
2640
                        // within our logs: the new contract will take the
2641
                        // place of the old one.
2642
                        case nextContract != nil:
4✔
2643
                                log.Debugf("ChannelArbitrator(%v): swapping "+
4✔
2644
                                        "out contract %T for %T ",
4✔
2645
                                        c.cfg.ChanPoint, currentContract,
4✔
2646
                                        nextContract)
4✔
2647

4✔
2648
                                // Swap contract in log.
4✔
2649
                                err := c.log.SwapContract(
4✔
2650
                                        currentContract, nextContract,
4✔
2651
                                )
4✔
2652
                                if err != nil {
4✔
2653
                                        log.Errorf("unable to add recurse "+
×
2654
                                                "contract: %v", err)
×
2655
                                }
×
2656

2657
                                // Swap contract in resolvers list. This is to
2658
                                // make sure that reports are queried from the
2659
                                // new resolver.
2660
                                err = c.replaceResolver(
4✔
2661
                                        currentContract, nextContract,
4✔
2662
                                )
4✔
2663
                                if err != nil {
4✔
2664
                                        log.Errorf("unable to replace "+
×
2665
                                                "contract: %v", err)
×
2666
                                }
×
2667

2668
                                // As this contract produced another, we'll
2669
                                // re-assign, so we can continue our resolution
2670
                                // loop.
2671
                                currentContract = nextContract
4✔
2672

2673
                        // If this contract is actually fully resolved, then
2674
                        // we'll mark it as such within the database.
2675
                        case currentContract.IsResolved():
8✔
2676
                                log.Debugf("ChannelArbitrator(%v): marking "+
8✔
2677
                                        "contract %T fully resolved",
8✔
2678
                                        c.cfg.ChanPoint, currentContract)
8✔
2679

8✔
2680
                                err := c.log.ResolveContract(currentContract)
8✔
2681
                                if err != nil {
8✔
2682
                                        log.Errorf("unable to resolve contract: %v",
×
2683
                                                err)
×
2684
                                }
×
2685

2686
                                // Now that the contract has been resolved,
2687
                                // well signal to the main goroutine.
2688
                                select {
8✔
2689
                                case c.resolutionSignal <- struct{}{}:
7✔
2690
                                case <-c.quit:
4✔
2691
                                        return
4✔
2692
                                }
2693
                        }
2694

2695
                }
2696
        }
2697
}
2698

2699
// signalUpdateMsg is a struct that carries fresh signals to the
2700
// ChannelArbitrator. We need to receive a message like this each time the
2701
// channel becomes active, as it's internal state may change.
2702
type signalUpdateMsg struct {
2703
        // newSignals is the set of new active signals to be sent to the
2704
        // arbitrator.
2705
        newSignals *ContractSignals
2706

2707
        // doneChan is a channel that will be closed on the arbitrator has
2708
        // attached the new signals.
2709
        doneChan chan struct{}
2710
}
2711

2712
// UpdateContractSignals updates the set of signals the ChannelArbitrator needs
2713
// to receive from a channel in real-time in order to keep in sync with the
2714
// latest state of the contract.
2715
func (c *ChannelArbitrator) UpdateContractSignals(newSignals *ContractSignals) {
14✔
2716
        done := make(chan struct{})
14✔
2717

14✔
2718
        select {
14✔
2719
        case c.signalUpdates <- &signalUpdateMsg{
2720
                newSignals: newSignals,
2721
                doneChan:   done,
2722
        }:
14✔
2723
        case <-c.quit:
×
2724
        }
2725

2726
        select {
14✔
2727
        case <-done:
14✔
2728
        case <-c.quit:
×
2729
        }
2730
}
2731

2732
// notifyContractUpdate updates the ChannelArbitrator's unmerged mappings such
2733
// that it can later be merged with activeHTLCs when calling
2734
// checkLocalChainActions or sweepAnchors. These are the only two places that
2735
// activeHTLCs is used.
2736
func (c *ChannelArbitrator) notifyContractUpdate(upd *ContractUpdate) {
15✔
2737
        c.unmergedMtx.Lock()
15✔
2738
        defer c.unmergedMtx.Unlock()
15✔
2739

15✔
2740
        // Update the mapping.
15✔
2741
        c.unmergedSet[upd.HtlcKey] = newHtlcSet(upd.Htlcs)
15✔
2742

15✔
2743
        log.Tracef("ChannelArbitrator(%v): fresh set of htlcs=%v",
15✔
2744
                c.cfg.ChanPoint, lnutils.SpewLogClosure(upd))
15✔
2745
}
15✔
2746

2747
// updateActiveHTLCs merges the unmerged set of HTLCs from the link with
2748
// activeHTLCs.
2749
func (c *ChannelArbitrator) updateActiveHTLCs() {
76✔
2750
        c.unmergedMtx.RLock()
76✔
2751
        defer c.unmergedMtx.RUnlock()
76✔
2752

76✔
2753
        // Update the mapping.
76✔
2754
        c.activeHTLCs[LocalHtlcSet] = c.unmergedSet[LocalHtlcSet]
76✔
2755
        c.activeHTLCs[RemoteHtlcSet] = c.unmergedSet[RemoteHtlcSet]
76✔
2756

76✔
2757
        // If the pending set exists, update that as well.
76✔
2758
        if _, ok := c.unmergedSet[RemotePendingHtlcSet]; ok {
88✔
2759
                pendingSet := c.unmergedSet[RemotePendingHtlcSet]
12✔
2760
                c.activeHTLCs[RemotePendingHtlcSet] = pendingSet
12✔
2761
        }
12✔
2762
}
2763

2764
// channelAttendant is the primary goroutine that acts at the judicial
2765
// arbitrator between our channel state, the remote channel peer, and the
2766
// blockchain (Our judge). This goroutine will ensure that we faithfully execute
2767
// all clauses of our contract in the case that we need to go on-chain for a
2768
// dispute. Currently, two such conditions warrant our intervention: when an
2769
// outgoing HTLC is about to timeout, and when we know the pre-image for an
2770
// incoming HTLC, but it hasn't yet been settled off-chain. In these cases,
2771
// we'll: broadcast our commitment, cancel/settle any HTLC's backwards after
2772
// sufficient confirmation, and finally send our set of outputs to the UTXO
2773
// Nursery for incubation, and ultimate sweeping.
2774
//
2775
// NOTE: This MUST be run as a goroutine.
2776
func (c *ChannelArbitrator) channelAttendant(bestHeight int32) {
50✔
2777

50✔
2778
        // TODO(roasbeef): tell top chain arb we're done
50✔
2779
        defer func() {
97✔
2780
                c.wg.Done()
47✔
2781
        }()
47✔
2782

2783
        for {
158✔
2784
                select {
108✔
2785

2786
                // A new block has arrived, we'll examine all the active HTLC's
2787
                // to see if any of them have expired, and also update our
2788
                // track of the best current height.
2789
                case blockHeight, ok := <-c.blocks:
26✔
2790
                        if !ok {
37✔
2791
                                return
11✔
2792
                        }
11✔
2793
                        bestHeight = blockHeight
18✔
2794

18✔
2795
                        // If we're not in the default state, then we can
18✔
2796
                        // ignore this signal as we're waiting for contract
18✔
2797
                        // resolution.
18✔
2798
                        if c.state != StateDefault {
30✔
2799
                                continue
12✔
2800
                        }
2801

2802
                        // Now that a new block has arrived, we'll attempt to
2803
                        // advance our state forward.
2804
                        nextState, _, err := c.advanceState(
9✔
2805
                                uint32(bestHeight), chainTrigger, nil,
9✔
2806
                        )
9✔
2807
                        if err != nil {
9✔
2808
                                log.Errorf("Unable to advance state: %v", err)
×
2809
                        }
×
2810

2811
                        // If as a result of this trigger, the contract is
2812
                        // fully resolved, then well exit.
2813
                        if nextState == StateFullyResolved {
9✔
2814
                                return
×
2815
                        }
×
2816

2817
                // A new signal update was just sent. This indicates that the
2818
                // channel under watch is now live, and may modify its internal
2819
                // state, so we'll get the most up to date signals to we can
2820
                // properly do our job.
2821
                case signalUpdate := <-c.signalUpdates:
14✔
2822
                        log.Tracef("ChannelArbitrator(%v): got new signal "+
14✔
2823
                                "update!", c.cfg.ChanPoint)
14✔
2824

14✔
2825
                        // We'll update the ShortChannelID.
14✔
2826
                        c.cfg.ShortChanID = signalUpdate.newSignals.ShortChanID
14✔
2827

14✔
2828
                        // Now that the signal has been updated, we'll now
14✔
2829
                        // close the done channel to signal to the caller we've
14✔
2830
                        // registered the new ShortChannelID.
14✔
2831
                        close(signalUpdate.doneChan)
14✔
2832

2833
                // We've cooperatively closed the channel, so we're no longer
2834
                // needed. We'll mark the channel as resolved and exit.
2835
                case closeInfo := <-c.cfg.ChainEvents.CooperativeClosure:
5✔
2836
                        log.Infof("ChannelArbitrator(%v) marking channel "+
5✔
2837
                                "cooperatively closed", c.cfg.ChanPoint)
5✔
2838

5✔
2839
                        err := c.cfg.MarkChannelClosed(
5✔
2840
                                closeInfo.ChannelCloseSummary,
5✔
2841
                                channeldb.ChanStatusCoopBroadcasted,
5✔
2842
                        )
5✔
2843
                        if err != nil {
5✔
2844
                                log.Errorf("Unable to mark channel closed: "+
×
2845
                                        "%v", err)
×
2846
                                return
×
2847
                        }
×
2848

2849
                        // We'll now advance our state machine until it reaches
2850
                        // a terminal state, and the channel is marked resolved.
2851
                        _, _, err = c.advanceState(
5✔
2852
                                closeInfo.CloseHeight, coopCloseTrigger, nil,
5✔
2853
                        )
5✔
2854
                        if err != nil {
6✔
2855
                                log.Errorf("Unable to advance state: %v", err)
1✔
2856
                                return
1✔
2857
                        }
1✔
2858

2859
                // We have broadcasted our commitment, and it is now confirmed
2860
                // on-chain.
2861
                case closeInfo := <-c.cfg.ChainEvents.LocalUnilateralClosure:
15✔
2862
                        log.Infof("ChannelArbitrator(%v): local on-chain "+
15✔
2863
                                "channel close", c.cfg.ChanPoint)
15✔
2864

15✔
2865
                        if c.state != StateCommitmentBroadcasted {
19✔
2866
                                log.Errorf("ChannelArbitrator(%v): unexpected "+
4✔
2867
                                        "local on-chain channel close",
4✔
2868
                                        c.cfg.ChanPoint)
4✔
2869
                        }
4✔
2870
                        closeTx := closeInfo.CloseTx
15✔
2871

15✔
2872
                        contractRes := &ContractResolutions{
15✔
2873
                                CommitHash:       closeTx.TxHash(),
15✔
2874
                                CommitResolution: closeInfo.CommitResolution,
15✔
2875
                                HtlcResolutions:  *closeInfo.HtlcResolutions,
15✔
2876
                                AnchorResolution: closeInfo.AnchorResolution,
15✔
2877
                        }
15✔
2878

15✔
2879
                        // When processing a unilateral close event, we'll
15✔
2880
                        // transition to the ContractClosed state. We'll log
15✔
2881
                        // out the set of resolutions such that they are
15✔
2882
                        // available to fetch in that state, we'll also write
15✔
2883
                        // the commit set so we can reconstruct our chain
15✔
2884
                        // actions on restart.
15✔
2885
                        err := c.log.LogContractResolutions(contractRes)
15✔
2886
                        if err != nil {
15✔
2887
                                log.Errorf("Unable to write resolutions: %v",
×
2888
                                        err)
×
2889
                                return
×
2890
                        }
×
2891
                        err = c.log.InsertConfirmedCommitSet(
15✔
2892
                                &closeInfo.CommitSet,
15✔
2893
                        )
15✔
2894
                        if err != nil {
15✔
2895
                                log.Errorf("Unable to write commit set: %v",
×
2896
                                        err)
×
2897
                                return
×
2898
                        }
×
2899

2900
                        // After the set of resolutions are successfully
2901
                        // logged, we can safely close the channel. After this
2902
                        // succeeds we won't be getting chain events anymore,
2903
                        // so we must make sure we can recover on restart after
2904
                        // it is marked closed. If the next state transition
2905
                        // fails, we'll start up in the prior state again, and
2906
                        // we won't be longer getting chain events. In this
2907
                        // case we must manually re-trigger the state
2908
                        // transition into StateContractClosed based on the
2909
                        // close status of the channel.
2910
                        err = c.cfg.MarkChannelClosed(
15✔
2911
                                closeInfo.ChannelCloseSummary,
15✔
2912
                                channeldb.ChanStatusLocalCloseInitiator,
15✔
2913
                        )
15✔
2914
                        if err != nil {
15✔
2915
                                log.Errorf("Unable to mark "+
×
2916
                                        "channel closed: %v", err)
×
2917
                                return
×
2918
                        }
×
2919

2920
                        // We'll now advance our state machine until it reaches
2921
                        // a terminal state.
2922
                        _, _, err = c.advanceState(
15✔
2923
                                uint32(closeInfo.SpendingHeight),
15✔
2924
                                localCloseTrigger, &closeInfo.CommitSet,
15✔
2925
                        )
15✔
2926
                        if err != nil {
16✔
2927
                                log.Errorf("Unable to advance state: %v", err)
1✔
2928
                        }
1✔
2929

2930
                // The remote party has broadcast the commitment on-chain.
2931
                // We'll examine our state to determine if we need to act at
2932
                // all.
2933
                case uniClosure := <-c.cfg.ChainEvents.RemoteUnilateralClosure:
11✔
2934
                        log.Infof("ChannelArbitrator(%v): remote party has "+
11✔
2935
                                "closed channel out on-chain", c.cfg.ChanPoint)
11✔
2936

11✔
2937
                        // If we don't have a self output, and there are no
11✔
2938
                        // active HTLC's, then we can immediately mark the
11✔
2939
                        // contract as fully resolved and exit.
11✔
2940
                        contractRes := &ContractResolutions{
11✔
2941
                                CommitHash:       *uniClosure.SpenderTxHash,
11✔
2942
                                CommitResolution: uniClosure.CommitResolution,
11✔
2943
                                HtlcResolutions:  *uniClosure.HtlcResolutions,
11✔
2944
                                AnchorResolution: uniClosure.AnchorResolution,
11✔
2945
                        }
11✔
2946

11✔
2947
                        // When processing a unilateral close event, we'll
11✔
2948
                        // transition to the ContractClosed state. We'll log
11✔
2949
                        // out the set of resolutions such that they are
11✔
2950
                        // available to fetch in that state, we'll also write
11✔
2951
                        // the commit set so we can reconstruct our chain
11✔
2952
                        // actions on restart.
11✔
2953
                        err := c.log.LogContractResolutions(contractRes)
11✔
2954
                        if err != nil {
12✔
2955
                                log.Errorf("Unable to write resolutions: %v",
1✔
2956
                                        err)
1✔
2957
                                return
1✔
2958
                        }
1✔
2959
                        err = c.log.InsertConfirmedCommitSet(
10✔
2960
                                &uniClosure.CommitSet,
10✔
2961
                        )
10✔
2962
                        if err != nil {
10✔
2963
                                log.Errorf("Unable to write commit set: %v",
×
2964
                                        err)
×
2965
                                return
×
2966
                        }
×
2967

2968
                        // After the set of resolutions are successfully
2969
                        // logged, we can safely close the channel. After this
2970
                        // succeeds we won't be getting chain events anymore,
2971
                        // so we must make sure we can recover on restart after
2972
                        // it is marked closed. If the next state transition
2973
                        // fails, we'll start up in the prior state again, and
2974
                        // we won't be longer getting chain events. In this
2975
                        // case we must manually re-trigger the state
2976
                        // transition into StateContractClosed based on the
2977
                        // close status of the channel.
2978
                        closeSummary := &uniClosure.ChannelCloseSummary
10✔
2979
                        err = c.cfg.MarkChannelClosed(
10✔
2980
                                closeSummary,
10✔
2981
                                channeldb.ChanStatusRemoteCloseInitiator,
10✔
2982
                        )
10✔
2983
                        if err != nil {
11✔
2984
                                log.Errorf("Unable to mark channel closed: %v",
1✔
2985
                                        err)
1✔
2986
                                return
1✔
2987
                        }
1✔
2988

2989
                        // We'll now advance our state machine until it reaches
2990
                        // a terminal state.
2991
                        _, _, err = c.advanceState(
9✔
2992
                                uint32(uniClosure.SpendingHeight),
9✔
2993
                                remoteCloseTrigger, &uniClosure.CommitSet,
9✔
2994
                        )
9✔
2995
                        if err != nil {
11✔
2996
                                log.Errorf("Unable to advance state: %v", err)
2✔
2997
                        }
2✔
2998

2999
                // The remote has breached the channel. As this is handled by
3000
                // the ChainWatcher and BreachArbitrator, we don't have to do
3001
                // anything in particular, so just advance our state and
3002
                // gracefully exit.
3003
                case breachInfo := <-c.cfg.ChainEvents.ContractBreach:
4✔
3004
                        log.Infof("ChannelArbitrator(%v): remote party has "+
4✔
3005
                                "breached channel!", c.cfg.ChanPoint)
4✔
3006

4✔
3007
                        // In the breach case, we'll only have anchor and
4✔
3008
                        // breach resolutions.
4✔
3009
                        contractRes := &ContractResolutions{
4✔
3010
                                CommitHash:       breachInfo.CommitHash,
4✔
3011
                                BreachResolution: breachInfo.BreachResolution,
4✔
3012
                                AnchorResolution: breachInfo.AnchorResolution,
4✔
3013
                        }
4✔
3014

4✔
3015
                        // We'll transition to the ContractClosed state and log
4✔
3016
                        // the set of resolutions such that they can be turned
4✔
3017
                        // into resolvers later on. We'll also insert the
4✔
3018
                        // CommitSet of the latest set of commitments.
4✔
3019
                        err := c.log.LogContractResolutions(contractRes)
4✔
3020
                        if err != nil {
4✔
3021
                                log.Errorf("Unable to write resolutions: %v",
×
3022
                                        err)
×
3023
                                return
×
3024
                        }
×
3025
                        err = c.log.InsertConfirmedCommitSet(
4✔
3026
                                &breachInfo.CommitSet,
4✔
3027
                        )
4✔
3028
                        if err != nil {
4✔
3029
                                log.Errorf("Unable to write commit set: %v",
×
3030
                                        err)
×
3031
                                return
×
3032
                        }
×
3033

3034
                        // The channel is finally marked pending closed here as
3035
                        // the BreachArbitrator and channel arbitrator have
3036
                        // persisted the relevant states.
3037
                        closeSummary := &breachInfo.CloseSummary
4✔
3038
                        err = c.cfg.MarkChannelClosed(
4✔
3039
                                closeSummary,
4✔
3040
                                channeldb.ChanStatusRemoteCloseInitiator,
4✔
3041
                        )
4✔
3042
                        if err != nil {
4✔
3043
                                log.Errorf("Unable to mark channel closed: %v",
×
3044
                                        err)
×
3045
                                return
×
3046
                        }
×
3047

3048
                        log.Infof("Breached channel=%v marked pending-closed",
4✔
3049
                                breachInfo.BreachResolution.FundingOutPoint)
4✔
3050

4✔
3051
                        // We'll advance our state machine until it reaches a
4✔
3052
                        // terminal state.
4✔
3053
                        _, _, err = c.advanceState(
4✔
3054
                                uint32(bestHeight), breachCloseTrigger,
4✔
3055
                                &breachInfo.CommitSet,
4✔
3056
                        )
4✔
3057
                        if err != nil {
4✔
3058
                                log.Errorf("Unable to advance state: %v", err)
×
3059
                        }
×
3060

3061
                // A new contract has just been resolved, we'll now check our
3062
                // log to see if all contracts have been resolved. If so, then
3063
                // we can exit as the contract is fully resolved.
3064
                case <-c.resolutionSignal:
7✔
3065
                        log.Infof("ChannelArbitrator(%v): a contract has been "+
7✔
3066
                                "fully resolved!", c.cfg.ChanPoint)
7✔
3067

7✔
3068
                        nextState, _, err := c.advanceState(
7✔
3069
                                uint32(bestHeight), chainTrigger, nil,
7✔
3070
                        )
7✔
3071
                        if err != nil {
7✔
3072
                                log.Errorf("Unable to advance state: %v", err)
×
3073
                        }
×
3074

3075
                        // If we don't have anything further to do after
3076
                        // advancing our state, then we'll exit.
3077
                        if nextState == StateFullyResolved {
10✔
3078
                                log.Infof("ChannelArbitrator(%v): all "+
3✔
3079
                                        "contracts fully resolved, exiting",
3✔
3080
                                        c.cfg.ChanPoint)
3✔
3081

3✔
3082
                                return
3✔
3083
                        }
3✔
3084

3085
                // We've just received a request to forcibly close out the
3086
                // channel. We'll
3087
                case closeReq := <-c.forceCloseReqs:
14✔
3088
                        log.Infof("ChannelArbitrator(%v): received force "+
14✔
3089
                                "close request", c.cfg.ChanPoint)
14✔
3090

14✔
3091
                        if c.state != StateDefault {
16✔
3092
                                select {
2✔
3093
                                case closeReq.closeTx <- nil:
2✔
3094
                                case <-c.quit:
×
3095
                                }
3096

3097
                                select {
2✔
3098
                                case closeReq.errResp <- errAlreadyForceClosed:
2✔
3099
                                case <-c.quit:
×
3100
                                }
3101

3102
                                continue
2✔
3103
                        }
3104

3105
                        nextState, closeTx, err := c.advanceState(
13✔
3106
                                uint32(bestHeight), userTrigger, nil,
13✔
3107
                        )
13✔
3108
                        if err != nil {
17✔
3109
                                log.Errorf("Unable to advance state: %v", err)
4✔
3110
                        }
4✔
3111

3112
                        select {
13✔
3113
                        case closeReq.closeTx <- closeTx:
13✔
3114
                        case <-c.quit:
×
3115
                                return
×
3116
                        }
3117

3118
                        select {
13✔
3119
                        case closeReq.errResp <- err:
13✔
3120
                        case <-c.quit:
×
3121
                                return
×
3122
                        }
3123

3124
                        // If we don't have anything further to do after
3125
                        // advancing our state, then we'll exit.
3126
                        if nextState == StateFullyResolved {
13✔
3127
                                log.Infof("ChannelArbitrator(%v): all "+
×
3128
                                        "contracts resolved, exiting",
×
3129
                                        c.cfg.ChanPoint)
×
3130
                                return
×
3131
                        }
×
3132

3133
                case <-c.quit:
33✔
3134
                        return
33✔
3135
                }
3136
        }
3137
}
3138

3139
// checkLegacyBreach returns StateFullyResolved if the channel was closed with
3140
// a breach transaction before the channel arbitrator launched its own breach
3141
// resolver. StateContractClosed is returned if this is a modern breach close
3142
// with a breach resolver. StateError is returned if the log lookup failed.
3143
func (c *ChannelArbitrator) checkLegacyBreach() (ArbitratorState, error) {
5✔
3144
        // A previous version of the channel arbitrator would make the breach
5✔
3145
        // close skip to StateFullyResolved. If there are no contract
5✔
3146
        // resolutions in the bolt arbitrator log, then this is an older breach
5✔
3147
        // close. Otherwise, if there are resolutions, the state should advance
5✔
3148
        // to StateContractClosed.
5✔
3149
        _, err := c.log.FetchContractResolutions()
5✔
3150
        if err == errNoResolutions {
5✔
3151
                // This is an older breach close still in the database.
×
3152
                return StateFullyResolved, nil
×
3153
        } else if err != nil {
5✔
3154
                return StateError, err
×
3155
        }
×
3156

3157
        // This is a modern breach close with resolvers.
3158
        return StateContractClosed, nil
5✔
3159
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc