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

lightningnetwork / lnd / 12203473065

06 Dec 2024 05:40PM UTC coverage: 58.983% (+0.01%) from 58.972%
12203473065

Pull #9313

github

aakselrod
temp: debug commit
Pull Request #9313: Reapply 8644 on 9260

36 of 72 new or added lines in 6 files covered. (50.0%)

55 existing lines in 18 files now uncovered.

134181 of 227492 relevant lines covered (58.98%)

19381.14 hits per line

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

83.07
/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/chainio"
18
        "github.com/lightningnetwork/lnd/channeldb"
19
        "github.com/lightningnetwork/lnd/fn"
20
        "github.com/lightningnetwork/lnd/graph/db/models"
21
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
22
        "github.com/lightningnetwork/lnd/input"
23
        "github.com/lightningnetwork/lnd/invoices"
24
        "github.com/lightningnetwork/lnd/kvdb"
25
        "github.com/lightningnetwork/lnd/labels"
26
        "github.com/lightningnetwork/lnd/lntypes"
27
        "github.com/lightningnetwork/lnd/lnutils"
28
        "github.com/lightningnetwork/lnd/lnwallet"
29
        "github.com/lightningnetwork/lnd/lnwire"
30
        "github.com/lightningnetwork/lnd/sweep"
31
)
32

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

182
        ChainArbitratorConfig
183
}
184

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

334
        // Embed the blockbeat consumer struct to get access to the method
335
        // `NotifyBlockProcessed` and the `BlockbeatChan`.
336
        chainio.BeatConsumer
337

338
        // startTimestamp is the time when this ChannelArbitrator was started.
339
        startTimestamp time.Time
340

341
        // log is a persistent log that the attendant will use to checkpoint
342
        // its next action, and the state of any unresolved contracts.
343
        log ArbitratorLog
344

345
        // activeHTLCs is the set of active incoming/outgoing HTLC's on all
346
        // currently valid commitment transactions.
347
        activeHTLCs map[HtlcSetKey]htlcSet
348

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

356
        // cfg contains all the functionality that the ChannelArbitrator requires
357
        // to do its duty.
358
        cfg ChannelArbitratorConfig
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 {
54✔
393

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

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

407
        c := &ChannelArbitrator{
54✔
408
                log:              log,
54✔
409
                signalUpdates:    make(chan *signalUpdateMsg),
54✔
410
                resolutionSignal: make(chan struct{}),
54✔
411
                forceCloseReqs:   make(chan *forceCloseReq),
54✔
412
                activeHTLCs:      htlcSets,
54✔
413
                unmergedSet:      unmerged,
54✔
414
                cfg:              cfg,
54✔
415
                quit:             make(chan struct{}),
54✔
416
        }
54✔
417

54✔
418
        // Mount the block consumer.
54✔
419
        c.BeatConsumer = chainio.NewBeatConsumer(c.quit, c.Name())
54✔
420

54✔
421
        return c
54✔
422
}
423

424
// Compile-time check for the chainio.Consumer interface.
425
var _ chainio.Consumer = (*ChannelArbitrator)(nil)
426

427
// chanArbStartState contains the information from disk that we need to start
428
// up a channel arbitrator.
429
type chanArbStartState struct {
430
        currentState ArbitratorState
431
        commitSet    *CommitSet
432
}
433

434
// getStartState retrieves the information from disk that our channel arbitrator
435
// requires to start.
436
func (c *ChannelArbitrator) getStartState(tx kvdb.RTx) (*chanArbStartState,
437
        error) {
51✔
438

51✔
439
        // First, we'll read our last state from disk, so our internal state
51✔
440
        // machine can act accordingly.
51✔
441
        state, err := c.log.CurrentState(tx)
51✔
442
        if err != nil {
51✔
443
                return nil, err
×
444
        }
×
445

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

456
        return &chanArbStartState{
51✔
457
                currentState: state,
51✔
458
                commitSet:    commitSet,
51✔
459
        }, nil
51✔
460
}
461

462
// Start starts all the goroutines that the ChannelArbitrator needs to operate.
463
// If takes a start state, which will be looked up on disk if it is not
464
// provided.
465
func (c *ChannelArbitrator) Start(state *chanArbStartState,
466
        beat chainio.Blockbeat) error {
51✔
467

51✔
468
        if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
51✔
469
                return nil
×
470
        }
×
471
        c.startTimestamp = c.cfg.Clock.Now()
51✔
472

51✔
473
        // If the state passed in is nil, we look it up now.
51✔
474
        if state == nil {
91✔
475
                var err error
40✔
476
                state, err = c.getStartState(nil)
40✔
477
                if err != nil {
40✔
478
                        return err
×
479
                }
×
480
        }
481

482
        log.Tracef("Starting ChannelArbitrator(%v), htlc_set=%v, state=%v",
51✔
483
                c.cfg.ChanPoint, lnutils.SpewLogClosure(c.activeHTLCs),
51✔
484
                state.currentState)
51✔
485

51✔
486
        // Set our state from our starting state.
51✔
487
        c.state = state.currentState
51✔
488

51✔
489
        // Get the starting height.
51✔
490
        bestHeight := beat.Height()
51✔
491

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

508
                        case channeldb.CooperativeClose:
1✔
509
                                trigger = coopCloseTrigger
1✔
510

511
                        case channeldb.BreachClose:
1✔
512
                                trigger = breachCloseTrigger
1✔
513

514
                        case channeldb.LocalForceClose:
1✔
515
                                trigger = localCloseTrigger
1✔
516

517
                        case channeldb.RemoteForceClose:
2✔
518
                                trigger = remoteCloseTrigger
2✔
519
                        }
520

521
                        log.Warnf("ChannelArbitrator(%v): detected stalled "+
5✔
522
                                "state=%v for closed channel",
5✔
523
                                c.cfg.ChanPoint, c.state)
5✔
524
                }
525

526
                triggerHeight = c.cfg.ClosingHeight
8✔
527
        }
528

529
        log.Infof("ChannelArbitrator(%v): starting state=%v, trigger=%v, "+
51✔
530
                "triggerHeight=%v", c.cfg.ChanPoint, c.state, trigger,
51✔
531
                triggerHeight)
51✔
532

51✔
533
        // We'll now attempt to advance our state forward based on the current
51✔
534
        // on-chain state, and our set of active contracts.
51✔
535
        startingState := c.state
51✔
536
        nextState, _, err := c.advanceState(
51✔
537
                triggerHeight, trigger, state.commitSet,
51✔
538
        )
51✔
539
        if err != nil {
53✔
540
                switch err {
2✔
541

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

553
                default:
1✔
554
                        return err
1✔
555
                }
556
        }
557

558
        // If we start and ended at the awaiting full resolution state, then
559
        // we'll relaunch our set of unresolved contracts.
560
        if startingState == StateWaitingFullResolution &&
50✔
561
                nextState == StateWaitingFullResolution {
54✔
562

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

580
        c.wg.Add(1)
50✔
581
        go c.channelAttendant(bestHeight)
50✔
582
        return nil
50✔
583
}
584

585
// maybeAugmentTaprootResolvers will update the contract resolution information
586
// for taproot channels. This ensures that all the resolvers have the latest
587
// resolution, which may also include data such as the control block and tap
588
// tweaks.
589
func maybeAugmentTaprootResolvers(chanType channeldb.ChannelType,
590
        resolver ContractResolver,
591
        contractResolutions *ContractResolutions) {
4✔
592

4✔
593
        if !chanType.IsTaproot() {
8✔
594
                return
4✔
595
        }
4✔
596

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

3✔
612
                        if r.htlcResolution.ClaimOutpoint ==
3✔
613
                                htlcRes.ClaimOutpoint {
6✔
614

3✔
615
                                r.htlcResolution = htlcRes
3✔
616
                        }
3✔
617
                }
618

619
        case *htlcTimeoutResolver:
3✔
620
                //nolint:ll
3✔
621
                htlcResolutions := contractResolutions.HtlcResolutions.OutgoingHTLCs
3✔
622
                for _, htlcRes := range htlcResolutions {
6✔
623
                        htlcRes := htlcRes
3✔
624

3✔
625
                        if r.htlcResolution.ClaimOutpoint ==
3✔
626
                                htlcRes.ClaimOutpoint {
6✔
627

3✔
628
                                r.htlcResolution = htlcRes
3✔
629
                        }
3✔
630
                }
631

632
        case *htlcIncomingContestResolver:
3✔
633
                //nolint:ll
3✔
634
                htlcResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs
3✔
635
                for _, htlcRes := range htlcResolutions {
6✔
636
                        htlcRes := htlcRes
3✔
637

3✔
638
                        if r.htlcResolution.ClaimOutpoint ==
3✔
639
                                htlcRes.ClaimOutpoint {
6✔
640

3✔
641
                                r.htlcResolution = htlcRes
3✔
642
                        }
3✔
643
                }
644
        case *htlcSuccessResolver:
×
645
                //nolint:ll
×
646
                htlcResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs
×
647
                for _, htlcRes := range htlcResolutions {
×
648
                        htlcRes := htlcRes
×
649

×
650
                        if r.htlcResolution.ClaimOutpoint ==
×
651
                                htlcRes.ClaimOutpoint {
×
652

×
653
                                r.htlcResolution = htlcRes
×
654
                        }
×
655
                }
656
        }
657
}
658

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

4✔
667
        // We'll now query our log to see if there are any active unresolved
4✔
668
        // contracts. If this is the case, then we'll relaunch all contract
4✔
669
        // resolvers.
4✔
670
        unresolvedContracts, err := c.log.FetchUnresolvedContracts()
4✔
671
        if err != nil {
4✔
672
                return err
×
673
        }
×
674

675
        // Retrieve the commitment tx hash from the log.
676
        contractResolutions, err := c.log.FetchContractResolutions()
4✔
677
        if err != nil {
4✔
678
                log.Errorf("unable to fetch contract resolutions: %v",
×
679
                        err)
×
680
                return err
×
681
        }
×
682
        commitHash := contractResolutions.CommitHash
4✔
683

4✔
684
        // In prior versions of lnd, the information needed to supplement the
4✔
685
        // resolvers (in most cases, the full amount of the HTLC) was found in
4✔
686
        // the chain action map, which is now deprecated.  As a result, if the
4✔
687
        // commitSet is nil (an older node with unresolved HTLCs at time of
4✔
688
        // upgrade), then we'll use the chain action information in place. The
4✔
689
        // chain actions may exclude some information, but we cannot recover it
4✔
690
        // for these older nodes at the moment.
4✔
691
        var confirmedHTLCs []channeldb.HTLC
4✔
692
        if commitSet != nil && commitSet.ConfCommitKey.IsSome() {
8✔
693
                confCommitKey, err := commitSet.ConfCommitKey.UnwrapOrErr(
4✔
694
                        fmt.Errorf("no commitKey available"),
4✔
695
                )
4✔
696
                if err != nil {
4✔
697
                        return err
×
698
                }
×
699
                confirmedHTLCs = commitSet.HtlcSets[confCommitKey]
4✔
700
        } else {
×
701
                chainActions, err := c.log.FetchChainActions()
×
702
                if err != nil {
×
703
                        log.Errorf("unable to fetch chain actions: %v", err)
×
704
                        return err
×
705
                }
×
706
                for _, htlcs := range chainActions {
×
707
                        confirmedHTLCs = append(confirmedHTLCs, htlcs...)
×
708
                }
×
709
        }
710

711
        // Reconstruct the htlc outpoints and data from the chain action log.
712
        // The purpose of the constructed htlc map is to supplement to
713
        // resolvers restored from database with extra data. Ideally this data
714
        // is stored as part of the resolver in the log. This is a workaround
715
        // to prevent a db migration. We use all available htlc sets here in
716
        // order to ensure we have complete coverage.
717
        htlcMap := make(map[wire.OutPoint]*channeldb.HTLC)
4✔
718
        for _, htlc := range confirmedHTLCs {
10✔
719
                htlc := htlc
6✔
720
                outpoint := wire.OutPoint{
6✔
721
                        Hash:  commitHash,
6✔
722
                        Index: uint32(htlc.OutputIndex),
6✔
723
                }
6✔
724
                htlcMap[outpoint] = &htlc
6✔
725
        }
6✔
726

727
        // We'll also fetch the historical state of this channel, as it should
728
        // have been marked as closed by now, and supplement it to each resolver
729
        // such that we can properly resolve our pending contracts.
730
        var chanState *channeldb.OpenChannel
4✔
731
        chanState, err = c.cfg.FetchHistoricalChannel()
4✔
732
        switch {
4✔
733
        // If we don't find this channel, then it may be the case that it
734
        // was closed before we started to retain the final state
735
        // information for open channels.
736
        case err == channeldb.ErrNoHistoricalBucket:
×
737
                fallthrough
×
738
        case err == channeldb.ErrChannelNotFound:
×
739
                log.Warnf("ChannelArbitrator(%v): unable to fetch historical "+
×
740
                        "state", c.cfg.ChanPoint)
×
741

742
        case err != nil:
×
743
                return err
×
744
        }
745

746
        log.Infof("ChannelArbitrator(%v): relaunching %v contract "+
4✔
747
                "resolvers", c.cfg.ChanPoint, len(unresolvedContracts))
4✔
748

4✔
749
        for i := range unresolvedContracts {
8✔
750
                resolver := unresolvedContracts[i]
4✔
751

4✔
752
                if chanState != nil {
8✔
753
                        resolver.SupplementState(chanState)
4✔
754

4✔
755
                        // For taproot channels, we'll need to also make sure
4✔
756
                        // the control block information was set properly.
4✔
757
                        maybeAugmentTaprootResolvers(
4✔
758
                                chanState.ChanType, resolver,
4✔
759
                                contractResolutions,
4✔
760
                        )
4✔
761
                }
4✔
762

763
                unresolvedContracts[i] = resolver
4✔
764

4✔
765
                htlcResolver, ok := resolver.(htlcContractResolver)
4✔
766
                if !ok {
7✔
767
                        continue
3✔
768
                }
769

770
                htlcPoint := htlcResolver.HtlcPoint()
4✔
771
                htlc, ok := htlcMap[htlcPoint]
4✔
772
                if !ok {
4✔
773
                        return fmt.Errorf(
×
774
                                "htlc resolver %T unavailable", resolver,
×
775
                        )
×
776
                }
×
777

778
                htlcResolver.Supplement(*htlc)
4✔
779

4✔
780
                // If this is an outgoing HTLC, we will also need to supplement
4✔
781
                // the resolver with the expiry block height of its
4✔
782
                // corresponding incoming HTLC.
4✔
783
                if !htlc.Incoming {
8✔
784
                        deadline := c.cfg.FindOutgoingHTLCDeadline(*htlc)
4✔
785
                        htlcResolver.SupplementDeadline(deadline)
4✔
786
                }
4✔
787
        }
788

789
        // The anchor resolver is stateless and can always be re-instantiated.
790
        if contractResolutions.AnchorResolution != nil {
7✔
791
                anchorResolver := newAnchorResolver(
3✔
792
                        contractResolutions.AnchorResolution.AnchorSignDescriptor,
3✔
793
                        contractResolutions.AnchorResolution.CommitAnchor,
3✔
794
                        heightHint, c.cfg.ChanPoint,
3✔
795
                        ResolverConfig{
3✔
796
                                ChannelArbitratorConfig: c.cfg,
3✔
797
                        },
3✔
798
                )
3✔
799

3✔
800
                anchorResolver.SupplementState(chanState)
3✔
801

3✔
802
                unresolvedContracts = append(unresolvedContracts, anchorResolver)
3✔
803

3✔
804
                // TODO(roasbeef): this isn't re-launched?
3✔
805
        }
3✔
806

807
        c.resolveContracts(unresolvedContracts)
4✔
808

4✔
809
        return nil
4✔
810
}
811

812
// Report returns htlc reports for the active resolvers.
813
func (c *ChannelArbitrator) Report() []*ContractReport {
3✔
814
        c.activeResolversLock.RLock()
3✔
815
        defer c.activeResolversLock.RUnlock()
3✔
816

3✔
817
        var reports []*ContractReport
3✔
818
        for _, resolver := range c.activeResolvers {
6✔
819
                r, ok := resolver.(reportingContractResolver)
3✔
820
                if !ok {
3✔
821
                        continue
×
822
                }
823

824
                report := r.report()
3✔
825
                if report == nil {
6✔
826
                        continue
3✔
827
                }
828

829
                reports = append(reports, report)
3✔
830
        }
831

832
        return reports
3✔
833
}
834

835
// Stop signals the ChannelArbitrator for a graceful shutdown.
836
func (c *ChannelArbitrator) Stop() error {
53✔
837
        if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
59✔
838
                return nil
6✔
839
        }
6✔
840

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

47✔
843
        if c.cfg.ChainEvents.Cancel != nil {
61✔
844
                go c.cfg.ChainEvents.Cancel()
14✔
845
        }
14✔
846

847
        c.activeResolversLock.RLock()
47✔
848
        for _, activeResolver := range c.activeResolvers {
56✔
849
                activeResolver.Stop()
9✔
850
        }
9✔
851
        c.activeResolversLock.RUnlock()
47✔
852

47✔
853
        close(c.quit)
47✔
854
        c.wg.Wait()
47✔
855

47✔
856
        return nil
47✔
857
}
858

859
// transitionTrigger is an enum that denotes exactly *why* a state transition
860
// was initiated. This is useful as depending on the initial trigger, we may
861
// skip certain states as those actions are expected to have already taken
862
// place as a result of the external trigger.
863
type transitionTrigger uint8
864

865
const (
866
        // chainTrigger is a transition trigger that has been attempted due to
867
        // changing on-chain conditions such as a block which times out HTLC's
868
        // being attached.
869
        chainTrigger transitionTrigger = iota
870

871
        // userTrigger is a transition trigger driven by user action. Examples
872
        // of such a trigger include a user requesting a force closure of the
873
        // channel.
874
        userTrigger
875

876
        // remoteCloseTrigger is a transition trigger driven by the remote
877
        // peer's commitment being confirmed.
878
        remoteCloseTrigger
879

880
        // localCloseTrigger is a transition trigger driven by our commitment
881
        // being confirmed.
882
        localCloseTrigger
883

884
        // coopCloseTrigger is a transition trigger driven by a cooperative
885
        // close transaction being confirmed.
886
        coopCloseTrigger
887

888
        // breachCloseTrigger is a transition trigger driven by a remote breach
889
        // being confirmed. In this case the channel arbitrator will wait for
890
        // the BreachArbitrator to finish and then clean up gracefully.
891
        breachCloseTrigger
892
)
893

894
// String returns a human readable string describing the passed
895
// transitionTrigger.
896
func (t transitionTrigger) String() string {
3✔
897
        switch t {
3✔
898
        case chainTrigger:
3✔
899
                return "chainTrigger"
3✔
900

901
        case remoteCloseTrigger:
3✔
902
                return "remoteCloseTrigger"
3✔
903

904
        case userTrigger:
3✔
905
                return "userTrigger"
3✔
906

907
        case localCloseTrigger:
3✔
908
                return "localCloseTrigger"
3✔
909

910
        case coopCloseTrigger:
3✔
911
                return "coopCloseTrigger"
3✔
912

913
        case breachCloseTrigger:
3✔
914
                return "breachCloseTrigger"
3✔
915

916
        default:
×
917
                return "unknown trigger"
×
918
        }
919
}
920

921
// stateStep is a help method that examines our internal state, and attempts
922
// the appropriate state transition if necessary. The next state we transition
923
// to is returned, Additionally, if the next transition results in a commitment
924
// broadcast, the commitment transaction itself is returned.
925
func (c *ChannelArbitrator) stateStep(
926
        triggerHeight uint32, trigger transitionTrigger,
927
        confCommitSet *CommitSet) (ArbitratorState, *wire.MsgTx, error) {
177✔
928

177✔
929
        var (
177✔
930
                nextState ArbitratorState
177✔
931
                closeTx   *wire.MsgTx
177✔
932
        )
177✔
933
        switch c.state {
177✔
934

935
        // If we're in the default state, then we'll check our set of actions
936
        // to see if while we were down, conditions have changed.
937
        case StateDefault:
66✔
938
                log.Debugf("ChannelArbitrator(%v): new block (height=%v) "+
66✔
939
                        "examining active HTLC's", c.cfg.ChanPoint,
66✔
940
                        triggerHeight)
66✔
941

66✔
942
                // As a new block has been connected to the end of the main
66✔
943
                // chain, we'll check to see if we need to make any on-chain
66✔
944
                // claims on behalf of the channel contract that we're
66✔
945
                // arbitrating for. If a commitment has confirmed, then we'll
66✔
946
                // use the set snapshot from the chain, otherwise we'll use our
66✔
947
                // current set.
66✔
948
                var (
66✔
949
                        chainActions ChainActionMap
66✔
950
                        err          error
66✔
951
                )
66✔
952

66✔
953
                // Normally if we force close the channel locally we will have
66✔
954
                // no confCommitSet. However when the remote commitment confirms
66✔
955
                // without us ever broadcasting our local commitment we need to
66✔
956
                // make sure we cancel all upstream HTLCs for outgoing dust
66✔
957
                // HTLCs as well hence we need to fetch the chain actions here
66✔
958
                // as well.
66✔
959
                if confCommitSet == nil {
123✔
960
                        // Update the set of activeHTLCs so
57✔
961
                        // checkLocalChainActions has an up-to-date view of the
57✔
962
                        // commitments.
57✔
963
                        c.updateActiveHTLCs()
57✔
964
                        htlcs := c.activeHTLCs
57✔
965
                        chainActions, err = c.checkLocalChainActions(
57✔
966
                                triggerHeight, trigger, htlcs, false,
57✔
967
                        )
57✔
968
                        if err != nil {
57✔
969
                                return StateDefault, nil, err
×
970
                        }
×
971
                } else {
12✔
972
                        chainActions, err = c.constructChainActions(
12✔
973
                                confCommitSet, triggerHeight, trigger,
12✔
974
                        )
12✔
975
                        if err != nil {
12✔
976
                                return StateDefault, nil, err
×
977
                        }
×
978
                }
979

980
                // If there are no actions to be made, then we'll remain in the
981
                // default state. If this isn't a self initiated event (we're
982
                // checking due to a chain update), then we'll exit now.
983
                if len(chainActions) == 0 && trigger == chainTrigger {
105✔
984
                        log.Debugf("ChannelArbitrator(%v): no actions for "+
39✔
985
                                "chain trigger, terminating", c.cfg.ChanPoint)
39✔
986

39✔
987
                        return StateDefault, closeTx, nil
39✔
988
                }
39✔
989

990
                // Otherwise, we'll log that we checked the HTLC actions as the
991
                // commitment transaction has already been broadcast.
992
                log.Tracef("ChannelArbitrator(%v): logging chain_actions=%v",
30✔
993
                        c.cfg.ChanPoint, lnutils.SpewLogClosure(chainActions))
30✔
994

30✔
995
                // Cancel upstream HTLCs for all outgoing dust HTLCs available
30✔
996
                // either on the local or the remote/remote pending commitment
30✔
997
                // transaction.
30✔
998
                dustHTLCs := chainActions[HtlcFailDustAction]
30✔
999
                if len(dustHTLCs) > 0 {
34✔
1000
                        log.Debugf("ChannelArbitrator(%v): canceling %v dust "+
4✔
1001
                                "HTLCs backwards", c.cfg.ChanPoint,
4✔
1002
                                len(dustHTLCs))
4✔
1003

4✔
1004
                        getIdx := func(htlc channeldb.HTLC) uint64 {
8✔
1005
                                return htlc.HtlcIndex
4✔
1006
                        }
4✔
1007
                        dustHTLCSet := fn.NewSet(fn.Map(getIdx, dustHTLCs)...)
4✔
1008
                        err = c.abandonForwards(dustHTLCSet)
4✔
1009
                        if err != nil {
4✔
1010
                                return StateError, closeTx, err
×
1011
                        }
×
1012
                }
1013

1014
                // Depending on the type of trigger, we'll either "tunnel"
1015
                // through to a farther state, or just proceed linearly to the
1016
                // next state.
1017
                switch trigger {
30✔
1018

1019
                // If this is a chain trigger, then we'll go straight to the
1020
                // next state, as we still need to broadcast the commitment
1021
                // transaction.
1022
                case chainTrigger:
8✔
1023
                        fallthrough
8✔
1024
                case userTrigger:
18✔
1025
                        nextState = StateBroadcastCommit
18✔
1026

1027
                // If the trigger is a cooperative close being confirmed, then
1028
                // we can go straight to StateFullyResolved, as there won't be
1029
                // any contracts to resolve.
1030
                case coopCloseTrigger:
6✔
1031
                        nextState = StateFullyResolved
6✔
1032

1033
                // Otherwise, if this state advance was triggered by a
1034
                // commitment being confirmed on chain, then we'll jump
1035
                // straight to the state where the contract has already been
1036
                // closed, and we will inspect the set of unresolved contracts.
1037
                case localCloseTrigger:
5✔
1038
                        log.Errorf("ChannelArbitrator(%v): unexpected local "+
5✔
1039
                                "commitment confirmed while in StateDefault",
5✔
1040
                                c.cfg.ChanPoint)
5✔
1041
                        fallthrough
5✔
1042
                case remoteCloseTrigger:
11✔
1043
                        nextState = StateContractClosed
11✔
1044

1045
                case breachCloseTrigger:
4✔
1046
                        nextContractState, err := c.checkLegacyBreach()
4✔
1047
                        if nextContractState == StateError {
4✔
1048
                                return nextContractState, nil, err
×
1049
                        }
×
1050

1051
                        nextState = nextContractState
4✔
1052
                }
1053

1054
        // If we're in this state, then we've decided to broadcast the
1055
        // commitment transaction. We enter this state either due to an outside
1056
        // sub-system, or because an on-chain action has been triggered.
1057
        case StateBroadcastCommit:
23✔
1058
                // Under normal operation, we can only enter
23✔
1059
                // StateBroadcastCommit via a user or chain trigger. On restart,
23✔
1060
                // this state may be reexecuted after closing the channel, but
23✔
1061
                // failing to commit to StateContractClosed or
23✔
1062
                // StateFullyResolved. In that case, one of the four close
23✔
1063
                // triggers will be presented, signifying that we should skip
23✔
1064
                // rebroadcasting, and go straight to resolving the on-chain
23✔
1065
                // contract or marking the channel resolved.
23✔
1066
                switch trigger {
23✔
1067
                case localCloseTrigger, remoteCloseTrigger:
×
1068
                        log.Infof("ChannelArbitrator(%v): detected %s "+
×
1069
                                "close after closing channel, fast-forwarding "+
×
1070
                                "to %s to resolve contract",
×
1071
                                c.cfg.ChanPoint, trigger, StateContractClosed)
×
1072
                        return StateContractClosed, closeTx, nil
×
1073

1074
                case breachCloseTrigger:
4✔
1075
                        nextContractState, err := c.checkLegacyBreach()
4✔
1076
                        if nextContractState == StateError {
4✔
1077
                                log.Infof("ChannelArbitrator(%v): unable to "+
×
1078
                                        "advance breach close resolution: %v",
×
1079
                                        c.cfg.ChanPoint, nextContractState)
×
1080
                                return StateError, closeTx, err
×
1081
                        }
×
1082

1083
                        log.Infof("ChannelArbitrator(%v): detected %s close "+
4✔
1084
                                "after closing channel, fast-forwarding to %s"+
4✔
1085
                                " to resolve contract", c.cfg.ChanPoint,
4✔
1086
                                trigger, nextContractState)
4✔
1087

4✔
1088
                        return nextContractState, closeTx, nil
4✔
1089

1090
                case coopCloseTrigger:
×
1091
                        log.Infof("ChannelArbitrator(%v): detected %s "+
×
1092
                                "close after closing channel, fast-forwarding "+
×
1093
                                "to %s to resolve contract",
×
1094
                                c.cfg.ChanPoint, trigger, StateFullyResolved)
×
1095
                        return StateFullyResolved, closeTx, nil
×
1096
                }
1097

1098
                log.Infof("ChannelArbitrator(%v): force closing "+
22✔
1099
                        "chan", c.cfg.ChanPoint)
22✔
1100

22✔
1101
                // Now that we have all the actions decided for the set of
22✔
1102
                // HTLC's, we'll broadcast the commitment transaction, and
22✔
1103
                // signal the link to exit.
22✔
1104

22✔
1105
                // We'll tell the switch that it should remove the link for
22✔
1106
                // this channel, in addition to fetching the force close
22✔
1107
                // summary needed to close this channel on chain.
22✔
1108
                forceCloseTx, err := c.cfg.Channel.ForceCloseChan()
22✔
1109
                if err != nil {
23✔
1110
                        log.Errorf("ChannelArbitrator(%v): unable to "+
1✔
1111
                                "force close: %v", c.cfg.ChanPoint, err)
1✔
1112

1✔
1113
                        // We tried to force close (HTLC may be expiring from
1✔
1114
                        // our PoV, etc), but we think we've lost data. In this
1✔
1115
                        // case, we'll not force close, but terminate the state
1✔
1116
                        // machine here to wait to see what confirms on chain.
1✔
1117
                        if errors.Is(err, lnwallet.ErrForceCloseLocalDataLoss) {
2✔
1118
                                log.Error("ChannelArbitrator(%v): broadcast "+
1✔
1119
                                        "failed due to local data loss, "+
1✔
1120
                                        "waiting for on chain confimation...",
1✔
1121
                                        c.cfg.ChanPoint)
1✔
1122

1✔
1123
                                return StateBroadcastCommit, nil, nil
1✔
1124
                        }
1✔
1125

1126
                        return StateError, closeTx, err
×
1127
                }
1128
                closeTx = forceCloseTx
21✔
1129

21✔
1130
                // Before publishing the transaction, we store it to the
21✔
1131
                // database, such that we can re-publish later in case it
21✔
1132
                // didn't propagate. We initiated the force close, so we
21✔
1133
                // mark broadcast with local initiator set to true.
21✔
1134
                err = c.cfg.MarkCommitmentBroadcasted(closeTx, lntypes.Local)
21✔
1135
                if err != nil {
21✔
1136
                        log.Errorf("ChannelArbitrator(%v): unable to "+
×
1137
                                "mark commitment broadcasted: %v",
×
1138
                                c.cfg.ChanPoint, err)
×
1139
                        return StateError, closeTx, err
×
1140
                }
×
1141

1142
                // With the close transaction in hand, broadcast the
1143
                // transaction to the network, thereby entering the post
1144
                // channel resolution state.
1145
                log.Infof("Broadcasting force close transaction %v, "+
21✔
1146
                        "ChannelPoint(%v): %v", closeTx.TxHash(),
21✔
1147
                        c.cfg.ChanPoint, lnutils.SpewLogClosure(closeTx))
21✔
1148

21✔
1149
                // At this point, we'll now broadcast the commitment
21✔
1150
                // transaction itself.
21✔
1151
                label := labels.MakeLabel(
21✔
1152
                        labels.LabelTypeChannelClose, &c.cfg.ShortChanID,
21✔
1153
                )
21✔
1154
                if err := c.cfg.PublishTx(closeTx, label); err != nil {
29✔
1155
                        log.Errorf("ChannelArbitrator(%v): unable to broadcast "+
8✔
1156
                                "close tx: %v", c.cfg.ChanPoint, err)
8✔
1157

8✔
1158
                        // This makes sure we don't fail at startup if the
8✔
1159
                        // commitment transaction has too low fees to make it
8✔
1160
                        // into mempool. The rebroadcaster makes sure this
8✔
1161
                        // transaction is republished regularly until confirmed
8✔
1162
                        // or replaced.
8✔
1163
                        if !errors.Is(err, lnwallet.ErrDoubleSpend) &&
8✔
1164
                                !errors.Is(err, lnwallet.ErrMempoolFee) {
13✔
1165

5✔
1166
                                return StateError, closeTx, err
5✔
1167
                        }
5✔
1168
                }
1169

1170
                // We go to the StateCommitmentBroadcasted state, where we'll
1171
                // be waiting for the commitment to be confirmed.
1172
                nextState = StateCommitmentBroadcasted
19✔
1173

1174
        // In this state we have broadcasted our own commitment, and will need
1175
        // to wait for a commitment (not necessarily the one we broadcasted!)
1176
        // to be confirmed.
1177
        case StateCommitmentBroadcasted:
33✔
1178
                switch trigger {
33✔
1179

1180
                // We are waiting for a commitment to be confirmed.
1181
                case chainTrigger, userTrigger:
20✔
1182
                        // The commitment transaction has been broadcast, but it
20✔
1183
                        // doesn't necessarily need to be the commitment
20✔
1184
                        // transaction version that is going to be confirmed. To
20✔
1185
                        // be sure that any of those versions can be anchored
20✔
1186
                        // down, we now submit all anchor resolutions to the
20✔
1187
                        // sweeper. The sweeper will keep trying to sweep all of
20✔
1188
                        // them.
20✔
1189
                        //
20✔
1190
                        // Note that the sweeper is idempotent. If we ever
20✔
1191
                        // happen to end up at this point in the code again, no
20✔
1192
                        // harm is done by re-offering the anchors to the
20✔
1193
                        // sweeper.
20✔
1194
                        anchors, err := c.cfg.Channel.NewAnchorResolutions()
20✔
1195
                        if err != nil {
20✔
1196
                                return StateError, closeTx, err
×
1197
                        }
×
1198

1199
                        err = c.sweepAnchors(anchors, triggerHeight)
20✔
1200
                        if err != nil {
20✔
1201
                                return StateError, closeTx, err
×
1202
                        }
×
1203

1204
                        nextState = StateCommitmentBroadcasted
20✔
1205

1206
                // If this state advance was triggered by any of the
1207
                // commitments being confirmed, then we'll jump to the state
1208
                // where the contract has been closed.
1209
                case localCloseTrigger, remoteCloseTrigger:
16✔
1210
                        nextState = StateContractClosed
16✔
1211

1212
                // If a coop close was confirmed, jump straight to the fully
1213
                // resolved state.
1214
                case coopCloseTrigger:
×
1215
                        nextState = StateFullyResolved
×
1216

1217
                case breachCloseTrigger:
×
1218
                        nextContractState, err := c.checkLegacyBreach()
×
1219
                        if nextContractState == StateError {
×
1220
                                return nextContractState, closeTx, err
×
1221
                        }
×
1222

1223
                        nextState = nextContractState
×
1224
                }
1225

1226
                log.Infof("ChannelArbitrator(%v): trigger %v moving from "+
33✔
1227
                        "state %v to %v", c.cfg.ChanPoint, trigger, c.state,
33✔
1228
                        nextState)
33✔
1229

1230
        // If we're in this state, then the contract has been fully closed to
1231
        // outside sub-systems, so we'll process the prior set of on-chain
1232
        // contract actions and launch a set of resolvers.
1233
        case StateContractClosed:
25✔
1234
                // First, we'll fetch our chain actions, and both sets of
25✔
1235
                // resolutions so we can process them.
25✔
1236
                contractResolutions, err := c.log.FetchContractResolutions()
25✔
1237
                if err != nil {
27✔
1238
                        log.Errorf("unable to fetch contract resolutions: %v",
2✔
1239
                                err)
2✔
1240
                        return StateError, closeTx, err
2✔
1241
                }
2✔
1242

1243
                // If the resolution is empty, and we have no HTLCs at all to
1244
                // send to, then we're done here. We don't need to launch any
1245
                // resolvers, and can go straight to our final state.
1246
                if contractResolutions.IsEmpty() && confCommitSet.IsEmpty() {
34✔
1247
                        log.Infof("ChannelArbitrator(%v): contract "+
11✔
1248
                                "resolutions empty, marking channel as fully resolved!",
11✔
1249
                                c.cfg.ChanPoint)
11✔
1250
                        nextState = StateFullyResolved
11✔
1251
                        break
11✔
1252
                }
1253

1254
                // First, we'll reconstruct a fresh set of chain actions as the
1255
                // set of actions we need to act on may differ based on if it
1256
                // was our commitment, or they're commitment that hit the chain.
1257
                htlcActions, err := c.constructChainActions(
15✔
1258
                        confCommitSet, triggerHeight, trigger,
15✔
1259
                )
15✔
1260
                if err != nil {
15✔
1261
                        return StateError, closeTx, err
×
1262
                }
×
1263

1264
                // In case its a breach transaction we fail back all upstream
1265
                // HTLCs for their corresponding outgoing HTLCs on the remote
1266
                // commitment set (remote and remote pending set).
1267
                if contractResolutions.BreachResolution != nil {
20✔
1268
                        // cancelBreachedHTLCs is a set which holds HTLCs whose
5✔
1269
                        // corresponding incoming HTLCs will be failed back
5✔
1270
                        // because the peer broadcasted an old state.
5✔
1271
                        cancelBreachedHTLCs := fn.NewSet[uint64]()
5✔
1272

5✔
1273
                        // We'll use the CommitSet, we'll fail back all
5✔
1274
                        // upstream HTLCs for their corresponding outgoing
5✔
1275
                        // HTLC that exist on either of the remote commitments.
5✔
1276
                        // The map is used to deduplicate any shared HTLC's.
5✔
1277
                        for htlcSetKey, htlcs := range confCommitSet.HtlcSets {
10✔
1278
                                if !htlcSetKey.IsRemote {
8✔
1279
                                        continue
3✔
1280
                                }
1281

1282
                                for _, htlc := range htlcs {
10✔
1283
                                        // Only outgoing HTLCs have a
5✔
1284
                                        // corresponding incoming HTLC.
5✔
1285
                                        if htlc.Incoming {
9✔
1286
                                                continue
4✔
1287
                                        }
1288

1289
                                        cancelBreachedHTLCs.Add(htlc.HtlcIndex)
4✔
1290
                                }
1291
                        }
1292

1293
                        err := c.abandonForwards(cancelBreachedHTLCs)
5✔
1294
                        if err != nil {
5✔
1295
                                return StateError, closeTx, err
×
1296
                        }
×
1297
                } else {
13✔
1298
                        // If it's not a breach, we resolve all incoming dust
13✔
1299
                        // HTLCs immediately after the commitment is confirmed.
13✔
1300
                        err = c.failIncomingDust(
13✔
1301
                                htlcActions[HtlcIncomingDustFinalAction],
13✔
1302
                        )
13✔
1303
                        if err != nil {
13✔
1304
                                return StateError, closeTx, err
×
1305
                        }
×
1306

1307
                        // We fail the upstream HTLCs for all remote pending
1308
                        // outgoing HTLCs as soon as the commitment is
1309
                        // confirmed. The upstream HTLCs for outgoing dust
1310
                        // HTLCs have already been resolved before we reach
1311
                        // this point.
1312
                        getIdx := func(htlc channeldb.HTLC) uint64 {
24✔
1313
                                return htlc.HtlcIndex
11✔
1314
                        }
11✔
1315
                        remoteDangling := fn.NewSet(fn.Map(
13✔
1316
                                getIdx, htlcActions[HtlcFailDanglingAction],
13✔
1317
                        )...)
13✔
1318
                        err := c.abandonForwards(remoteDangling)
13✔
1319
                        if err != nil {
13✔
1320
                                return StateError, closeTx, err
×
1321
                        }
×
1322
                }
1323

1324
                // Now that we know we'll need to act, we'll process all the
1325
                // resolvers, then create the structures we need to resolve all
1326
                // outstanding contracts.
1327
                resolvers, err := c.prepContractResolutions(
15✔
1328
                        contractResolutions, triggerHeight, htlcActions,
15✔
1329
                )
15✔
1330
                if err != nil {
15✔
1331
                        log.Errorf("ChannelArbitrator(%v): unable to "+
×
1332
                                "resolve contracts: %v", c.cfg.ChanPoint, err)
×
1333
                        return StateError, closeTx, err
×
1334
                }
×
1335

1336
                log.Debugf("ChannelArbitrator(%v): inserting %v contract "+
15✔
1337
                        "resolvers", c.cfg.ChanPoint, len(resolvers))
15✔
1338

15✔
1339
                err = c.log.InsertUnresolvedContracts(nil, resolvers...)
15✔
1340
                if err != nil {
15✔
1341
                        return StateError, closeTx, err
×
1342
                }
×
1343

1344
                // Finally, we'll launch all the required contract resolvers.
1345
                // Once they're all resolved, we're no longer needed.
1346
                c.resolveContracts(resolvers)
15✔
1347

15✔
1348
                nextState = StateWaitingFullResolution
15✔
1349

1350
        // This is our terminal state. We'll keep returning this state until
1351
        // all contracts are fully resolved.
1352
        case StateWaitingFullResolution:
20✔
1353
                log.Infof("ChannelArbitrator(%v): still awaiting contract "+
20✔
1354
                        "resolution", c.cfg.ChanPoint)
20✔
1355

20✔
1356
                unresolved, err := c.log.FetchUnresolvedContracts()
20✔
1357
                if err != nil {
20✔
1358
                        return StateError, closeTx, err
×
1359
                }
×
1360

1361
                // If we have no unresolved contracts, then we can move to the
1362
                // final state.
1363
                if len(unresolved) == 0 {
35✔
1364
                        nextState = StateFullyResolved
15✔
1365
                        break
15✔
1366
                }
1367

1368
                // Otherwise we still have unresolved contracts, then we'll
1369
                // stay alive to oversee their resolution.
1370
                nextState = StateWaitingFullResolution
8✔
1371

8✔
1372
                // Add debug logs.
8✔
1373
                for _, r := range unresolved {
16✔
1374
                        log.Debugf("ChannelArbitrator(%v): still have "+
8✔
1375
                                "unresolved contract: %T", c.cfg.ChanPoint, r)
8✔
1376
                }
8✔
1377

1378
        // If we start as fully resolved, then we'll end as fully resolved.
1379
        case StateFullyResolved:
25✔
1380
                // To ensure that the state of the contract in persistent
25✔
1381
                // storage is properly reflected, we'll mark the contract as
25✔
1382
                // fully resolved now.
25✔
1383
                nextState = StateFullyResolved
25✔
1384

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

25✔
1388
                if err := c.cfg.MarkChannelResolved(); err != nil {
25✔
1389
                        log.Errorf("unable to mark channel resolved: %v", err)
×
1390
                        return StateError, closeTx, err
×
1391
                }
×
1392
        }
1393

1394
        log.Tracef("ChannelArbitrator(%v): next_state=%v", c.cfg.ChanPoint,
135✔
1395
                nextState)
135✔
1396

135✔
1397
        return nextState, closeTx, nil
135✔
1398
}
1399

1400
// sweepAnchors offers all given anchor resolutions to the sweeper. It requests
1401
// sweeping at the minimum fee rate. This fee rate can be upped manually by the
1402
// user via the BumpFee rpc.
1403
func (c *ChannelArbitrator) sweepAnchors(anchors *lnwallet.AnchorResolutions,
1404
        heightHint uint32) error {
22✔
1405

22✔
1406
        // Update the set of activeHTLCs so that the sweeping routine has an
22✔
1407
        // up-to-date view of the set of commitments.
22✔
1408
        c.updateActiveHTLCs()
22✔
1409

22✔
1410
        // Prepare the sweeping requests for all possible versions of
22✔
1411
        // commitments.
22✔
1412
        sweepReqs, err := c.prepareAnchorSweeps(heightHint, anchors)
22✔
1413
        if err != nil {
22✔
1414
                return err
×
1415
        }
×
1416

1417
        // Send out the sweeping requests to the sweeper.
1418
        for _, req := range sweepReqs {
33✔
1419
                _, err = c.cfg.Sweeper.SweepInput(req.input, req.params)
11✔
1420
                if err != nil {
11✔
1421
                        return err
×
1422
                }
×
1423
        }
1424

1425
        return nil
22✔
1426
}
1427

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

16✔
1450
        deadlineMinHeight := uint32(math.MaxUint32)
16✔
1451
        totalValue := btcutil.Amount(0)
16✔
1452

16✔
1453
        // First, iterate through the outgoingHTLCs to find the lowest CLTV
16✔
1454
        // value.
16✔
1455
        for _, htlc := range htlcs.outgoingHTLCs {
29✔
1456
                // Skip if the HTLC is dust.
13✔
1457
                if htlc.OutputIndex < 0 {
19✔
1458
                        log.Debugf("ChannelArbitrator(%v): skipped deadline "+
6✔
1459
                                "for dust htlc=%x",
6✔
1460
                                c.cfg.ChanPoint, htlc.RHash[:])
6✔
1461

6✔
1462
                        continue
6✔
1463
                }
1464

1465
                value := htlc.Amt.ToSatoshis()
10✔
1466

10✔
1467
                // Find the expiry height for this outgoing HTLC's incoming
10✔
1468
                // HTLC.
10✔
1469
                deadlineOpt := c.cfg.FindOutgoingHTLCDeadline(htlc)
10✔
1470

10✔
1471
                // The deadline is default to the current deadlineMinHeight,
10✔
1472
                // and it's overwritten when it's not none.
10✔
1473
                deadline := deadlineMinHeight
10✔
1474
                deadlineOpt.WhenSome(func(d int32) {
18✔
1475
                        deadline = uint32(d)
8✔
1476

8✔
1477
                        // We only consider the value is under protection when
8✔
1478
                        // it's time-sensitive.
8✔
1479
                        totalValue += value
8✔
1480
                })
8✔
1481

1482
                if deadline < deadlineMinHeight {
18✔
1483
                        deadlineMinHeight = deadline
8✔
1484

8✔
1485
                        log.Tracef("ChannelArbitrator(%v): outgoing HTLC has "+
8✔
1486
                                "deadline=%v, value=%v", c.cfg.ChanPoint,
8✔
1487
                                deadlineMinHeight, value)
8✔
1488
                }
8✔
1489
        }
1490

1491
        // Then going through the incomingHTLCs, and update the minHeight when
1492
        // conditions met.
1493
        for _, htlc := range htlcs.incomingHTLCs {
28✔
1494
                // Skip if the HTLC is dust.
12✔
1495
                if htlc.OutputIndex < 0 {
13✔
1496
                        log.Debugf("ChannelArbitrator(%v): skipped deadline "+
1✔
1497
                                "for dust htlc=%x",
1✔
1498
                                c.cfg.ChanPoint, htlc.RHash[:])
1✔
1499

1✔
1500
                        continue
1✔
1501
                }
1502

1503
                // Since it's an HTLC sent to us, check if we have preimage for
1504
                // this HTLC.
1505
                preimageAvailable, err := c.isPreimageAvailable(htlc.RHash)
11✔
1506
                if err != nil {
11✔
1507
                        return fn.None[int32](), 0, err
×
1508
                }
×
1509

1510
                if !preimageAvailable {
16✔
1511
                        continue
5✔
1512
                }
1513

1514
                value := htlc.Amt.ToSatoshis()
9✔
1515
                totalValue += value
9✔
1516

9✔
1517
                if htlc.RefundTimeout < deadlineMinHeight {
17✔
1518
                        deadlineMinHeight = htlc.RefundTimeout
8✔
1519

8✔
1520
                        log.Tracef("ChannelArbitrator(%v): incoming HTLC has "+
8✔
1521
                                "deadline=%v, amt=%v", c.cfg.ChanPoint,
8✔
1522
                                deadlineMinHeight, value)
8✔
1523
                }
8✔
1524
        }
1525

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

1540
        // When the deadline is passed, we will fall back to the smallest conf
1541
        // target (1 block).
1542
        case deadlineMinHeight <= heightHint:
1✔
1543
                log.Warnf("ChannelArbitrator(%v): deadline is passed with "+
1✔
1544
                        "deadlineMinHeight=%d, heightHint=%d",
1✔
1545
                        c.cfg.ChanPoint, deadlineMinHeight, heightHint)
1✔
1546
                deadline = 1
1✔
1547

1548
        // Use half of the deadline delta, and leave the other half to be used
1549
        // to sweep the HTLCs.
1550
        default:
11✔
1551
                deadline = (deadlineMinHeight - heightHint) / 2
11✔
1552
        }
1553

1554
        // Calculate the value left after subtracting the budget used for
1555
        // sweeping the time-sensitive HTLCs.
1556
        valueLeft := totalValue - calculateBudget(
12✔
1557
                totalValue, c.cfg.Budget.DeadlineHTLCRatio,
12✔
1558
                c.cfg.Budget.DeadlineHTLC,
12✔
1559
        )
12✔
1560

12✔
1561
        log.Debugf("ChannelArbitrator(%v): calculated valueLeft=%v, "+
12✔
1562
                "deadline=%d, using deadlineMinHeight=%d, heightHint=%d",
12✔
1563
                c.cfg.ChanPoint, valueLeft, deadline, deadlineMinHeight,
12✔
1564
                heightHint)
12✔
1565

12✔
1566
        return fn.Some(int32(deadline)), valueLeft, nil
12✔
1567
}
1568

1569
// resolveContracts updates the activeResolvers list and starts to resolve each
1570
// contract concurrently, and launches them.
1571
func (c *ChannelArbitrator) resolveContracts(resolvers []ContractResolver) {
16✔
1572
        c.activeResolversLock.Lock()
16✔
1573
        c.activeResolvers = resolvers
16✔
1574
        c.activeResolversLock.Unlock()
16✔
1575

16✔
1576
        // Launch all resolvers.
16✔
1577
        c.launchResolvers()
16✔
1578

16✔
1579
        for _, contract := range resolvers {
25✔
1580
                c.wg.Add(1)
9✔
1581
                go c.resolveContract(contract)
9✔
1582
        }
9✔
1583
}
1584

1585
// launchResolvers launches all the active resolvers concurrently.
1586
func (c *ChannelArbitrator) launchResolvers() {
22✔
1587
        c.activeResolversLock.Lock()
22✔
1588
        resolvers := c.activeResolvers
22✔
1589
        c.activeResolversLock.Unlock()
22✔
1590

22✔
1591
        // errChans is a map of channels that will be used to receive errors
22✔
1592
        // returned from launching the resolvers.
22✔
1593
        errChans := make(map[ContractResolver]chan error, len(resolvers))
22✔
1594

22✔
1595
        // Launch each resolver in goroutines.
22✔
1596
        for _, r := range resolvers {
31✔
1597
                // If the contract is already resolved, there's no need to
9✔
1598
                // launch it again.
9✔
1599
                if r.IsResolved() {
12✔
1600
                        log.Debugf("ChannelArbitrator(%v): skipping resolver "+
3✔
1601
                                "%T as it's already resolved", c.cfg.ChanPoint,
3✔
1602
                                r)
3✔
1603

3✔
1604
                        continue
3✔
1605
                }
1606

1607
                // Create a signal chan.
1608
                errChan := make(chan error, 1)
9✔
1609
                errChans[r] = errChan
9✔
1610

9✔
1611
                go func() {
18✔
1612
                        err := r.Launch()
9✔
1613
                        errChan <- err
9✔
1614
                }()
9✔
1615
        }
1616

1617
        // Wait for all resolvers to finish launching.
1618
        for r, errChan := range errChans {
31✔
1619
                select {
9✔
1620
                case err := <-errChan:
9✔
1621
                        if err == nil {
18✔
1622
                                continue
9✔
1623
                        }
1624

1625
                        log.Errorf("ChannelArbitrator(%v): unable to launch "+
×
1626
                                "contract resolver(%T): %v", c.cfg.ChanPoint, r,
×
1627
                                err)
×
1628

1629
                case <-c.quit:
×
1630
                        log.Debugf("ChannelArbitrator quit signal received, " +
×
1631
                                "exit launchResolvers")
×
1632

×
1633
                        return
×
1634
                }
1635
        }
1636
}
1637

1638
// advanceState is the main driver of our state machine. This method is an
1639
// iterative function which repeatedly attempts to advance the internal state
1640
// of the channel arbitrator. The state will be advanced until we reach a
1641
// redundant transition, meaning that the state transition is a noop. The final
1642
// param is a callback that allows the caller to execute an arbitrary action
1643
// after each state transition.
1644
func (c *ChannelArbitrator) advanceState(
1645
        triggerHeight uint32, trigger transitionTrigger,
1646
        confCommitSet *CommitSet) (ArbitratorState, *wire.MsgTx, error) {
91✔
1647

91✔
1648
        var (
91✔
1649
                priorState   ArbitratorState
91✔
1650
                forceCloseTx *wire.MsgTx
91✔
1651
        )
91✔
1652

91✔
1653
        // We'll continue to advance our state forward until the state we
91✔
1654
        // transition to is that same state that we started at.
91✔
1655
        for {
268✔
1656
                priorState = c.state
177✔
1657
                log.Debugf("ChannelArbitrator(%v): attempting state step with "+
177✔
1658
                        "trigger=%v from state=%v at height=%v",
177✔
1659
                        c.cfg.ChanPoint, trigger, priorState, triggerHeight)
177✔
1660

177✔
1661
                nextState, closeTx, err := c.stateStep(
177✔
1662
                        triggerHeight, trigger, confCommitSet,
177✔
1663
                )
177✔
1664
                if err != nil {
184✔
1665
                        log.Errorf("ChannelArbitrator(%v): unable to advance "+
7✔
1666
                                "state: %v", c.cfg.ChanPoint, err)
7✔
1667
                        return priorState, nil, err
7✔
1668
                }
7✔
1669

1670
                if forceCloseTx == nil && closeTx != nil {
192✔
1671
                        forceCloseTx = closeTx
19✔
1672
                }
19✔
1673

1674
                // Our termination transition is a noop transition. If we get
1675
                // our prior state back as the next state, then we'll
1676
                // terminate.
1677
                if nextState == priorState {
257✔
1678
                        log.Debugf("ChannelArbitrator(%v): terminating at "+
84✔
1679
                                "state=%v", c.cfg.ChanPoint, nextState)
84✔
1680
                        return nextState, forceCloseTx, nil
84✔
1681
                }
84✔
1682

1683
                // As the prior state was successfully executed, we can now
1684
                // commit the next state. This ensures that we will re-execute
1685
                // the prior state if anything fails.
1686
                if err := c.log.CommitState(nextState); err != nil {
95✔
1687
                        log.Errorf("ChannelArbitrator(%v): unable to commit "+
3✔
1688
                                "next state(%v): %v", c.cfg.ChanPoint,
3✔
1689
                                nextState, err)
3✔
1690
                        return priorState, nil, err
3✔
1691
                }
3✔
1692
                c.state = nextState
89✔
1693
        }
1694
}
1695

1696
// ChainAction is an enum that encompasses all possible on-chain actions
1697
// we'll take for a set of HTLC's.
1698
type ChainAction uint8
1699

1700
const (
1701
        // NoAction is the min chainAction type, indicating that no action
1702
        // needs to be taken for a given HTLC.
1703
        NoAction ChainAction = 0
1704

1705
        // HtlcTimeoutAction indicates that the HTLC will timeout soon. As a
1706
        // result, we should get ready to sweep it on chain after the timeout.
1707
        HtlcTimeoutAction = 1
1708

1709
        // HtlcClaimAction indicates that we should claim the HTLC on chain
1710
        // before its timeout period.
1711
        HtlcClaimAction = 2
1712

1713
        // HtlcFailDustAction indicates that we should fail the upstream HTLC
1714
        // for an outgoing dust HTLC immediately (even before the commitment
1715
        // transaction is confirmed) because it has no output on the commitment
1716
        // transaction. This also includes remote pending outgoing dust HTLCs.
1717
        HtlcFailDustAction = 3
1718

1719
        // HtlcOutgoingWatchAction indicates that we can't yet timeout this
1720
        // HTLC, but we had to go to chain on order to resolve an existing
1721
        // HTLC.  In this case, we'll either: time it out once it expires, or
1722
        // will learn the pre-image if the remote party claims the output. In
1723
        // this case, well add the pre-image to our global store.
1724
        HtlcOutgoingWatchAction = 4
1725

1726
        // HtlcIncomingWatchAction indicates that we don't yet have the
1727
        // pre-image to claim incoming HTLC, but we had to go to chain in order
1728
        // to resolve and existing HTLC. In this case, we'll either: let the
1729
        // other party time it out, or eventually learn of the pre-image, in
1730
        // which case we'll claim on chain.
1731
        HtlcIncomingWatchAction = 5
1732

1733
        // HtlcIncomingDustFinalAction indicates that we should mark an incoming
1734
        // dust htlc as final because it can't be claimed on-chain.
1735
        HtlcIncomingDustFinalAction = 6
1736

1737
        // HtlcFailDanglingAction indicates that we should fail the upstream
1738
        // HTLC for an outgoing HTLC immediately after the commitment
1739
        // transaction has confirmed because it has no corresponding output on
1740
        // the commitment transaction. This category does NOT include any dust
1741
        // HTLCs which are mapped in the "HtlcFailDustAction" category.
1742
        HtlcFailDanglingAction = 7
1743
)
1744

1745
// String returns a human readable string describing a chain action.
1746
func (c ChainAction) String() string {
×
1747
        switch c {
×
1748
        case NoAction:
×
1749
                return "NoAction"
×
1750

1751
        case HtlcTimeoutAction:
×
1752
                return "HtlcTimeoutAction"
×
1753

1754
        case HtlcClaimAction:
×
1755
                return "HtlcClaimAction"
×
1756

1757
        case HtlcFailDustAction:
×
1758
                return "HtlcFailDustAction"
×
1759

1760
        case HtlcOutgoingWatchAction:
×
1761
                return "HtlcOutgoingWatchAction"
×
1762

1763
        case HtlcIncomingWatchAction:
×
1764
                return "HtlcIncomingWatchAction"
×
1765

1766
        case HtlcIncomingDustFinalAction:
×
1767
                return "HtlcIncomingDustFinalAction"
×
1768

1769
        case HtlcFailDanglingAction:
×
1770
                return "HtlcFailDanglingAction"
×
1771

1772
        default:
×
1773
                return "<unknown action>"
×
1774
        }
1775
}
1776

1777
// ChainActionMap is a map of a chain action, to the set of HTLC's that need to
1778
// be acted upon for a given action type. The channel
1779
type ChainActionMap map[ChainAction][]channeldb.HTLC
1780

1781
// Merge merges the passed chain actions with the target chain action map.
1782
func (c ChainActionMap) Merge(actions ChainActionMap) {
71✔
1783
        for chainAction, htlcs := range actions {
87✔
1784
                c[chainAction] = append(c[chainAction], htlcs...)
16✔
1785
        }
16✔
1786
}
1787

1788
// shouldGoOnChain takes into account the absolute timeout of the HTLC, if the
1789
// confirmation delta that we need is close, and returns a bool indicating if
1790
// we should go on chain to claim.  We do this rather than waiting up until the
1791
// last minute as we want to ensure that when we *need* (HTLC is timed out) to
1792
// sweep, the commitment is already confirmed.
1793
func (c *ChannelArbitrator) shouldGoOnChain(htlc channeldb.HTLC,
1794
        broadcastDelta, currentHeight uint32) bool {
29✔
1795

29✔
1796
        // We'll calculate the broadcast cut off for this HTLC. This is the
29✔
1797
        // height that (based on our current fee estimation) we should
29✔
1798
        // broadcast in order to ensure the commitment transaction is confirmed
29✔
1799
        // before the HTLC fully expires.
29✔
1800
        broadcastCutOff := htlc.RefundTimeout - broadcastDelta
29✔
1801

29✔
1802
        log.Tracef("ChannelArbitrator(%v): examining outgoing contract: "+
29✔
1803
                "expiry=%v, cutoff=%v, height=%v", c.cfg.ChanPoint, htlc.RefundTimeout,
29✔
1804
                broadcastCutOff, currentHeight)
29✔
1805

29✔
1806
        // TODO(roasbeef): take into account default HTLC delta, don't need to
29✔
1807
        // broadcast immediately
29✔
1808
        //  * can then batch with SINGLE | ANYONECANPAY
29✔
1809

29✔
1810
        // We should on-chain for this HTLC, iff we're within out broadcast
29✔
1811
        // cutoff window.
29✔
1812
        if currentHeight < broadcastCutOff {
51✔
1813
                return false
22✔
1814
        }
22✔
1815

1816
        // In case of incoming htlc we should go to chain.
1817
        if htlc.Incoming {
13✔
1818
                return true
3✔
1819
        }
3✔
1820

1821
        // For htlcs that are result of our initiated payments we give some grace
1822
        // period before force closing the channel. During this time we expect
1823
        // both nodes to connect and give a chance to the other node to send its
1824
        // updates and cancel the htlc.
1825
        // This shouldn't add any security risk as there is no incoming htlc to
1826
        // fulfill at this case and the expectation is that when the channel is
1827
        // active the other node will send update_fail_htlc to remove the htlc
1828
        // without closing the channel. It is up to the user to force close the
1829
        // channel if the peer misbehaves and doesn't send the update_fail_htlc.
1830
        // It is useful when this node is most of the time not online and is
1831
        // likely to miss the time slot where the htlc may be cancelled.
1832
        isForwarded := c.cfg.IsForwardedHTLC(c.cfg.ShortChanID, htlc.HtlcIndex)
10✔
1833
        upTime := c.cfg.Clock.Now().Sub(c.startTimestamp)
10✔
1834
        return isForwarded || upTime > c.cfg.PaymentsExpirationGracePeriod
10✔
1835
}
1836

1837
// checkCommitChainActions is called for each new block connected to the end of
1838
// the main chain. Given the new block height, this new method will examine all
1839
// active HTLC's, and determine if we need to go on-chain to claim any of them.
1840
// A map of action -> []htlc is returned, detailing what action (if any) should
1841
// be performed for each HTLC. For timed out HTLC's, once the commitment has
1842
// been sufficiently confirmed, the HTLC's should be canceled backwards. For
1843
// redeemed HTLC's, we should send the pre-image back to the incoming link.
1844
func (c *ChannelArbitrator) checkCommitChainActions(height uint32,
1845
        trigger transitionTrigger, htlcs htlcSet) (ChainActionMap, error) {
71✔
1846

71✔
1847
        // TODO(roasbeef): would need to lock channel? channel totem?
71✔
1848
        //  * race condition if adding and we broadcast, etc
71✔
1849
        //  * or would make each instance sync?
71✔
1850

71✔
1851
        log.Debugf("ChannelArbitrator(%v): checking commit chain actions at "+
71✔
1852
                "height=%v, in_htlc_count=%v, out_htlc_count=%v",
71✔
1853
                c.cfg.ChanPoint, height,
71✔
1854
                len(htlcs.incomingHTLCs), len(htlcs.outgoingHTLCs))
71✔
1855

71✔
1856
        actionMap := make(ChainActionMap)
71✔
1857

71✔
1858
        // First, we'll make an initial pass over the set of incoming and
71✔
1859
        // outgoing HTLC's to decide if we need to go on chain at all.
71✔
1860
        haveChainActions := false
71✔
1861
        for _, htlc := range htlcs.outgoingHTLCs {
81✔
1862
                // We'll need to go on-chain for an outgoing HTLC if it was
10✔
1863
                // never resolved downstream, and it's "close" to timing out.
10✔
1864
                //
10✔
1865
                // TODO(yy): If there's no corresponding incoming HTLC, it
10✔
1866
                // means we are the first hop, hence the payer. This is a
10✔
1867
                // tricky case - unlike a forwarding hop, we don't have an
10✔
1868
                // incoming HTLC that will time out, which means as long as we
10✔
1869
                // can learn the preimage, we can settle the invoice (before it
10✔
1870
                // expires?).
10✔
1871
                toChain := c.shouldGoOnChain(
10✔
1872
                        htlc, c.cfg.OutgoingBroadcastDelta, height,
10✔
1873
                )
10✔
1874

10✔
1875
                if toChain {
13✔
1876
                        // Convert to int64 in case of overflow.
3✔
1877
                        remainingBlocks := int64(htlc.RefundTimeout) -
3✔
1878
                                int64(height)
3✔
1879

3✔
1880
                        log.Infof("ChannelArbitrator(%v): go to chain for "+
3✔
1881
                                "outgoing htlc %x: timeout=%v, amount=%v, "+
3✔
1882
                                "blocks_until_expiry=%v, broadcast_delta=%v",
3✔
1883
                                c.cfg.ChanPoint, htlc.RHash[:],
3✔
1884
                                htlc.RefundTimeout, htlc.Amt, remainingBlocks,
3✔
1885
                                c.cfg.OutgoingBroadcastDelta,
3✔
1886
                        )
3✔
1887
                }
3✔
1888

1889
                haveChainActions = haveChainActions || toChain
10✔
1890
        }
1891

1892
        for _, htlc := range htlcs.incomingHTLCs {
79✔
1893
                // We'll need to go on-chain to pull an incoming HTLC iff we
8✔
1894
                // know the pre-image and it's close to timing out. We need to
8✔
1895
                // ensure that we claim the funds that are rightfully ours
8✔
1896
                // on-chain.
8✔
1897
                preimageAvailable, err := c.isPreimageAvailable(htlc.RHash)
8✔
1898
                if err != nil {
8✔
1899
                        return nil, err
×
1900
                }
×
1901

1902
                if !preimageAvailable {
15✔
1903
                        continue
7✔
1904
                }
1905

1906
                toChain := c.shouldGoOnChain(
4✔
1907
                        htlc, c.cfg.IncomingBroadcastDelta, height,
4✔
1908
                )
4✔
1909

4✔
1910
                if toChain {
7✔
1911
                        // Convert to int64 in case of overflow.
3✔
1912
                        remainingBlocks := int64(htlc.RefundTimeout) -
3✔
1913
                                int64(height)
3✔
1914

3✔
1915
                        log.Infof("ChannelArbitrator(%v): go to chain for "+
3✔
1916
                                "incoming htlc %x: timeout=%v, amount=%v, "+
3✔
1917
                                "blocks_until_expiry=%v, broadcast_delta=%v",
3✔
1918
                                c.cfg.ChanPoint, htlc.RHash[:],
3✔
1919
                                htlc.RefundTimeout, htlc.Amt, remainingBlocks,
3✔
1920
                                c.cfg.IncomingBroadcastDelta,
3✔
1921
                        )
3✔
1922
                }
3✔
1923

1924
                haveChainActions = haveChainActions || toChain
4✔
1925
        }
1926

1927
        // If we don't have any actions to make, then we'll return an empty
1928
        // action map. We only do this if this was a chain trigger though, as
1929
        // if we're going to broadcast the commitment (or the remote party did)
1930
        // we're *forced* to act on each HTLC.
1931
        if !haveChainActions && trigger == chainTrigger {
114✔
1932
                log.Tracef("ChannelArbitrator(%v): no actions to take at "+
43✔
1933
                        "height=%v", c.cfg.ChanPoint, height)
43✔
1934
                return actionMap, nil
43✔
1935
        }
43✔
1936

1937
        // Now that we know we'll need to go on-chain, we'll examine all of our
1938
        // active outgoing HTLC's to see if we either need to: sweep them after
1939
        // a timeout (then cancel backwards), cancel them backwards
1940
        // immediately, or watch them as they're still active contracts.
1941
        for _, htlc := range htlcs.outgoingHTLCs {
41✔
1942
                switch {
10✔
1943
                // If the HTLC is dust, then we can cancel it backwards
1944
                // immediately as there's no matching contract to arbitrate
1945
                // on-chain. We know the HTLC is dust, if the OutputIndex
1946
                // negative.
1947
                case htlc.OutputIndex < 0:
5✔
1948
                        log.Tracef("ChannelArbitrator(%v): immediately "+
5✔
1949
                                "failing dust htlc=%x", c.cfg.ChanPoint,
5✔
1950
                                htlc.RHash[:])
5✔
1951

5✔
1952
                        actionMap[HtlcFailDustAction] = append(
5✔
1953
                                actionMap[HtlcFailDustAction], htlc,
5✔
1954
                        )
5✔
1955

1956
                // If we don't need to immediately act on this HTLC, then we'll
1957
                // mark it still "live". After we broadcast, we'll monitor it
1958
                // until the HTLC times out to see if we can also redeem it
1959
                // on-chain.
1960
                case !c.shouldGoOnChain(htlc, c.cfg.OutgoingBroadcastDelta,
1961
                        height,
1962
                ):
8✔
1963
                        // TODO(roasbeef): also need to be able to query
8✔
1964
                        // circuit map to see if HTLC hasn't been fully
8✔
1965
                        // resolved
8✔
1966
                        //
8✔
1967
                        //  * can't fail incoming until if outgoing not yet
8✔
1968
                        //  failed
8✔
1969

8✔
1970
                        log.Tracef("ChannelArbitrator(%v): watching chain to "+
8✔
1971
                                "decide action for outgoing htlc=%x",
8✔
1972
                                c.cfg.ChanPoint, htlc.RHash[:])
8✔
1973

8✔
1974
                        actionMap[HtlcOutgoingWatchAction] = append(
8✔
1975
                                actionMap[HtlcOutgoingWatchAction], htlc,
8✔
1976
                        )
8✔
1977

1978
                // Otherwise, we'll update our actionMap to mark that we need
1979
                // to sweep this HTLC on-chain
1980
                default:
3✔
1981
                        log.Tracef("ChannelArbitrator(%v): going on-chain to "+
3✔
1982
                                "timeout htlc=%x", c.cfg.ChanPoint, htlc.RHash[:])
3✔
1983

3✔
1984
                        actionMap[HtlcTimeoutAction] = append(
3✔
1985
                                actionMap[HtlcTimeoutAction], htlc,
3✔
1986
                        )
3✔
1987
                }
1988
        }
1989

1990
        // Similarly, for each incoming HTLC, now that we need to go on-chain,
1991
        // we'll either: sweep it immediately if we know the pre-image, or
1992
        // observe the output on-chain if we don't In this last, case we'll
1993
        // either learn of it eventually from the outgoing HTLC, or the sender
1994
        // will timeout the HTLC.
1995
        for _, htlc := range htlcs.incomingHTLCs {
39✔
1996
                // If the HTLC is dust, there is no action to be taken.
8✔
1997
                if htlc.OutputIndex < 0 {
13✔
1998
                        log.Debugf("ChannelArbitrator(%v): no resolution "+
5✔
1999
                                "needed for incoming dust htlc=%x",
5✔
2000
                                c.cfg.ChanPoint, htlc.RHash[:])
5✔
2001

5✔
2002
                        actionMap[HtlcIncomingDustFinalAction] = append(
5✔
2003
                                actionMap[HtlcIncomingDustFinalAction], htlc,
5✔
2004
                        )
5✔
2005

5✔
2006
                        continue
5✔
2007
                }
2008

2009
                log.Tracef("ChannelArbitrator(%v): watching chain to decide "+
6✔
2010
                        "action for incoming htlc=%x", c.cfg.ChanPoint,
6✔
2011
                        htlc.RHash[:])
6✔
2012

6✔
2013
                actionMap[HtlcIncomingWatchAction] = append(
6✔
2014
                        actionMap[HtlcIncomingWatchAction], htlc,
6✔
2015
                )
6✔
2016
        }
2017

2018
        return actionMap, nil
31✔
2019
}
2020

2021
// isPreimageAvailable returns whether the hash preimage is available in either
2022
// the preimage cache or the invoice database.
2023
func (c *ChannelArbitrator) isPreimageAvailable(hash lntypes.Hash) (bool,
2024
        error) {
20✔
2025

20✔
2026
        // Start by checking the preimage cache for preimages of
20✔
2027
        // forwarded HTLCs.
20✔
2028
        _, preimageAvailable := c.cfg.PreimageDB.LookupPreimage(
20✔
2029
                hash,
20✔
2030
        )
20✔
2031
        if preimageAvailable {
30✔
2032
                return true, nil
10✔
2033
        }
10✔
2034

2035
        // Then check if we have an invoice that can be settled by this HTLC.
2036
        //
2037
        // TODO(joostjager): Check that there are still more blocks remaining
2038
        // than the invoice cltv delta. We don't want to go to chain only to
2039
        // have the incoming contest resolver decide that we don't want to
2040
        // settle this invoice.
2041
        invoice, err := c.cfg.Registry.LookupInvoice(context.Background(), hash)
13✔
2042
        switch {
13✔
2043
        case err == nil:
3✔
2044
        case errors.Is(err, invoices.ErrInvoiceNotFound) ||
2045
                errors.Is(err, invoices.ErrNoInvoicesCreated):
13✔
2046

13✔
2047
                return false, nil
13✔
2048
        default:
×
2049
                return false, err
×
2050
        }
2051

2052
        preimageAvailable = invoice.Terms.PaymentPreimage != nil
3✔
2053

3✔
2054
        return preimageAvailable, nil
3✔
2055
}
2056

2057
// checkLocalChainActions is similar to checkCommitChainActions, but it also
2058
// examines the set of HTLCs on the remote party's commitment. This allows us
2059
// to ensure we're able to satisfy the HTLC timeout constraints for incoming vs
2060
// outgoing HTLCs.
2061
func (c *ChannelArbitrator) checkLocalChainActions(
2062
        height uint32, trigger transitionTrigger,
2063
        activeHTLCs map[HtlcSetKey]htlcSet,
2064
        commitsConfirmed bool) (ChainActionMap, error) {
63✔
2065

63✔
2066
        // First, we'll check our local chain actions as normal. This will only
63✔
2067
        // examine HTLCs on our local commitment (timeout or settle).
63✔
2068
        localCommitActions, err := c.checkCommitChainActions(
63✔
2069
                height, trigger, activeHTLCs[LocalHtlcSet],
63✔
2070
        )
63✔
2071
        if err != nil {
63✔
2072
                return nil, err
×
2073
        }
×
2074

2075
        // Next, we'll examine the remote commitment (and maybe a dangling one)
2076
        // to see if the set difference of our HTLCs is non-empty. If so, then
2077
        // we may need to cancel back some HTLCs if we decide go to chain.
2078
        remoteDanglingActions := c.checkRemoteDanglingActions(
63✔
2079
                height, activeHTLCs, commitsConfirmed,
63✔
2080
        )
63✔
2081

63✔
2082
        // Finally, we'll merge the two set of chain actions.
63✔
2083
        localCommitActions.Merge(remoteDanglingActions)
63✔
2084

63✔
2085
        return localCommitActions, nil
63✔
2086
}
2087

2088
// checkRemoteDanglingActions examines the set of remote commitments for any
2089
// HTLCs that are close to timing out. If we find any, then we'll return a set
2090
// of chain actions for HTLCs that are on our commitment, but not theirs to
2091
// cancel immediately.
2092
func (c *ChannelArbitrator) checkRemoteDanglingActions(
2093
        height uint32, activeHTLCs map[HtlcSetKey]htlcSet,
2094
        commitsConfirmed bool) ChainActionMap {
63✔
2095

63✔
2096
        var (
63✔
2097
                pendingRemoteHTLCs []channeldb.HTLC
63✔
2098
                localHTLCs         = make(map[uint64]struct{})
63✔
2099
                remoteHTLCs        = make(map[uint64]channeldb.HTLC)
63✔
2100
                actionMap          = make(ChainActionMap)
63✔
2101
        )
63✔
2102

63✔
2103
        // First, we'll construct two sets of the outgoing HTLCs: those on our
63✔
2104
        // local commitment, and those that are on the remote commitment(s).
63✔
2105
        for htlcSetKey, htlcs := range activeHTLCs {
183✔
2106
                if htlcSetKey.IsRemote {
185✔
2107
                        for _, htlc := range htlcs.outgoingHTLCs {
82✔
2108
                                remoteHTLCs[htlc.HtlcIndex] = htlc
17✔
2109
                        }
17✔
2110
                } else {
58✔
2111
                        for _, htlc := range htlcs.outgoingHTLCs {
66✔
2112
                                localHTLCs[htlc.HtlcIndex] = struct{}{}
8✔
2113
                        }
8✔
2114
                }
2115
        }
2116

2117
        // With both sets constructed, we'll now compute the set difference of
2118
        // our two sets of HTLCs. This'll give us the HTLCs that exist on the
2119
        // remote commitment transaction, but not on ours.
2120
        for htlcIndex, htlc := range remoteHTLCs {
80✔
2121
                if _, ok := localHTLCs[htlcIndex]; ok {
21✔
2122
                        continue
4✔
2123
                }
2124

2125
                pendingRemoteHTLCs = append(pendingRemoteHTLCs, htlc)
16✔
2126
        }
2127

2128
        // Finally, we'll examine all the pending remote HTLCs for those that
2129
        // have expired. If we find any, then we'll recommend that they be
2130
        // failed now so we can free up the incoming HTLC.
2131
        for _, htlc := range pendingRemoteHTLCs {
79✔
2132
                // We'll now check if we need to go to chain in order to cancel
16✔
2133
                // the incoming HTLC.
16✔
2134
                goToChain := c.shouldGoOnChain(htlc, c.cfg.OutgoingBroadcastDelta,
16✔
2135
                        height,
16✔
2136
                )
16✔
2137

16✔
2138
                // If we don't need to go to chain, and no commitments have
16✔
2139
                // been confirmed, then we can move on. Otherwise, if
16✔
2140
                // commitments have been confirmed, then we need to cancel back
16✔
2141
                // *all* of the pending remote HTLCS.
16✔
2142
                if !goToChain && !commitsConfirmed {
23✔
2143
                        continue
7✔
2144
                }
2145

2146
                // Dust htlcs can be canceled back even before the commitment
2147
                // transaction confirms. Dust htlcs are not enforceable onchain.
2148
                // If another version of the commit tx would confirm we either
2149
                // gain or lose those dust amounts but there is no other way
2150
                // than cancelling the incoming back because we will never learn
2151
                // the preimage.
2152
                if htlc.OutputIndex < 0 {
12✔
2153
                        log.Infof("ChannelArbitrator(%v): fail dangling dust "+
×
2154
                                "htlc=%x from local/remote commitments diff",
×
2155
                                c.cfg.ChanPoint, htlc.RHash[:])
×
2156

×
2157
                        actionMap[HtlcFailDustAction] = append(
×
2158
                                actionMap[HtlcFailDustAction], htlc,
×
2159
                        )
×
2160

×
2161
                        continue
×
2162
                }
2163

2164
                log.Infof("ChannelArbitrator(%v): fail dangling htlc=%x from "+
12✔
2165
                        "local/remote commitments diff",
12✔
2166
                        c.cfg.ChanPoint, htlc.RHash[:])
12✔
2167

12✔
2168
                actionMap[HtlcFailDanglingAction] = append(
12✔
2169
                        actionMap[HtlcFailDanglingAction], htlc,
12✔
2170
                )
12✔
2171
        }
2172

2173
        return actionMap
63✔
2174
}
2175

2176
// checkRemoteChainActions examines the two possible remote commitment chains
2177
// and returns the set of chain actions we need to carry out if the remote
2178
// commitment (non pending) confirms. The pendingConf indicates if the pending
2179
// remote commitment confirmed. This is similar to checkCommitChainActions, but
2180
// we'll immediately fail any HTLCs on the pending remote commit, but not the
2181
// remote commit (or the other way around).
2182
func (c *ChannelArbitrator) checkRemoteChainActions(
2183
        height uint32, trigger transitionTrigger,
2184
        activeHTLCs map[HtlcSetKey]htlcSet,
2185
        pendingConf bool) (ChainActionMap, error) {
11✔
2186

11✔
2187
        // First, we'll examine all the normal chain actions on the remote
11✔
2188
        // commitment that confirmed.
11✔
2189
        confHTLCs := activeHTLCs[RemoteHtlcSet]
11✔
2190
        if pendingConf {
13✔
2191
                confHTLCs = activeHTLCs[RemotePendingHtlcSet]
2✔
2192
        }
2✔
2193
        remoteCommitActions, err := c.checkCommitChainActions(
11✔
2194
                height, trigger, confHTLCs,
11✔
2195
        )
11✔
2196
        if err != nil {
11✔
2197
                return nil, err
×
2198
        }
×
2199

2200
        // With these actions computed, we'll now check the diff of the HTLCs on
2201
        // the commitments, and cancel back any that are on the pending but not
2202
        // the non-pending.
2203
        remoteDiffActions := c.checkRemoteDiffActions(
11✔
2204
                activeHTLCs, pendingConf,
11✔
2205
        )
11✔
2206

11✔
2207
        // Finally, we'll merge all the chain actions and the final set of
11✔
2208
        // chain actions.
11✔
2209
        remoteCommitActions.Merge(remoteDiffActions)
11✔
2210
        return remoteCommitActions, nil
11✔
2211
}
2212

2213
// checkRemoteDiffActions checks the set difference of the HTLCs on the remote
2214
// confirmed commit and remote pending commit for HTLCS that we need to cancel
2215
// back. If we find any HTLCs on the remote pending but not the remote, then
2216
// we'll mark them to be failed immediately.
2217
func (c *ChannelArbitrator) checkRemoteDiffActions(
2218
        activeHTLCs map[HtlcSetKey]htlcSet,
2219
        pendingConf bool) ChainActionMap {
11✔
2220

11✔
2221
        // First, we'll partition the HTLCs into those that are present on the
11✔
2222
        // confirmed commitment, and those on the dangling commitment.
11✔
2223
        confHTLCs := activeHTLCs[RemoteHtlcSet]
11✔
2224
        danglingHTLCs := activeHTLCs[RemotePendingHtlcSet]
11✔
2225
        if pendingConf {
13✔
2226
                confHTLCs = activeHTLCs[RemotePendingHtlcSet]
2✔
2227
                danglingHTLCs = activeHTLCs[RemoteHtlcSet]
2✔
2228
        }
2✔
2229

2230
        // Next, we'll create a set of all the HTLCs confirmed commitment.
2231
        remoteHtlcs := make(map[uint64]struct{})
11✔
2232
        for _, htlc := range confHTLCs.outgoingHTLCs {
16✔
2233
                remoteHtlcs[htlc.HtlcIndex] = struct{}{}
5✔
2234
        }
5✔
2235

2236
        // With the remote HTLCs assembled, we'll mark any HTLCs only on the
2237
        // remote pending commitment to be failed asap.
2238
        actionMap := make(ChainActionMap)
11✔
2239
        for _, htlc := range danglingHTLCs.outgoingHTLCs {
18✔
2240
                if _, ok := remoteHtlcs[htlc.HtlcIndex]; ok {
10✔
2241
                        continue
3✔
2242
                }
2243

2244
                preimageAvailable, err := c.isPreimageAvailable(htlc.RHash)
4✔
2245
                if err != nil {
4✔
2246
                        log.Errorf("ChannelArbitrator(%v): failed to query "+
×
2247
                                "preimage for dangling htlc=%x from remote "+
×
2248
                                "commitments diff", c.cfg.ChanPoint,
×
2249
                                htlc.RHash[:])
×
2250

×
2251
                        continue
×
2252
                }
2253

2254
                if preimageAvailable {
4✔
2255
                        continue
×
2256
                }
2257

2258
                // Dust HTLCs on the remote commitment can be failed back.
2259
                if htlc.OutputIndex < 0 {
4✔
2260
                        log.Infof("ChannelArbitrator(%v): fail dangling dust "+
×
2261
                                "htlc=%x from remote commitments diff",
×
2262
                                c.cfg.ChanPoint, htlc.RHash[:])
×
2263

×
2264
                        actionMap[HtlcFailDustAction] = append(
×
2265
                                actionMap[HtlcFailDustAction], htlc,
×
2266
                        )
×
2267

×
2268
                        continue
×
2269
                }
2270

2271
                actionMap[HtlcFailDanglingAction] = append(
4✔
2272
                        actionMap[HtlcFailDanglingAction], htlc,
4✔
2273
                )
4✔
2274

4✔
2275
                log.Infof("ChannelArbitrator(%v): fail dangling htlc=%x from "+
4✔
2276
                        "remote commitments diff",
4✔
2277
                        c.cfg.ChanPoint, htlc.RHash[:])
4✔
2278
        }
2279

2280
        return actionMap
11✔
2281
}
2282

2283
// constructChainActions returns the set of actions that should be taken for
2284
// confirmed HTLCs at the specified height. Our actions will depend on the set
2285
// of HTLCs that were active across all channels at the time of channel
2286
// closure.
2287
func (c *ChannelArbitrator) constructChainActions(confCommitSet *CommitSet,
2288
        height uint32, trigger transitionTrigger) (ChainActionMap, error) {
24✔
2289

24✔
2290
        // If we've reached this point and have not confirmed commitment set,
24✔
2291
        // then this is an older node that had a pending close channel before
24✔
2292
        // the CommitSet was introduced. In this case, we'll just return the
24✔
2293
        // existing ChainActionMap they had on disk.
24✔
2294
        if confCommitSet == nil || confCommitSet.ConfCommitKey.IsNone() {
31✔
2295
                return c.log.FetchChainActions()
7✔
2296
        }
7✔
2297

2298
        // Otherwise, we have the full commitment set written to disk, and can
2299
        // proceed as normal.
2300
        htlcSets := confCommitSet.toActiveHTLCSets()
17✔
2301
        confCommitKey, err := confCommitSet.ConfCommitKey.UnwrapOrErr(
17✔
2302
                fmt.Errorf("no commitKey available"),
17✔
2303
        )
17✔
2304
        if err != nil {
17✔
2305
                return nil, err
×
2306
        }
×
2307

2308
        switch confCommitKey {
17✔
2309
        // If the local commitment transaction confirmed, then we'll examine
2310
        // that as well as their commitments to the set of chain actions.
2311
        case LocalHtlcSet:
9✔
2312
                return c.checkLocalChainActions(
9✔
2313
                        height, trigger, htlcSets, true,
9✔
2314
                )
9✔
2315

2316
        // If the remote commitment confirmed, then we'll grab all the chain
2317
        // actions for the remote commit, and check the pending commit for any
2318
        // HTLCS we need to handle immediately (dust).
2319
        case RemoteHtlcSet:
9✔
2320
                return c.checkRemoteChainActions(
9✔
2321
                        height, trigger, htlcSets, false,
9✔
2322
                )
9✔
2323

2324
        // Otherwise, the remote pending commitment confirmed, so we'll examine
2325
        // the HTLCs on that unrevoked dangling commitment.
2326
        case RemotePendingHtlcSet:
2✔
2327
                return c.checkRemoteChainActions(
2✔
2328
                        height, trigger, htlcSets, true,
2✔
2329
                )
2✔
2330
        }
2331

2332
        return nil, fmt.Errorf("unable to locate chain actions")
×
2333
}
2334

2335
// prepContractResolutions is called either in the case that we decide we need
2336
// to go to chain, or the remote party goes to chain. Given a set of actions we
2337
// need to take for each HTLC, this method will return a set of contract
2338
// resolvers that will resolve the contracts on-chain if needed, and also a set
2339
// of packets to send to the htlcswitch in order to ensure all incoming HTLC's
2340
// are properly resolved.
2341
func (c *ChannelArbitrator) prepContractResolutions(
2342
        contractResolutions *ContractResolutions, height uint32,
2343
        htlcActions ChainActionMap) ([]ContractResolver, error) {
15✔
2344

15✔
2345
        // We'll also fetch the historical state of this channel, as it should
15✔
2346
        // have been marked as closed by now, and supplement it to each resolver
15✔
2347
        // such that we can properly resolve our pending contracts.
15✔
2348
        var chanState *channeldb.OpenChannel
15✔
2349
        chanState, err := c.cfg.FetchHistoricalChannel()
15✔
2350
        switch {
15✔
2351
        // If we don't find this channel, then it may be the case that it
2352
        // was closed before we started to retain the final state
2353
        // information for open channels.
2354
        case err == channeldb.ErrNoHistoricalBucket:
×
2355
                fallthrough
×
2356
        case err == channeldb.ErrChannelNotFound:
×
2357
                log.Warnf("ChannelArbitrator(%v): unable to fetch historical "+
×
2358
                        "state", c.cfg.ChanPoint)
×
2359

2360
        case err != nil:
×
2361
                return nil, err
×
2362
        }
2363

2364
        incomingResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs
15✔
2365
        outgoingResolutions := contractResolutions.HtlcResolutions.OutgoingHTLCs
15✔
2366

15✔
2367
        // We'll use these two maps to quickly look up an active HTLC with its
15✔
2368
        // matching HTLC resolution.
15✔
2369
        outResolutionMap := make(map[wire.OutPoint]lnwallet.OutgoingHtlcResolution)
15✔
2370
        inResolutionMap := make(map[wire.OutPoint]lnwallet.IncomingHtlcResolution)
15✔
2371
        for i := 0; i < len(incomingResolutions); i++ {
18✔
2372
                inRes := incomingResolutions[i]
3✔
2373
                inResolutionMap[inRes.HtlcPoint()] = inRes
3✔
2374
        }
3✔
2375
        for i := 0; i < len(outgoingResolutions); i++ {
19✔
2376
                outRes := outgoingResolutions[i]
4✔
2377
                outResolutionMap[outRes.HtlcPoint()] = outRes
4✔
2378
        }
4✔
2379

2380
        // We'll create the resolver kit that we'll be cloning for each
2381
        // resolver so they each can do their duty.
2382
        resolverCfg := ResolverConfig{
15✔
2383
                ChannelArbitratorConfig: c.cfg,
15✔
2384
                Checkpoint: func(res ContractResolver,
15✔
2385
                        reports ...*channeldb.ResolverReport) error {
20✔
2386

5✔
2387
                        return c.log.InsertUnresolvedContracts(reports, res)
5✔
2388
                },
5✔
2389
        }
2390

2391
        commitHash := contractResolutions.CommitHash
15✔
2392

15✔
2393
        var htlcResolvers []ContractResolver
15✔
2394

15✔
2395
        // We instantiate an anchor resolver if the commitment tx has an
15✔
2396
        // anchor.
15✔
2397
        if contractResolutions.AnchorResolution != nil {
20✔
2398
                anchorResolver := newAnchorResolver(
5✔
2399
                        contractResolutions.AnchorResolution.AnchorSignDescriptor,
5✔
2400
                        contractResolutions.AnchorResolution.CommitAnchor,
5✔
2401
                        height, c.cfg.ChanPoint, resolverCfg,
5✔
2402
                )
5✔
2403
                anchorResolver.SupplementState(chanState)
5✔
2404

5✔
2405
                htlcResolvers = append(htlcResolvers, anchorResolver)
5✔
2406
        }
5✔
2407

2408
        // If this is a breach close, we'll create a breach resolver, determine
2409
        // the htlc's to fail back, and exit. This is done because the other
2410
        // steps taken for non-breach-closes do not matter for breach-closes.
2411
        if contractResolutions.BreachResolution != nil {
20✔
2412
                breachResolver := newBreachResolver(resolverCfg)
5✔
2413
                htlcResolvers = append(htlcResolvers, breachResolver)
5✔
2414

5✔
2415
                return htlcResolvers, nil
5✔
2416
        }
5✔
2417

2418
        // For each HTLC, we'll either act immediately, meaning we'll instantly
2419
        // fail the HTLC, or we'll act only once the transaction has been
2420
        // confirmed, in which case we'll need an HTLC resolver.
2421
        for htlcAction, htlcs := range htlcActions {
27✔
2422
                switch htlcAction {
14✔
2423
                // If we can claim this HTLC, we'll create an HTLC resolver to
2424
                // claim the HTLC (second-level or directly), then add the pre
2425
                case HtlcClaimAction:
×
2426
                        for _, htlc := range htlcs {
×
2427
                                htlc := htlc
×
2428

×
2429
                                htlcOp := wire.OutPoint{
×
2430
                                        Hash:  commitHash,
×
2431
                                        Index: uint32(htlc.OutputIndex),
×
2432
                                }
×
2433

×
2434
                                resolution, ok := inResolutionMap[htlcOp]
×
2435
                                if !ok {
×
2436
                                        // TODO(roasbeef): panic?
×
2437
                                        log.Errorf("ChannelArbitrator(%v) unable to find "+
×
2438
                                                "incoming resolution: %v",
×
2439
                                                c.cfg.ChanPoint, htlcOp)
×
2440
                                        continue
×
2441
                                }
2442

2443
                                resolver := newSuccessResolver(
×
2444
                                        resolution, height, htlc, resolverCfg,
×
2445
                                )
×
2446
                                if chanState != nil {
×
2447
                                        resolver.SupplementState(chanState)
×
2448
                                }
×
2449
                                htlcResolvers = append(htlcResolvers, resolver)
×
2450
                        }
2451

2452
                // If we can timeout the HTLC directly, then we'll create the
2453
                // proper resolver to do so, who will then cancel the packet
2454
                // backwards.
2455
                case HtlcTimeoutAction:
3✔
2456
                        for _, htlc := range htlcs {
6✔
2457
                                htlc := htlc
3✔
2458

3✔
2459
                                htlcOp := wire.OutPoint{
3✔
2460
                                        Hash:  commitHash,
3✔
2461
                                        Index: uint32(htlc.OutputIndex),
3✔
2462
                                }
3✔
2463

3✔
2464
                                resolution, ok := outResolutionMap[htlcOp]
3✔
2465
                                if !ok {
3✔
2466
                                        log.Errorf("ChannelArbitrator(%v) unable to find "+
×
2467
                                                "outgoing resolution: %v", c.cfg.ChanPoint, htlcOp)
×
2468
                                        continue
×
2469
                                }
2470

2471
                                resolver := newTimeoutResolver(
3✔
2472
                                        resolution, height, htlc, resolverCfg,
3✔
2473
                                )
3✔
2474
                                if chanState != nil {
6✔
2475
                                        resolver.SupplementState(chanState)
3✔
2476
                                }
3✔
2477

2478
                                // For outgoing HTLCs, we will also need to
2479
                                // supplement the resolver with the expiry
2480
                                // block height of its corresponding incoming
2481
                                // HTLC.
2482
                                deadline := c.cfg.FindOutgoingHTLCDeadline(htlc)
3✔
2483
                                resolver.SupplementDeadline(deadline)
3✔
2484

3✔
2485
                                htlcResolvers = append(htlcResolvers, resolver)
3✔
2486
                        }
2487

2488
                // If this is an incoming HTLC, but we can't act yet, then
2489
                // we'll create an incoming resolver to redeem the HTLC if we
2490
                // learn of the pre-image, or let the remote party time out.
2491
                case HtlcIncomingWatchAction:
3✔
2492
                        for _, htlc := range htlcs {
6✔
2493
                                htlc := htlc
3✔
2494

3✔
2495
                                htlcOp := wire.OutPoint{
3✔
2496
                                        Hash:  commitHash,
3✔
2497
                                        Index: uint32(htlc.OutputIndex),
3✔
2498
                                }
3✔
2499

3✔
2500
                                // TODO(roasbeef): need to handle incoming dust...
3✔
2501

3✔
2502
                                // TODO(roasbeef): can't be negative!!!
3✔
2503
                                resolution, ok := inResolutionMap[htlcOp]
3✔
2504
                                if !ok {
3✔
2505
                                        log.Errorf("ChannelArbitrator(%v) unable to find "+
×
2506
                                                "incoming resolution: %v",
×
2507
                                                c.cfg.ChanPoint, htlcOp)
×
2508
                                        continue
×
2509
                                }
2510

2511
                                resolver := newIncomingContestResolver(
3✔
2512
                                        resolution, height, htlc,
3✔
2513
                                        resolverCfg,
3✔
2514
                                )
3✔
2515
                                if chanState != nil {
6✔
2516
                                        resolver.SupplementState(chanState)
3✔
2517
                                }
3✔
2518
                                htlcResolvers = append(htlcResolvers, resolver)
3✔
2519
                        }
2520

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

4✔
2528
                                htlcOp := wire.OutPoint{
4✔
2529
                                        Hash:  commitHash,
4✔
2530
                                        Index: uint32(htlc.OutputIndex),
4✔
2531
                                }
4✔
2532

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

×
2540
                                        continue
×
2541
                                }
2542

2543
                                resolver := newOutgoingContestResolver(
4✔
2544
                                        resolution, height, htlc, resolverCfg,
4✔
2545
                                )
4✔
2546
                                if chanState != nil {
8✔
2547
                                        resolver.SupplementState(chanState)
4✔
2548
                                }
4✔
2549

2550
                                // For outgoing HTLCs, we will also need to
2551
                                // supplement the resolver with the expiry
2552
                                // block height of its corresponding incoming
2553
                                // HTLC.
2554
                                deadline := c.cfg.FindOutgoingHTLCDeadline(htlc)
4✔
2555
                                resolver.SupplementDeadline(deadline)
4✔
2556

4✔
2557
                                htlcResolvers = append(htlcResolvers, resolver)
4✔
2558
                        }
2559
                }
2560
        }
2561

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

2576
        return htlcResolvers, nil
13✔
2577
}
2578

2579
// replaceResolver replaces a in the list of active resolvers. If the resolver
2580
// to be replaced is not found, it returns an error.
2581
func (c *ChannelArbitrator) replaceResolver(oldResolver,
2582
        newResolver ContractResolver) error {
4✔
2583

4✔
2584
        c.activeResolversLock.Lock()
4✔
2585
        defer c.activeResolversLock.Unlock()
4✔
2586

4✔
2587
        oldKey := oldResolver.ResolverKey()
4✔
2588
        for i, r := range c.activeResolvers {
8✔
2589
                if bytes.Equal(r.ResolverKey(), oldKey) {
8✔
2590
                        c.activeResolvers[i] = newResolver
4✔
2591
                        return nil
4✔
2592
                }
4✔
2593
        }
2594

2595
        return errors.New("resolver to be replaced not found")
×
2596
}
2597

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

9✔
2609
        log.Debugf("ChannelArbitrator(%v): attempting to resolve %T",
9✔
2610
                c.cfg.ChanPoint, currentContract)
9✔
2611

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

10✔
2618
                select {
10✔
2619

2620
                // If we've been signalled to quit, then we'll exit early.
2621
                case <-c.quit:
×
2622
                        return
×
2623

2624
                default:
10✔
2625
                        // Otherwise, we'll attempt to resolve the current
10✔
2626
                        // contract.
10✔
2627
                        nextContract, err := currentContract.Resolve()
10✔
2628
                        if err != nil {
14✔
2629
                                if err == errResolverShuttingDown {
8✔
2630
                                        return
4✔
2631
                                }
4✔
2632

2633
                                log.Errorf("ChannelArbitrator(%v): unable to "+
3✔
2634
                                        "progress %T: %v",
3✔
2635
                                        c.cfg.ChanPoint, currentContract, err)
3✔
2636
                                return
3✔
2637
                        }
2638

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

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

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

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

4✔
2676
                                // Launch the new contract.
4✔
2677
                                err = currentContract.Launch()
4✔
2678
                                if err != nil {
4✔
2679
                                        log.Errorf("Failed to launch %T: %v",
×
2680
                                                currentContract, err)
×
2681
                                }
×
2682

2683
                        // If this contract is actually fully resolved, then
2684
                        // we'll mark it as such within the database.
2685
                        case currentContract.IsResolved():
8✔
2686
                                log.Debugf("ChannelArbitrator(%v): marking "+
8✔
2687
                                        "contract %T fully resolved",
8✔
2688
                                        c.cfg.ChanPoint, currentContract)
8✔
2689

8✔
2690
                                err := c.log.ResolveContract(currentContract)
8✔
2691
                                if err != nil {
8✔
2692
                                        log.Errorf("unable to resolve contract: %v",
×
2693
                                                err)
×
2694
                                }
×
2695

2696
                                // Now that the contract has been resolved,
2697
                                // well signal to the main goroutine.
2698
                                select {
8✔
2699
                                case c.resolutionSignal <- struct{}{}:
7✔
2700
                                case <-c.quit:
4✔
2701
                                        return
4✔
2702
                                }
2703
                        }
2704

2705
                }
2706
        }
2707
}
2708

2709
// signalUpdateMsg is a struct that carries fresh signals to the
2710
// ChannelArbitrator. We need to receive a message like this each time the
2711
// channel becomes active, as it's internal state may change.
2712
type signalUpdateMsg struct {
2713
        // newSignals is the set of new active signals to be sent to the
2714
        // arbitrator.
2715
        newSignals *ContractSignals
2716

2717
        // doneChan is a channel that will be closed on the arbitrator has
2718
        // attached the new signals.
2719
        doneChan chan struct{}
2720
}
2721

2722
// UpdateContractSignals updates the set of signals the ChannelArbitrator needs
2723
// to receive from a channel in real-time in order to keep in sync with the
2724
// latest state of the contract.
2725
func (c *ChannelArbitrator) UpdateContractSignals(newSignals *ContractSignals) {
14✔
2726
        done := make(chan struct{})
14✔
2727

14✔
2728
        select {
14✔
2729
        case c.signalUpdates <- &signalUpdateMsg{
2730
                newSignals: newSignals,
2731
                doneChan:   done,
2732
        }:
14✔
2733
        case <-c.quit:
×
2734
        }
2735

2736
        select {
14✔
2737
        case <-done:
14✔
2738
        case <-c.quit:
×
2739
        }
2740
}
2741

2742
// notifyContractUpdate updates the ChannelArbitrator's unmerged mappings such
2743
// that it can later be merged with activeHTLCs when calling
2744
// checkLocalChainActions or sweepAnchors. These are the only two places that
2745
// activeHTLCs is used.
2746
func (c *ChannelArbitrator) notifyContractUpdate(upd *ContractUpdate) {
15✔
2747
        c.unmergedMtx.Lock()
15✔
2748
        defer c.unmergedMtx.Unlock()
15✔
2749

15✔
2750
        // Update the mapping.
15✔
2751
        c.unmergedSet[upd.HtlcKey] = newHtlcSet(upd.Htlcs)
15✔
2752

15✔
2753
        log.Tracef("ChannelArbitrator(%v): fresh set of htlcs=%v",
15✔
2754
                c.cfg.ChanPoint, lnutils.SpewLogClosure(upd))
15✔
2755
}
15✔
2756

2757
// updateActiveHTLCs merges the unmerged set of HTLCs from the link with
2758
// activeHTLCs.
2759
func (c *ChannelArbitrator) updateActiveHTLCs() {
76✔
2760
        c.unmergedMtx.RLock()
76✔
2761
        defer c.unmergedMtx.RUnlock()
76✔
2762

76✔
2763
        // Update the mapping.
76✔
2764
        c.activeHTLCs[LocalHtlcSet] = c.unmergedSet[LocalHtlcSet]
76✔
2765
        c.activeHTLCs[RemoteHtlcSet] = c.unmergedSet[RemoteHtlcSet]
76✔
2766

76✔
2767
        // If the pending set exists, update that as well.
76✔
2768
        if _, ok := c.unmergedSet[RemotePendingHtlcSet]; ok {
88✔
2769
                pendingSet := c.unmergedSet[RemotePendingHtlcSet]
12✔
2770
                c.activeHTLCs[RemotePendingHtlcSet] = pendingSet
12✔
2771
        }
12✔
2772
}
2773

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

50✔
2788
        // TODO(roasbeef): tell top chain arb we're done
50✔
2789
        defer func() {
97✔
2790
                c.wg.Done()
47✔
2791
        }()
47✔
2792

2793
        for {
150✔
2794
                select {
100✔
2795

2796
                // A new block has arrived, we'll examine all the active HTLC's
2797
                // to see if any of them have expired, and also update our
2798
                // track of the best current height.
2799
                case beat := <-c.BlockbeatChan:
9✔
2800
                        bestHeight = beat.Height()
9✔
2801

9✔
2802
                        log.Debugf("ChannelArbitrator(%v): new block height=%v",
9✔
2803
                                c.cfg.ChanPoint, bestHeight)
9✔
2804

9✔
2805
                        err := c.handleBlockbeat(beat)
9✔
2806
                        if err != nil {
9✔
2807
                                log.Errorf("Handle block=%v got err: %v",
×
2808
                                        bestHeight, err)
×
2809
                        }
×
2810

2811
                        // If as a result of this trigger, the contract is
2812
                        // fully resolved, then well exit.
2813
                        if c.state == 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
                        err := c.handleCoopCloseEvent(closeInfo)
5✔
2837
                        if err != nil {
5✔
2838
                                log.Errorf("Failed to handle coop close: %v",
×
2839
                                        err)
×
2840

×
2841
                                return
×
2842
                        }
×
2843

2844
                // We have broadcasted our commitment, and it is now confirmed
2845
                // on-chain.
2846
                case closeInfo := <-c.cfg.ChainEvents.LocalUnilateralClosure:
15✔
2847
                        if c.state != StateCommitmentBroadcasted {
19✔
2848
                                log.Errorf("ChannelArbitrator(%v): unexpected "+
4✔
2849
                                        "local on-chain channel close",
4✔
2850
                                        c.cfg.ChanPoint)
4✔
2851
                        }
4✔
2852

2853
                        err := c.handleLocalForceCloseEvent(closeInfo)
15✔
2854
                        if err != nil {
15✔
2855
                                log.Errorf("Failed to handle local force "+
×
2856
                                        "close: %v", err)
×
2857

×
2858
                                return
×
2859
                        }
×
2860

2861
                // The remote party has broadcast the commitment on-chain.
2862
                // We'll examine our state to determine if we need to act at
2863
                // all.
2864
                case uniClosure := <-c.cfg.ChainEvents.RemoteUnilateralClosure:
11✔
2865
                        err := c.handleRemoteForceCloseEvent(uniClosure)
11✔
2866
                        if err != nil {
13✔
2867
                                log.Errorf("Failed to handle remote force "+
2✔
2868
                                        "close: %v", err)
2✔
2869

2✔
2870
                                return
2✔
2871
                        }
2✔
2872

2873
                // The remote has breached the channel. As this is handled by
2874
                // the ChainWatcher and BreachArbitrator, we don't have to do
2875
                // anything in particular, so just advance our state and
2876
                // gracefully exit.
2877
                case breachInfo := <-c.cfg.ChainEvents.ContractBreach:
4✔
2878
                        err := c.handleContractBreach(breachInfo)
4✔
2879
                        if err != nil {
4✔
2880
                                log.Errorf("Failed to handle contract breach: "+
×
2881
                                        "%v", err)
×
2882

×
2883
                                return
×
2884
                        }
×
2885

2886
                // A new contract has just been resolved, we'll now check our
2887
                // log to see if all contracts have been resolved. If so, then
2888
                // we can exit as the contract is fully resolved.
2889
                case <-c.resolutionSignal:
7✔
2890
                        log.Infof("ChannelArbitrator(%v): a contract has been "+
7✔
2891
                                "fully resolved!", c.cfg.ChanPoint)
7✔
2892

7✔
2893
                        nextState, _, err := c.advanceState(
7✔
2894
                                uint32(bestHeight), chainTrigger, nil,
7✔
2895
                        )
7✔
2896
                        if err != nil {
7✔
2897
                                log.Errorf("Unable to advance state: %v", err)
×
2898
                        }
×
2899

2900
                        // If we don't have anything further to do after
2901
                        // advancing our state, then we'll exit.
2902
                        if nextState == StateFullyResolved {
10✔
2903
                                log.Infof("ChannelArbitrator(%v): all "+
3✔
2904
                                        "contracts fully resolved, exiting",
3✔
2905
                                        c.cfg.ChanPoint)
3✔
2906

3✔
2907
                                return
3✔
2908
                        }
3✔
2909

2910
                // We've just received a request to forcibly close out the
2911
                // channel. We'll
2912
                case closeReq := <-c.forceCloseReqs:
14✔
2913
                        log.Infof("ChannelArbitrator(%v): received force "+
14✔
2914
                                "close request", c.cfg.ChanPoint)
14✔
2915

14✔
2916
                        if c.state != StateDefault {
16✔
2917
                                select {
2✔
2918
                                case closeReq.closeTx <- nil:
2✔
2919
                                case <-c.quit:
×
2920
                                }
2921

2922
                                select {
2✔
2923
                                case closeReq.errResp <- errAlreadyForceClosed:
2✔
2924
                                case <-c.quit:
×
2925
                                }
2926

2927
                                continue
2✔
2928
                        }
2929

2930
                        nextState, closeTx, err := c.advanceState(
13✔
2931
                                uint32(bestHeight), userTrigger, nil,
13✔
2932
                        )
13✔
2933
                        if err != nil {
17✔
2934
                                log.Errorf("Unable to advance state: %v", err)
4✔
2935
                        }
4✔
2936

2937
                        select {
13✔
2938
                        case closeReq.closeTx <- closeTx:
13✔
2939
                        case <-c.quit:
×
2940
                                return
×
2941
                        }
2942

2943
                        select {
13✔
2944
                        case closeReq.errResp <- err:
13✔
2945
                        case <-c.quit:
×
2946
                                return
×
2947
                        }
2948

2949
                        // If we don't have anything further to do after
2950
                        // advancing our state, then we'll exit.
2951
                        if nextState == StateFullyResolved {
13✔
2952
                                log.Infof("ChannelArbitrator(%v): all "+
×
2953
                                        "contracts resolved, exiting",
×
2954
                                        c.cfg.ChanPoint)
×
2955
                                return
×
2956
                        }
×
2957

2958
                case <-c.quit:
42✔
2959
                        return
42✔
2960
                }
2961
        }
2962
}
2963

2964
// handleBlockbeat processes a newly received blockbeat by advancing the
2965
// arbitrator's internal state using the received block height.
2966
func (c *ChannelArbitrator) handleBlockbeat(beat chainio.Blockbeat) error {
9✔
2967
        // Notify we've processed the block.
9✔
2968
        defer c.NotifyBlockProcessed(beat, nil)
9✔
2969

9✔
2970
        // Perform a non-blocking read on the close events in case the channel
9✔
2971
        // is closed in this blockbeat.
9✔
2972
        c.receiveAndProcessCloseEvent()
9✔
2973

9✔
2974
        // Try to advance the state if we are in StateDefault.
9✔
2975
        if c.state == StateDefault {
17✔
2976
                // Now that a new block has arrived, we'll attempt to advance
8✔
2977
                // our state forward.
8✔
2978
                _, _, err := c.advanceState(
8✔
2979
                        uint32(beat.Height()), chainTrigger, nil,
8✔
2980
                )
8✔
2981
                if err != nil {
8✔
2982
                        return fmt.Errorf("unable to advance state: %w", err)
×
2983
                }
×
2984
        }
2985

2986
        // Launch all active resolvers when a new blockbeat is received.
2987
        c.launchResolvers()
9✔
2988

9✔
2989
        return nil
9✔
2990
}
2991

2992
// receiveAndProcessCloseEvent does a non-blocking read on all the channel
2993
// close event channels. If an event is received, it will be further processed.
2994
func (c *ChannelArbitrator) receiveAndProcessCloseEvent() {
9✔
2995
        select {
9✔
2996
        // Received a coop close event, we now mark the channel as resolved and
2997
        // exit.
2998
        case closeInfo := <-c.cfg.ChainEvents.CooperativeClosure:
×
2999
                err := c.handleCoopCloseEvent(closeInfo)
×
3000
                if err != nil {
×
3001
                        log.Errorf("Failed to handle coop close: %v", err)
×
3002
                        return
×
3003
                }
×
3004

3005
        // We have broadcast our commitment, and it is now confirmed onchain.
UNCOV
3006
        case closeInfo := <-c.cfg.ChainEvents.LocalUnilateralClosure:
×
UNCOV
3007
                if c.state != StateCommitmentBroadcasted {
×
3008
                        log.Errorf("ChannelArbitrator(%v): unexpected "+
×
3009
                                "local on-chain channel close", c.cfg.ChanPoint)
×
3010
                }
×
3011

UNCOV
3012
                err := c.handleLocalForceCloseEvent(closeInfo)
×
UNCOV
3013
                if err != nil {
×
3014
                        log.Errorf("Failed to handle local force close: %v",
×
3015
                                err)
×
3016

×
3017
                        return
×
3018
                }
×
3019

3020
        // The remote party has broadcast the commitment. We'll examine our
3021
        // state to determine if we need to act at all.
3022
        case uniClosure := <-c.cfg.ChainEvents.RemoteUnilateralClosure:
×
3023
                err := c.handleRemoteForceCloseEvent(uniClosure)
×
3024
                if err != nil {
×
3025
                        log.Errorf("Failed to handle remote force close: %v",
×
3026
                                err)
×
3027

×
3028
                        return
×
3029
                }
×
3030

3031
        // The remote has breached the channel! We now launch the breach
3032
        // contract resolvers.
3033
        case breachInfo := <-c.cfg.ChainEvents.ContractBreach:
×
3034
                err := c.handleContractBreach(breachInfo)
×
3035
                if err != nil {
×
3036
                        log.Errorf("Failed to handle contract breach: %v", err)
×
3037
                        return
×
3038
                }
×
3039

3040
        default:
9✔
3041
                log.Infof("ChannelArbitrator(%v) no close event",
9✔
3042
                        c.cfg.ChanPoint)
9✔
3043
        }
3044
}
3045

3046
// Name returns a human-readable string for this subsystem.
3047
//
3048
// NOTE: Part of chainio.Consumer interface.
3049
func (c *ChannelArbitrator) Name() string {
54✔
3050
        return fmt.Sprintf("ChannelArbitrator(%v)", c.cfg.ChanPoint)
54✔
3051
}
54✔
3052

3053
// checkLegacyBreach returns StateFullyResolved if the channel was closed with
3054
// a breach transaction before the channel arbitrator launched its own breach
3055
// resolver. StateContractClosed is returned if this is a modern breach close
3056
// with a breach resolver. StateError is returned if the log lookup failed.
3057
func (c *ChannelArbitrator) checkLegacyBreach() (ArbitratorState, error) {
5✔
3058
        // A previous version of the channel arbitrator would make the breach
5✔
3059
        // close skip to StateFullyResolved. If there are no contract
5✔
3060
        // resolutions in the bolt arbitrator log, then this is an older breach
5✔
3061
        // close. Otherwise, if there are resolutions, the state should advance
5✔
3062
        // to StateContractClosed.
5✔
3063
        _, err := c.log.FetchContractResolutions()
5✔
3064
        if err == errNoResolutions {
5✔
3065
                // This is an older breach close still in the database.
×
3066
                return StateFullyResolved, nil
×
3067
        } else if err != nil {
5✔
3068
                return StateError, err
×
3069
        }
×
3070

3071
        // This is a modern breach close with resolvers.
3072
        return StateContractClosed, nil
5✔
3073
}
3074

3075
// sweepRequest wraps the arguments used when calling `SweepInput`.
3076
type sweepRequest struct {
3077
        // input is the input to be swept.
3078
        input input.Input
3079

3080
        // params holds the sweeping parameters.
3081
        params sweep.Params
3082
}
3083

3084
// createSweepRequest creates an anchor sweeping request for a particular
3085
// version (local/remote/remote pending) of the commitment.
3086
func (c *ChannelArbitrator) createSweepRequest(
3087
        anchor *lnwallet.AnchorResolution, htlcs htlcSet, anchorPath string,
3088
        heightHint uint32) (sweepRequest, error) {
11✔
3089

11✔
3090
        // Use the chan id as the exclusive group. This prevents any of the
11✔
3091
        // anchors from being batched together.
11✔
3092
        exclusiveGroup := c.cfg.ShortChanID.ToUint64()
11✔
3093

11✔
3094
        // Find the deadline for this specific anchor.
11✔
3095
        deadline, value, err := c.findCommitmentDeadlineAndValue(
11✔
3096
                heightHint, htlcs,
11✔
3097
        )
11✔
3098
        if err != nil {
11✔
3099
                return sweepRequest{}, err
×
3100
        }
×
3101

3102
        // If we cannot find a deadline, it means there's no HTLCs at stake,
3103
        // which means we can relax our anchor sweeping conditions as we don't
3104
        // have any time sensitive outputs to sweep. However we need to
3105
        // register the anchor output with the sweeper so we are later able to
3106
        // bump the close fee.
3107
        if deadline.IsNone() {
17✔
3108
                log.Infof("ChannelArbitrator(%v): no HTLCs at stake, "+
6✔
3109
                        "sweeping anchor with default deadline",
6✔
3110
                        c.cfg.ChanPoint)
6✔
3111
        }
6✔
3112

3113
        witnessType := input.CommitmentAnchor
11✔
3114

11✔
3115
        // For taproot channels, we need to use the proper witness type.
11✔
3116
        if txscript.IsPayToTaproot(
11✔
3117
                anchor.AnchorSignDescriptor.Output.PkScript,
11✔
3118
        ) {
14✔
3119

3✔
3120
                witnessType = input.TaprootAnchorSweepSpend
3✔
3121
        }
3✔
3122

3123
        // Prepare anchor output for sweeping.
3124
        anchorInput := input.MakeBaseInput(
11✔
3125
                &anchor.CommitAnchor,
11✔
3126
                witnessType,
11✔
3127
                &anchor.AnchorSignDescriptor,
11✔
3128
                heightHint,
11✔
3129
                &input.TxInfo{
11✔
3130
                        Fee:    anchor.CommitFee,
11✔
3131
                        Weight: anchor.CommitWeight,
11✔
3132
                },
11✔
3133
        )
11✔
3134

11✔
3135
        // If we have a deadline, we'll use it to calculate the deadline
11✔
3136
        // height, otherwise default to none.
11✔
3137
        deadlineDesc := "None"
11✔
3138
        deadlineHeight := fn.MapOption(func(d int32) int32 {
19✔
3139
                deadlineDesc = fmt.Sprintf("%d", d)
8✔
3140

8✔
3141
                return d + int32(heightHint)
8✔
3142
        })(deadline)
8✔
3143

3144
        // Calculate the budget based on the value under protection, which is
3145
        // the sum of all HTLCs on this commitment subtracted by their budgets.
3146
        // The anchor output in itself has a small output value of 330 sats so
3147
        // we also include it in the budget to pay for the cpfp transaction.
3148
        budget := calculateBudget(
11✔
3149
                value, c.cfg.Budget.AnchorCPFPRatio, c.cfg.Budget.AnchorCPFP,
11✔
3150
        ) + AnchorOutputValue
11✔
3151

11✔
3152
        log.Infof("ChannelArbitrator(%v): offering anchor from %s commitment "+
11✔
3153
                "%v to sweeper with deadline=%v, budget=%v", c.cfg.ChanPoint,
11✔
3154
                anchorPath, anchor.CommitAnchor, deadlineDesc, budget)
11✔
3155

11✔
3156
        // Sweep anchor output with a confirmation target fee preference.
11✔
3157
        // Because this is a cpfp-operation, the anchor will only be attempted
11✔
3158
        // to sweep when the current fee estimate for the confirmation target
11✔
3159
        // exceeds the commit fee rate.
11✔
3160
        return sweepRequest{
11✔
3161
                input: &anchorInput,
11✔
3162
                params: sweep.Params{
11✔
3163
                        ExclusiveGroup: &exclusiveGroup,
11✔
3164
                        Budget:         budget,
11✔
3165
                        DeadlineHeight: deadlineHeight,
11✔
3166
                },
11✔
3167
        }, nil
11✔
3168
}
3169

3170
// prepareAnchorSweeps creates a list of requests to be used by the sweeper for
3171
// all possible commitment versions.
3172
func (c *ChannelArbitrator) prepareAnchorSweeps(heightHint uint32,
3173
        anchors *lnwallet.AnchorResolutions) ([]sweepRequest, error) {
22✔
3174

22✔
3175
        // requests holds all the possible anchor sweep requests. We can have
22✔
3176
        // up to 3 different versions of commitments (local/remote/remote
22✔
3177
        // dangling) to be CPFPed by the anchors.
22✔
3178
        requests := make([]sweepRequest, 0, 3)
22✔
3179

22✔
3180
        // remotePendingReq holds the request for sweeping the anchor output on
22✔
3181
        // the remote pending commitment. It's only set when there's an actual
22✔
3182
        // pending remote commitment and it's used to decide whether we need to
22✔
3183
        // update the fee budget when sweeping the anchor output on the local
22✔
3184
        // commitment.
22✔
3185
        remotePendingReq := fn.None[sweepRequest]()
22✔
3186

22✔
3187
        // First we check on the remote pending commitment and optionally
22✔
3188
        // create an anchor sweeping request.
22✔
3189
        htlcs, ok := c.activeHTLCs[RemotePendingHtlcSet]
22✔
3190
        if ok && anchors.RemotePending != nil {
24✔
3191
                req, err := c.createSweepRequest(
2✔
3192
                        anchors.RemotePending, htlcs, "remote pending",
2✔
3193
                        heightHint,
2✔
3194
                )
2✔
3195
                if err != nil {
2✔
3196
                        return nil, err
×
3197
                }
×
3198

3199
                // Save the request.
3200
                requests = append(requests, req)
2✔
3201

2✔
3202
                // Set the optional variable.
2✔
3203
                remotePendingReq = fn.Some(req)
2✔
3204
        }
3205

3206
        // Check the local commitment and optionally create an anchor sweeping
3207
        // request. The params used in this request will be influenced by the
3208
        // anchor sweeping request made from the pending remote commitment.
3209
        htlcs, ok = c.activeHTLCs[LocalHtlcSet]
22✔
3210
        if ok && anchors.Local != nil {
28✔
3211
                req, err := c.createSweepRequest(
6✔
3212
                        anchors.Local, htlcs, "local", heightHint,
6✔
3213
                )
6✔
3214
                if err != nil {
6✔
3215
                        return nil, err
×
3216
                }
×
3217

3218
                // If there's an anchor sweeping request from the pending
3219
                // remote commitment, we will compare its budget against the
3220
                // budget used here and choose the params that has a larger
3221
                // budget. The deadline when choosing the remote pending budget
3222
                // instead of the local one will always be earlier or equal to
3223
                // the local deadline because outgoing HTLCs are resolved on
3224
                // the local commitment first before they are removed from the
3225
                // remote one.
3226
                remotePendingReq.WhenSome(func(s sweepRequest) {
8✔
3227
                        if s.params.Budget <= req.params.Budget {
3✔
3228
                                return
1✔
3229
                        }
1✔
3230

3231
                        log.Infof("ChannelArbitrator(%v): replaced local "+
1✔
3232
                                "anchor(%v) sweep params with pending remote "+
1✔
3233
                                "anchor sweep params, \nold:[%v], \nnew:[%v]",
1✔
3234
                                c.cfg.ChanPoint, anchors.Local.CommitAnchor,
1✔
3235
                                req.params, s.params)
1✔
3236

1✔
3237
                        req.params = s.params
1✔
3238
                })
3239

3240
                // Save the request.
3241
                requests = append(requests, req)
6✔
3242
        }
3243

3244
        // Check the remote commitment and create an anchor sweeping request if
3245
        // needed.
3246
        htlcs, ok = c.activeHTLCs[RemoteHtlcSet]
22✔
3247
        if ok && anchors.Remote != nil {
28✔
3248
                req, err := c.createSweepRequest(
6✔
3249
                        anchors.Remote, htlcs, "remote", heightHint,
6✔
3250
                )
6✔
3251
                if err != nil {
6✔
3252
                        return nil, err
×
3253
                }
×
3254

3255
                requests = append(requests, req)
6✔
3256
        }
3257

3258
        return requests, nil
22✔
3259
}
3260

3261
// failIncomingDust resolves the incoming dust HTLCs because they do not have
3262
// an output on the commitment transaction and cannot be resolved onchain. We
3263
// mark them as failed here.
3264
func (c *ChannelArbitrator) failIncomingDust(
3265
        incomingDustHTLCs []channeldb.HTLC) error {
13✔
3266

13✔
3267
        for _, htlc := range incomingDustHTLCs {
17✔
3268
                if !htlc.Incoming || htlc.OutputIndex >= 0 {
4✔
3269
                        return fmt.Errorf("htlc with index %v is not incoming "+
×
3270
                                "dust", htlc.OutputIndex)
×
3271
                }
×
3272

3273
                key := models.CircuitKey{
4✔
3274
                        ChanID: c.cfg.ShortChanID,
4✔
3275
                        HtlcID: htlc.HtlcIndex,
4✔
3276
                }
4✔
3277

4✔
3278
                // Mark this dust htlc as final failed.
4✔
3279
                chainArbCfg := c.cfg.ChainArbitratorConfig
4✔
3280
                err := chainArbCfg.PutFinalHtlcOutcome(
4✔
3281
                        key.ChanID, key.HtlcID, false,
4✔
3282
                )
4✔
3283
                if err != nil {
4✔
3284
                        return err
×
3285
                }
×
3286

3287
                // Send notification.
3288
                chainArbCfg.HtlcNotifier.NotifyFinalHtlcEvent(
4✔
3289
                        key,
4✔
3290
                        channeldb.FinalHtlcInfo{
4✔
3291
                                Settled:  false,
4✔
3292
                                Offchain: false,
4✔
3293
                        },
4✔
3294
                )
4✔
3295
        }
3296

3297
        return nil
13✔
3298
}
3299

3300
// abandonForwards cancels back the incoming HTLCs for their corresponding
3301
// outgoing HTLCs. We use a set here to avoid sending duplicate failure messages
3302
// for the same HTLC. This also needs to be done for locally initiated outgoing
3303
// HTLCs they are special cased in the switch.
3304
func (c *ChannelArbitrator) abandonForwards(htlcs fn.Set[uint64]) error {
16✔
3305
        log.Debugf("ChannelArbitrator(%v): cancelling back %v incoming "+
16✔
3306
                "HTLC(s)", c.cfg.ChanPoint,
16✔
3307
                len(htlcs))
16✔
3308

16✔
3309
        msgsToSend := make([]ResolutionMsg, 0, len(htlcs))
16✔
3310
        failureMsg := &lnwire.FailPermanentChannelFailure{}
16✔
3311

16✔
3312
        for idx := range htlcs {
29✔
3313
                failMsg := ResolutionMsg{
13✔
3314
                        SourceChan: c.cfg.ShortChanID,
13✔
3315
                        HtlcIndex:  idx,
13✔
3316
                        Failure:    failureMsg,
13✔
3317
                }
13✔
3318

13✔
3319
                msgsToSend = append(msgsToSend, failMsg)
13✔
3320
        }
13✔
3321

3322
        // Send the msges to the switch, if there are any.
3323
        if len(msgsToSend) == 0 {
22✔
3324
                return nil
6✔
3325
        }
6✔
3326

3327
        log.Debugf("ChannelArbitrator(%v): sending resolution message=%v",
13✔
3328
                c.cfg.ChanPoint, lnutils.SpewLogClosure(msgsToSend))
13✔
3329

13✔
3330
        err := c.cfg.DeliverResolutionMsg(msgsToSend...)
13✔
3331
        if err != nil {
13✔
3332
                log.Errorf("Unable to send resolution msges to switch: %v", err)
×
3333
                return err
×
3334
        }
×
3335

3336
        return nil
13✔
3337
}
3338

3339
// handleCoopCloseEvent takes a coop close event from ChainEvents, marks the
3340
// channel as closed and advances the state.
3341
func (c *ChannelArbitrator) handleCoopCloseEvent(
3342
        closeInfo *CooperativeCloseInfo) error {
5✔
3343

5✔
3344
        log.Infof("ChannelArbitrator(%v) marking channel cooperatively closed "+
5✔
3345
                "at height %v", c.cfg.ChanPoint, closeInfo.CloseHeight)
5✔
3346

5✔
3347
        err := c.cfg.MarkChannelClosed(
5✔
3348
                closeInfo.ChannelCloseSummary,
5✔
3349
                channeldb.ChanStatusCoopBroadcasted,
5✔
3350
        )
5✔
3351
        if err != nil {
5✔
3352
                return fmt.Errorf("unable to mark channel closed: %w", err)
×
3353
        }
×
3354

3355
        // We'll now advance our state machine until it reaches a terminal
3356
        // state, and the channel is marked resolved.
3357
        _, _, err = c.advanceState(closeInfo.CloseHeight, coopCloseTrigger, nil)
5✔
3358
        if err != nil {
6✔
3359
                log.Errorf("Unable to advance state: %v", err)
1✔
3360
        }
1✔
3361

3362
        return nil
2✔
3363
}
3364

3365
// handleLocalForceCloseEvent takes a local force close event from ChainEvents,
3366
// saves the contract resolutions to disk, mark the channel as closed and
3367
// advance the state.
3368
func (c *ChannelArbitrator) handleLocalForceCloseEvent(
3369
        closeInfo *LocalUnilateralCloseInfo) error {
15✔
3370

15✔
3371
        closeTx := closeInfo.CloseTx
15✔
3372

15✔
3373
        resolutions, err := closeInfo.ContractResolutions.
15✔
3374
                UnwrapOrErr(
15✔
3375
                        fmt.Errorf("resolutions not found"),
15✔
3376
                )
15✔
3377
        if err != nil {
15✔
3378
                return fmt.Errorf("unable to get resolutions: %w", err)
×
3379
        }
×
3380

3381
        // We make sure that the htlc resolutions are present
3382
        // otherwise we would panic dereferencing the pointer.
3383
        //
3384
        // TODO(ziggie): Refactor ContractResolutions to use
3385
        // options.
3386
        if resolutions.HtlcResolutions == nil {
15✔
3387
                return fmt.Errorf("htlc resolutions is nil")
×
3388
        }
×
3389

3390
        log.Infof("ChannelArbitrator(%v): local force close tx=%v confirmed",
15✔
3391
                c.cfg.ChanPoint, closeTx.TxHash())
15✔
3392

15✔
3393
        contractRes := &ContractResolutions{
15✔
3394
                CommitHash:       closeTx.TxHash(),
15✔
3395
                CommitResolution: resolutions.CommitResolution,
15✔
3396
                HtlcResolutions:  *resolutions.HtlcResolutions,
15✔
3397
                AnchorResolution: resolutions.AnchorResolution,
15✔
3398
        }
15✔
3399

15✔
3400
        // When processing a unilateral close event, we'll transition to the
15✔
3401
        // ContractClosed state. We'll log out the set of resolutions such that
15✔
3402
        // they are available to fetch in that state, we'll also write the
15✔
3403
        // commit set so we can reconstruct our chain actions on restart.
15✔
3404
        err = c.log.LogContractResolutions(contractRes)
15✔
3405
        if err != nil {
15✔
3406
                return fmt.Errorf("unable to write resolutions: %w", err)
×
3407
        }
×
3408

3409
        err = c.log.InsertConfirmedCommitSet(&closeInfo.CommitSet)
15✔
3410
        if err != nil {
15✔
3411
                return fmt.Errorf("unable to write commit set: %w", err)
×
3412
        }
×
3413

3414
        // After the set of resolutions are successfully logged, we can safely
3415
        // close the channel. After this succeeds we won't be getting chain
3416
        // events anymore, so we must make sure we can recover on restart after
3417
        // it is marked closed. If the next state transition fails, we'll start
3418
        // up in the prior state again, and we won't be longer getting chain
3419
        // events. In this case we must manually re-trigger the state
3420
        // transition into StateContractClosed based on the close status of the
3421
        // channel.
3422
        err = c.cfg.MarkChannelClosed(
15✔
3423
                closeInfo.ChannelCloseSummary,
15✔
3424
                channeldb.ChanStatusLocalCloseInitiator,
15✔
3425
        )
15✔
3426
        if err != nil {
15✔
3427
                return fmt.Errorf("unable to mark channel closed: %w", err)
×
3428
        }
×
3429

3430
        // We'll now advance our state machine until it reaches a terminal
3431
        // state.
3432
        _, _, err = c.advanceState(
15✔
3433
                uint32(closeInfo.SpendingHeight),
15✔
3434
                localCloseTrigger, &closeInfo.CommitSet,
15✔
3435
        )
15✔
3436
        if err != nil {
16✔
3437
                log.Errorf("Unable to advance state: %v", err)
1✔
3438
        }
1✔
3439

3440
        return nil
15✔
3441
}
3442

3443
// handleRemoteForceCloseEvent takes a remote force close event from
3444
// ChainEvents, saves the contract resolutions to disk, mark the channel as
3445
// closed and advance the state.
3446
func (c *ChannelArbitrator) handleRemoteForceCloseEvent(
3447
        closeInfo *RemoteUnilateralCloseInfo) error {
11✔
3448

11✔
3449
        log.Infof("ChannelArbitrator(%v): remote party has force closed "+
11✔
3450
                "channel at height %v", c.cfg.ChanPoint,
11✔
3451
                closeInfo.SpendingHeight)
11✔
3452

11✔
3453
        // If we don't have a self output, and there are no active HTLC's, then
11✔
3454
        // we can immediately mark the contract as fully resolved and exit.
11✔
3455
        contractRes := &ContractResolutions{
11✔
3456
                CommitHash:       *closeInfo.SpenderTxHash,
11✔
3457
                CommitResolution: closeInfo.CommitResolution,
11✔
3458
                HtlcResolutions:  *closeInfo.HtlcResolutions,
11✔
3459
                AnchorResolution: closeInfo.AnchorResolution,
11✔
3460
        }
11✔
3461

11✔
3462
        // When processing a unilateral close event, we'll transition to the
11✔
3463
        // ContractClosed state. We'll log out the set of resolutions such that
11✔
3464
        // they are available to fetch in that state, we'll also write the
11✔
3465
        // commit set so we can reconstruct our chain actions on restart.
11✔
3466
        err := c.log.LogContractResolutions(contractRes)
11✔
3467
        if err != nil {
12✔
3468
                return fmt.Errorf("unable to write resolutions: %w", err)
1✔
3469
        }
1✔
3470

3471
        err = c.log.InsertConfirmedCommitSet(&closeInfo.CommitSet)
10✔
3472
        if err != nil {
10✔
3473
                return fmt.Errorf("unable to write commit set: %w", err)
×
3474
        }
×
3475

3476
        // After the set of resolutions are successfully logged, we can safely
3477
        // close the channel. After this succeeds we won't be getting chain
3478
        // events anymore, so we must make sure we can recover on restart after
3479
        // it is marked closed. If the next state transition fails, we'll start
3480
        // up in the prior state again, and we won't be longer getting chain
3481
        // events. In this case we must manually re-trigger the state
3482
        // transition into StateContractClosed based on the close status of the
3483
        // channel.
3484
        closeSummary := &closeInfo.ChannelCloseSummary
10✔
3485
        err = c.cfg.MarkChannelClosed(
10✔
3486
                closeSummary,
10✔
3487
                channeldb.ChanStatusRemoteCloseInitiator,
10✔
3488
        )
10✔
3489
        if err != nil {
11✔
3490
                return fmt.Errorf("unable to mark channel closed: %w", err)
1✔
3491
        }
1✔
3492

3493
        // We'll now advance our state machine until it reaches a terminal
3494
        // state.
3495
        _, _, err = c.advanceState(
9✔
3496
                uint32(closeInfo.SpendingHeight),
9✔
3497
                remoteCloseTrigger, &closeInfo.CommitSet,
9✔
3498
        )
9✔
3499
        if err != nil {
11✔
3500
                log.Errorf("Unable to advance state: %v", err)
2✔
3501
        }
2✔
3502

3503
        return nil
9✔
3504
}
3505

3506
// handleContractBreach takes a breach close event from ChainEvents, saves the
3507
// contract resolutions to disk, mark the channel as closed and advance the
3508
// state.
3509
func (c *ChannelArbitrator) handleContractBreach(
3510
        breachInfo *BreachCloseInfo) error {
4✔
3511

4✔
3512
        closeSummary := &breachInfo.CloseSummary
4✔
3513

4✔
3514
        log.Infof("ChannelArbitrator(%v): remote party has breached channel "+
4✔
3515
                "at height %v!", c.cfg.ChanPoint, closeSummary.CloseHeight)
4✔
3516

4✔
3517
        // In the breach case, we'll only have anchor and breach resolutions.
4✔
3518
        contractRes := &ContractResolutions{
4✔
3519
                CommitHash:       breachInfo.CommitHash,
4✔
3520
                BreachResolution: breachInfo.BreachResolution,
4✔
3521
                AnchorResolution: breachInfo.AnchorResolution,
4✔
3522
        }
4✔
3523

4✔
3524
        // We'll transition to the ContractClosed state and log the set of
4✔
3525
        // resolutions such that they can be turned into resolvers later on.
4✔
3526
        // We'll also insert the CommitSet of the latest set of commitments.
4✔
3527
        err := c.log.LogContractResolutions(contractRes)
4✔
3528
        if err != nil {
4✔
3529
                return fmt.Errorf("unable to write resolutions: %w", err)
×
3530
        }
×
3531

3532
        err = c.log.InsertConfirmedCommitSet(&breachInfo.CommitSet)
4✔
3533
        if err != nil {
4✔
3534
                return fmt.Errorf("unable to write commit set: %w", err)
×
3535
        }
×
3536

3537
        // The channel is finally marked pending closed here as the
3538
        // BreachArbitrator and channel arbitrator have persisted the relevant
3539
        // states.
3540
        err = c.cfg.MarkChannelClosed(
4✔
3541
                closeSummary, channeldb.ChanStatusRemoteCloseInitiator,
4✔
3542
        )
4✔
3543
        if err != nil {
4✔
3544
                return fmt.Errorf("unable to mark channel closed: %w", err)
×
3545
        }
×
3546

3547
        log.Infof("Breached channel=%v marked pending-closed",
4✔
3548
                breachInfo.BreachResolution.FundingOutPoint)
4✔
3549

4✔
3550
        // We'll advance our state machine until it reaches a terminal state.
4✔
3551
        _, _, err = c.advanceState(
4✔
3552
                closeSummary.CloseHeight, breachCloseTrigger,
4✔
3553
                &breachInfo.CommitSet,
4✔
3554
        )
4✔
3555
        if err != nil {
4✔
3556
                log.Errorf("Unable to advance state: %v", err)
×
3557
        }
×
3558

3559
        return nil
4✔
3560
}
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