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

lightningnetwork / lnd / 15782265189

20 Jun 2025 03:23PM UTC coverage: 68.14% (-0.003%) from 68.143%
15782265189

Pull #9958

github

web-flow
Merge ae1a1d1ba into 7857d2c6a
Pull Request #9958: improve CloseChannel docs

134478 of 197355 relevant lines covered (68.14%)

22170.18 hits per line

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

77.69
/htlcswitch/link.go
1
package htlcswitch
2

3
import (
4
        "bytes"
5
        "context"
6
        crand "crypto/rand"
7
        "crypto/sha256"
8
        "errors"
9
        "fmt"
10
        prand "math/rand"
11
        "sync"
12
        "sync/atomic"
13
        "time"
14

15
        "github.com/btcsuite/btcd/btcutil"
16
        "github.com/btcsuite/btcd/wire"
17
        "github.com/btcsuite/btclog/v2"
18
        "github.com/lightningnetwork/lnd/channeldb"
19
        "github.com/lightningnetwork/lnd/contractcourt"
20
        "github.com/lightningnetwork/lnd/fn/v2"
21
        "github.com/lightningnetwork/lnd/graph/db/models"
22
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
23
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
24
        "github.com/lightningnetwork/lnd/input"
25
        "github.com/lightningnetwork/lnd/invoices"
26
        "github.com/lightningnetwork/lnd/lnpeer"
27
        "github.com/lightningnetwork/lnd/lntypes"
28
        "github.com/lightningnetwork/lnd/lnutils"
29
        "github.com/lightningnetwork/lnd/lnwallet"
30
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
31
        "github.com/lightningnetwork/lnd/lnwire"
32
        "github.com/lightningnetwork/lnd/queue"
33
        "github.com/lightningnetwork/lnd/record"
34
        "github.com/lightningnetwork/lnd/ticker"
35
        "github.com/lightningnetwork/lnd/tlv"
36
)
37

38
func init() {
16✔
39
        prand.Seed(time.Now().UnixNano())
16✔
40
}
16✔
41

42
const (
43
        // DefaultMaxOutgoingCltvExpiry is the maximum outgoing time lock that
44
        // the node accepts for forwarded payments. The value is relative to the
45
        // current block height. The reason to have a maximum is to prevent
46
        // funds getting locked up unreasonably long. Otherwise, an attacker
47
        // willing to lock its own funds too, could force the funds of this node
48
        // to be locked up for an indefinite (max int32) number of blocks.
49
        //
50
        // The value 2016 corresponds to on average two weeks worth of blocks
51
        // and is based on the maximum number of hops (20), the default CLTV
52
        // delta (40), and some extra margin to account for the other lightning
53
        // implementations and past lnd versions which used to have a default
54
        // CLTV delta of 144.
55
        DefaultMaxOutgoingCltvExpiry = 2016
56

57
        // DefaultMinLinkFeeUpdateTimeout represents the minimum interval in
58
        // which a link should propose to update its commitment fee rate.
59
        DefaultMinLinkFeeUpdateTimeout = 10 * time.Minute
60

61
        // DefaultMaxLinkFeeUpdateTimeout represents the maximum interval in
62
        // which a link should propose to update its commitment fee rate.
63
        DefaultMaxLinkFeeUpdateTimeout = 60 * time.Minute
64

65
        // DefaultMaxLinkFeeAllocation is the highest allocation we'll allow
66
        // a channel's commitment fee to be of its balance. This only applies to
67
        // the initiator of the channel.
68
        DefaultMaxLinkFeeAllocation float64 = 0.5
69
)
70

71
// ExpectedFee computes the expected fee for a given htlc amount. The value
72
// returned from this function is to be used as a sanity check when forwarding
73
// HTLC's to ensure that an incoming HTLC properly adheres to our propagated
74
// forwarding policy.
75
//
76
// TODO(roasbeef): also add in current available channel bandwidth, inverse
77
// func
78
func ExpectedFee(f models.ForwardingPolicy,
79
        htlcAmt lnwire.MilliSatoshi) lnwire.MilliSatoshi {
81✔
80

81✔
81
        return f.BaseFee + (htlcAmt*f.FeeRate)/1000000
81✔
82
}
81✔
83

84
// ChannelLinkConfig defines the configuration for the channel link. ALL
85
// elements within the configuration MUST be non-nil for channel link to carry
86
// out its duties.
87
type ChannelLinkConfig struct {
88
        // FwrdingPolicy is the initial forwarding policy to be used when
89
        // deciding whether to forwarding incoming HTLC's or not. This value
90
        // can be updated with subsequent calls to UpdateForwardingPolicy
91
        // targeted at a given ChannelLink concrete interface implementation.
92
        FwrdingPolicy models.ForwardingPolicy
93

94
        // Circuits provides restricted access to the switch's circuit map,
95
        // allowing the link to open and close circuits.
96
        Circuits CircuitModifier
97

98
        // BestHeight returns the best known height.
99
        BestHeight func() uint32
100

101
        // ForwardPackets attempts to forward the batch of htlcs through the
102
        // switch. The function returns and error in case it fails to send one or
103
        // more packets. The link's quit signal should be provided to allow
104
        // cancellation of forwarding during link shutdown.
105
        ForwardPackets func(<-chan struct{}, bool, ...*htlcPacket) error
106

107
        // DecodeHopIterators facilitates batched decoding of HTLC Sphinx onion
108
        // blobs, which are then used to inform how to forward an HTLC.
109
        //
110
        // NOTE: This function assumes the same set of readers and preimages
111
        // are always presented for the same identifier.
112
        DecodeHopIterators func([]byte, []hop.DecodeHopIteratorRequest) (
113
                []hop.DecodeHopIteratorResponse, error)
114

115
        // ExtractErrorEncrypter function is responsible for decoding HTLC
116
        // Sphinx onion blob, and creating onion failure obfuscator.
117
        ExtractErrorEncrypter hop.ErrorEncrypterExtracter
118

119
        // FetchLastChannelUpdate retrieves the latest routing policy for a
120
        // target channel. This channel will typically be the outgoing channel
121
        // specified when we receive an incoming HTLC.  This will be used to
122
        // provide payment senders our latest policy when sending encrypted
123
        // error messages.
124
        FetchLastChannelUpdate func(lnwire.ShortChannelID) (
125
                *lnwire.ChannelUpdate1, error)
126

127
        // Peer is a lightning network node with which we have the channel link
128
        // opened.
129
        Peer lnpeer.Peer
130

131
        // Registry is a sub-system which responsible for managing the invoices
132
        // in thread-safe manner.
133
        Registry InvoiceDatabase
134

135
        // PreimageCache is a global witness beacon that houses any new
136
        // preimages discovered by other links. We'll use this to add new
137
        // witnesses that we discover which will notify any sub-systems
138
        // subscribed to new events.
139
        PreimageCache contractcourt.WitnessBeacon
140

141
        // OnChannelFailure is a function closure that we'll call if the
142
        // channel failed for some reason. Depending on the severity of the
143
        // error, the closure potentially must force close this channel and
144
        // disconnect the peer.
145
        //
146
        // NOTE: The method must return in order for the ChannelLink to be able
147
        // to shut down properly.
148
        OnChannelFailure func(lnwire.ChannelID, lnwire.ShortChannelID,
149
                LinkFailureError)
150

151
        // UpdateContractSignals is a function closure that we'll use to update
152
        // outside sub-systems with this channel's latest ShortChannelID.
153
        UpdateContractSignals func(*contractcourt.ContractSignals) error
154

155
        // NotifyContractUpdate is a function closure that we'll use to update
156
        // the contractcourt and more specifically the ChannelArbitrator of the
157
        // latest channel state.
158
        NotifyContractUpdate func(*contractcourt.ContractUpdate) error
159

160
        // ChainEvents is an active subscription to the chain watcher for this
161
        // channel to be notified of any on-chain activity related to this
162
        // channel.
163
        ChainEvents *contractcourt.ChainEventSubscription
164

165
        // FeeEstimator is an instance of a live fee estimator which will be
166
        // used to dynamically regulate the current fee of the commitment
167
        // transaction to ensure timely confirmation.
168
        FeeEstimator chainfee.Estimator
169

170
        // hodl.Mask is a bitvector composed of hodl.Flags, specifying breakpoints
171
        // for HTLC forwarding internal to the switch.
172
        //
173
        // NOTE: This should only be used for testing.
174
        HodlMask hodl.Mask
175

176
        // SyncStates is used to indicate that we need send the channel
177
        // reestablishment message to the remote peer. It should be done if our
178
        // clients have been restarted, or remote peer have been reconnected.
179
        SyncStates bool
180

181
        // BatchTicker is the ticker that determines the interval that we'll
182
        // use to check the batch to see if there're any updates we should
183
        // flush out. By batching updates into a single commit, we attempt to
184
        // increase throughput by maximizing the number of updates coalesced
185
        // into a single commit.
186
        BatchTicker ticker.Ticker
187

188
        // FwdPkgGCTicker is the ticker determining the frequency at which
189
        // garbage collection of forwarding packages occurs. We use a
190
        // time-based approach, as opposed to block epochs, as to not hinder
191
        // syncing.
192
        FwdPkgGCTicker ticker.Ticker
193

194
        // PendingCommitTicker is a ticker that allows the link to determine if
195
        // a locally initiated commitment dance gets stuck waiting for the
196
        // remote party to revoke.
197
        PendingCommitTicker ticker.Ticker
198

199
        // BatchSize is the max size of a batch of updates done to the link
200
        // before we do a state update.
201
        BatchSize uint32
202

203
        // UnsafeReplay will cause a link to replay the adds in its latest
204
        // commitment txn after the link is restarted. This should only be used
205
        // in testing, it is here to ensure the sphinx replay detection on the
206
        // receiving node is persistent.
207
        UnsafeReplay bool
208

209
        // MinUpdateTimeout represents the minimum interval in which a link
210
        // will propose to update its commitment fee rate. A random timeout will
211
        // be selected between this and MaxUpdateTimeout.
212
        MinUpdateTimeout time.Duration
213

214
        // MaxUpdateTimeout represents the maximum interval in which a link
215
        // will propose to update its commitment fee rate. A random timeout will
216
        // be selected between this and MinUpdateTimeout.
217
        MaxUpdateTimeout time.Duration
218

219
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
220
        // an htlc where we don't offer an htlc anymore. This should be at least
221
        // the outgoing broadcast delta, because in any case we don't want to
222
        // risk offering an htlc that triggers channel closure.
223
        OutgoingCltvRejectDelta uint32
224

225
        // TowerClient is an optional engine that manages the signing,
226
        // encrypting, and uploading of justice transactions to the daemon's
227
        // configured set of watchtowers for legacy channels.
228
        TowerClient TowerClient
229

230
        // MaxOutgoingCltvExpiry is the maximum outgoing timelock that the link
231
        // should accept for a forwarded HTLC. The value is relative to the
232
        // current block height.
233
        MaxOutgoingCltvExpiry uint32
234

235
        // MaxFeeAllocation is the highest allocation we'll allow a channel's
236
        // commitment fee to be of its balance. This only applies to the
237
        // initiator of the channel.
238
        MaxFeeAllocation float64
239

240
        // MaxAnchorsCommitFeeRate is the max commitment fee rate we'll use as
241
        // the initiator for channels of the anchor type.
242
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
243

244
        // NotifyActiveLink allows the link to tell the ChannelNotifier when a
245
        // link is first started.
246
        NotifyActiveLink func(wire.OutPoint)
247

248
        // NotifyActiveChannel allows the link to tell the ChannelNotifier when
249
        // channels becomes active.
250
        NotifyActiveChannel func(wire.OutPoint)
251

252
        // NotifyInactiveChannel allows the switch to tell the ChannelNotifier
253
        // when channels become inactive.
254
        NotifyInactiveChannel func(wire.OutPoint)
255

256
        // NotifyInactiveLinkEvent allows the switch to tell the
257
        // ChannelNotifier when a channel link become inactive.
258
        NotifyInactiveLinkEvent func(wire.OutPoint)
259

260
        // HtlcNotifier is an instance of a htlcNotifier which we will pipe htlc
261
        // events through.
262
        HtlcNotifier htlcNotifier
263

264
        // FailAliasUpdate is a function used to fail an HTLC for an
265
        // option_scid_alias channel.
266
        FailAliasUpdate func(sid lnwire.ShortChannelID,
267
                incoming bool) *lnwire.ChannelUpdate1
268

269
        // GetAliases is used by the link and switch to fetch the set of
270
        // aliases for a given link.
271
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
272

273
        // PreviouslySentShutdown is an optional value that is set if, at the
274
        // time of the link being started, persisted shutdown info was found for
275
        // the channel. This value being set means that we previously sent a
276
        // Shutdown message to our peer, and so we should do so again on
277
        // re-establish and should not allow anymore HTLC adds on the outgoing
278
        // direction of the link.
279
        PreviouslySentShutdown fn.Option[lnwire.Shutdown]
280

281
        // Adds the option to disable forwarding payments in blinded routes
282
        // by failing back any blinding-related payloads as if they were
283
        // invalid.
284
        DisallowRouteBlinding bool
285

286
        // DisallowQuiescence is a flag that can be used to disable the
287
        // quiescence protocol.
288
        DisallowQuiescence bool
289

290
        // MaxFeeExposure is the threshold in milli-satoshis after which we'll
291
        // restrict the flow of HTLCs and fee updates.
292
        MaxFeeExposure lnwire.MilliSatoshi
293

294
        // ShouldFwdExpEndorsement is a closure that indicates whether the link
295
        // should forward experimental endorsement signals.
296
        ShouldFwdExpEndorsement func() bool
297

298
        // AuxTrafficShaper is an optional auxiliary traffic shaper that can be
299
        // used to manage the bandwidth of the link.
300
        AuxTrafficShaper fn.Option[AuxTrafficShaper]
301
}
302

303
// channelLink is the service which drives a channel's commitment update
304
// state-machine. In the event that an HTLC needs to be propagated to another
305
// link, the forward handler from config is used which sends HTLC to the
306
// switch. Additionally, the link encapsulate logic of commitment protocol
307
// message ordering and updates.
308
type channelLink struct {
309
        // The following fields are only meant to be used *atomically*
310
        started       int32
311
        reestablished int32
312
        shutdown      int32
313

314
        // failed should be set to true in case a link error happens, making
315
        // sure we don't process any more updates.
316
        failed bool
317

318
        // keystoneBatch represents a volatile list of keystones that must be
319
        // written before attempting to sign the next commitment txn. These
320
        // represent all the HTLC's forwarded to the link from the switch. Once
321
        // we lock them into our outgoing commitment, then the circuit has a
322
        // keystone, and is fully opened.
323
        keystoneBatch []Keystone
324

325
        // openedCircuits is the set of all payment circuits that will be open
326
        // once we make our next commitment. After making the commitment we'll
327
        // ACK all these from our mailbox to ensure that they don't get
328
        // re-delivered if we reconnect.
329
        openedCircuits []CircuitKey
330

331
        // closedCircuits is the set of all payment circuits that will be
332
        // closed once we make our next commitment. After taking the commitment
333
        // we'll ACK all these to ensure that they don't get re-delivered if we
334
        // reconnect.
335
        closedCircuits []CircuitKey
336

337
        // channel is a lightning network channel to which we apply htlc
338
        // updates.
339
        channel *lnwallet.LightningChannel
340

341
        // cfg is a structure which carries all dependable fields/handlers
342
        // which may affect behaviour of the service.
343
        cfg ChannelLinkConfig
344

345
        // mailBox is the main interface between the outside world and the
346
        // link. All incoming messages will be sent over this mailBox. Messages
347
        // include new updates from our connected peer, and new packets to be
348
        // forwarded sent by the switch.
349
        mailBox MailBox
350

351
        // upstream is a channel that new messages sent from the remote peer to
352
        // the local peer will be sent across.
353
        upstream chan lnwire.Message
354

355
        // downstream is a channel in which new multi-hop HTLC's to be
356
        // forwarded will be sent across. Messages from this channel are sent
357
        // by the HTLC switch.
358
        downstream chan *htlcPacket
359

360
        // updateFeeTimer is the timer responsible for updating the link's
361
        // commitment fee every time it fires.
362
        updateFeeTimer *time.Timer
363

364
        // uncommittedPreimages stores a list of all preimages that have been
365
        // learned since receiving the last CommitSig from the remote peer. The
366
        // batch will be flushed just before accepting the subsequent CommitSig
367
        // or on shutdown to avoid doing a write for each preimage received.
368
        uncommittedPreimages []lntypes.Preimage
369

370
        sync.RWMutex
371

372
        // hodlQueue is used to receive exit hop htlc resolutions from invoice
373
        // registry.
374
        hodlQueue *queue.ConcurrentQueue
375

376
        // hodlMap stores related htlc data for a circuit key. It allows
377
        // resolving those htlcs when we receive a message on hodlQueue.
378
        hodlMap map[models.CircuitKey]hodlHtlc
379

380
        // log is a link-specific logging instance.
381
        log btclog.Logger
382

383
        // isOutgoingAddBlocked tracks whether the channelLink can send an
384
        // UpdateAddHTLC.
385
        isOutgoingAddBlocked atomic.Bool
386

387
        // isIncomingAddBlocked tracks whether the channelLink can receive an
388
        // UpdateAddHTLC.
389
        isIncomingAddBlocked atomic.Bool
390

391
        // flushHooks is a hookMap that is triggered when we reach a channel
392
        // state with no live HTLCs.
393
        flushHooks hookMap
394

395
        // outgoingCommitHooks is a hookMap that is triggered after we send our
396
        // next CommitSig.
397
        outgoingCommitHooks hookMap
398

399
        // incomingCommitHooks is a hookMap that is triggered after we receive
400
        // our next CommitSig.
401
        incomingCommitHooks hookMap
402

403
        // quiescer is the state machine that tracks where this channel is with
404
        // respect to the quiescence protocol.
405
        quiescer Quiescer
406

407
        // quiescenceReqs is a queue of requests to quiesce this link. The
408
        // members of the queue are send-only channels we should call back with
409
        // the result.
410
        quiescenceReqs chan StfuReq
411

412
        // cg is a helper that encapsulates a wait group and quit channel and
413
        // allows contexts that either block or cancel on those depending on
414
        // the use case.
415
        cg *fn.ContextGuard
416
}
417

418
// hookMap is a data structure that is used to track the hooks that need to be
419
// called in various parts of the channelLink's lifecycle.
420
//
421
// WARNING: NOT thread-safe.
422
type hookMap struct {
423
        // allocIdx keeps track of the next id we haven't yet allocated.
424
        allocIdx atomic.Uint64
425

426
        // transient is a map of hooks that are only called the next time invoke
427
        // is called. These hooks are deleted during invoke.
428
        transient map[uint64]func()
429

430
        // newTransients is a channel that we use to accept new hooks into the
431
        // hookMap.
432
        newTransients chan func()
433
}
434

435
// newHookMap initializes a new empty hookMap.
436
func newHookMap() hookMap {
648✔
437
        return hookMap{
648✔
438
                allocIdx:      atomic.Uint64{},
648✔
439
                transient:     make(map[uint64]func()),
648✔
440
                newTransients: make(chan func()),
648✔
441
        }
648✔
442
}
648✔
443

444
// alloc allocates space in the hook map for the supplied hook, the second
445
// argument determines whether it goes into the transient or persistent part
446
// of the hookMap.
447
func (m *hookMap) alloc(hook func()) uint64 {
5✔
448
        // We assume we never overflow a uint64. Seems OK.
5✔
449
        hookID := m.allocIdx.Add(1)
5✔
450
        if hookID == 0 {
5✔
451
                panic("hookMap allocIdx overflow")
×
452
        }
453
        m.transient[hookID] = hook
5✔
454

5✔
455
        return hookID
5✔
456
}
457

458
// invoke is used on a hook map to call all the registered hooks and then clear
459
// out the transient hooks so they are not called again.
460
func (m *hookMap) invoke() {
2,774✔
461
        for _, hook := range m.transient {
2,779✔
462
                hook()
5✔
463
        }
5✔
464

465
        m.transient = make(map[uint64]func())
2,774✔
466
}
467

468
// hodlHtlc contains htlc data that is required for resolution.
469
type hodlHtlc struct {
470
        add        lnwire.UpdateAddHTLC
471
        sourceRef  channeldb.AddRef
472
        obfuscator hop.ErrorEncrypter
473
}
474

475
// NewChannelLink creates a new instance of a ChannelLink given a configuration
476
// and active channel that will be used to verify/apply updates to.
477
func NewChannelLink(cfg ChannelLinkConfig,
478
        channel *lnwallet.LightningChannel) ChannelLink {
218✔
479

218✔
480
        logPrefix := fmt.Sprintf("ChannelLink(%v):", channel.ChannelPoint())
218✔
481

218✔
482
        // If the max fee exposure isn't set, use the default.
218✔
483
        if cfg.MaxFeeExposure == 0 {
433✔
484
                cfg.MaxFeeExposure = DefaultMaxFeeExposure
215✔
485
        }
215✔
486

487
        var qsm Quiescer
218✔
488
        if !cfg.DisallowQuiescence {
436✔
489
                qsm = NewQuiescer(QuiescerCfg{
218✔
490
                        chanID: lnwire.NewChanIDFromOutPoint(
218✔
491
                                channel.ChannelPoint(),
218✔
492
                        ),
218✔
493
                        channelInitiator: channel.Initiator(),
218✔
494
                        sendMsg: func(s lnwire.Stfu) error {
223✔
495
                                return cfg.Peer.SendMessage(false, &s)
5✔
496
                        },
5✔
497
                        timeoutDuration: defaultQuiescenceTimeout,
498
                        onTimeout: func() {
2✔
499
                                cfg.Peer.Disconnect(ErrQuiescenceTimeout)
2✔
500
                        },
2✔
501
                })
502
        } else {
×
503
                qsm = &quiescerNoop{}
×
504
        }
×
505

506
        quiescenceReqs := make(
218✔
507
                chan fn.Req[fn.Unit, fn.Result[lntypes.ChannelParty]], 1,
218✔
508
        )
218✔
509

218✔
510
        return &channelLink{
218✔
511
                cfg:                 cfg,
218✔
512
                channel:             channel,
218✔
513
                hodlMap:             make(map[models.CircuitKey]hodlHtlc),
218✔
514
                hodlQueue:           queue.NewConcurrentQueue(10),
218✔
515
                log:                 log.WithPrefix(logPrefix),
218✔
516
                flushHooks:          newHookMap(),
218✔
517
                outgoingCommitHooks: newHookMap(),
218✔
518
                incomingCommitHooks: newHookMap(),
218✔
519
                quiescer:            qsm,
218✔
520
                quiescenceReqs:      quiescenceReqs,
218✔
521
                cg:                  fn.NewContextGuard(),
218✔
522
        }
218✔
523
}
524

525
// A compile time check to ensure channelLink implements the ChannelLink
526
// interface.
527
var _ ChannelLink = (*channelLink)(nil)
528

529
// Start starts all helper goroutines required for the operation of the channel
530
// link.
531
//
532
// NOTE: Part of the ChannelLink interface.
533
func (l *channelLink) Start() error {
216✔
534
        if !atomic.CompareAndSwapInt32(&l.started, 0, 1) {
216✔
535
                err := fmt.Errorf("channel link(%v): already started", l)
×
536
                l.log.Warn("already started")
×
537
                return err
×
538
        }
×
539

540
        l.log.Info("starting")
216✔
541

216✔
542
        // If the config supplied watchtower client, ensure the channel is
216✔
543
        // registered before trying to use it during operation.
216✔
544
        if l.cfg.TowerClient != nil {
219✔
545
                err := l.cfg.TowerClient.RegisterChannel(
3✔
546
                        l.ChanID(), l.channel.State().ChanType,
3✔
547
                )
3✔
548
                if err != nil {
3✔
549
                        return err
×
550
                }
×
551
        }
552

553
        l.mailBox.ResetMessages()
216✔
554
        l.hodlQueue.Start()
216✔
555

216✔
556
        // Before launching the htlcManager messages, revert any circuits that
216✔
557
        // were marked open in the switch's circuit map, but did not make it
216✔
558
        // into a commitment txn. We use the next local htlc index as the cut
216✔
559
        // off point, since all indexes below that are committed. This action
216✔
560
        // is only performed if the link's final short channel ID has been
216✔
561
        // assigned, otherwise we would try to trim the htlcs belonging to the
216✔
562
        // all-zero, hop.Source ID.
216✔
563
        if l.ShortChanID() != hop.Source {
432✔
564
                localHtlcIndex, err := l.channel.NextLocalHtlcIndex()
216✔
565
                if err != nil {
216✔
566
                        return fmt.Errorf("unable to retrieve next local "+
×
567
                                "htlc index: %v", err)
×
568
                }
×
569

570
                // NOTE: This is automatically done by the switch when it
571
                // starts up, but is necessary to prevent inconsistencies in
572
                // the case that the link flaps. This is a result of a link's
573
                // life-cycle being shorter than that of the switch.
574
                chanID := l.ShortChanID()
216✔
575
                err = l.cfg.Circuits.TrimOpenCircuits(chanID, localHtlcIndex)
216✔
576
                if err != nil {
216✔
577
                        return fmt.Errorf("unable to trim circuits above "+
×
578
                                "local htlc index %d: %v", localHtlcIndex, err)
×
579
                }
×
580

581
                // Since the link is live, before we start the link we'll update
582
                // the ChainArbitrator with the set of new channel signals for
583
                // this channel.
584
                //
585
                // TODO(roasbeef): split goroutines within channel arb to avoid
586
                go func() {
432✔
587
                        signals := &contractcourt.ContractSignals{
216✔
588
                                ShortChanID: l.channel.ShortChanID(),
216✔
589
                        }
216✔
590

216✔
591
                        err := l.cfg.UpdateContractSignals(signals)
216✔
592
                        if err != nil {
216✔
593
                                l.log.Errorf("unable to update signals")
×
594
                        }
×
595
                }()
596
        }
597

598
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
216✔
599

216✔
600
        l.cg.WgAdd(1)
216✔
601
        go l.htlcManager(context.TODO())
216✔
602

216✔
603
        return nil
216✔
604
}
605

606
// Stop gracefully stops all active helper goroutines, then waits until they've
607
// exited.
608
//
609
// NOTE: Part of the ChannelLink interface.
610
func (l *channelLink) Stop() {
217✔
611
        if !atomic.CompareAndSwapInt32(&l.shutdown, 0, 1) {
229✔
612
                l.log.Warn("already stopped")
12✔
613
                return
12✔
614
        }
12✔
615

616
        l.log.Info("stopping")
205✔
617

205✔
618
        // As the link is stopping, we are no longer interested in htlc
205✔
619
        // resolutions coming from the invoice registry.
205✔
620
        l.cfg.Registry.HodlUnsubscribeAll(l.hodlQueue.ChanIn())
205✔
621

205✔
622
        if l.cfg.ChainEvents.Cancel != nil {
208✔
623
                l.cfg.ChainEvents.Cancel()
3✔
624
        }
3✔
625

626
        // Ensure the channel for the timer is drained.
627
        if l.updateFeeTimer != nil {
410✔
628
                if !l.updateFeeTimer.Stop() {
205✔
629
                        select {
×
630
                        case <-l.updateFeeTimer.C:
×
631
                        default:
×
632
                        }
633
                }
634
        }
635

636
        if l.hodlQueue != nil {
410✔
637
                l.hodlQueue.Stop()
205✔
638
        }
205✔
639

640
        l.cg.Quit()
205✔
641
        l.cg.WgWait()
205✔
642

205✔
643
        // Now that the htlcManager has completely exited, reset the packet
205✔
644
        // courier. This allows the mailbox to revaluate any lingering Adds that
205✔
645
        // were delivered but didn't make it on a commitment to be failed back
205✔
646
        // if the link is offline for an extended period of time. The error is
205✔
647
        // ignored since it can only fail when the daemon is exiting.
205✔
648
        _ = l.mailBox.ResetPackets()
205✔
649

205✔
650
        // As a final precaution, we will attempt to flush any uncommitted
205✔
651
        // preimages to the preimage cache. The preimages should be re-delivered
205✔
652
        // after channel reestablishment, however this adds an extra layer of
205✔
653
        // protection in case the peer never returns. Without this, we will be
205✔
654
        // unable to settle any contracts depending on the preimages even though
205✔
655
        // we had learned them at some point.
205✔
656
        err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
205✔
657
        if err != nil {
205✔
658
                l.log.Errorf("unable to add preimages=%v to cache: %v",
×
659
                        l.uncommittedPreimages, err)
×
660
        }
×
661
}
662

663
// WaitForShutdown blocks until the link finishes shutting down, which includes
664
// termination of all dependent goroutines.
665
func (l *channelLink) WaitForShutdown() {
×
666
        l.cg.WgWait()
×
667
}
×
668

669
// EligibleToForward returns a bool indicating if the channel is able to
670
// actively accept requests to forward HTLC's. We're able to forward HTLC's if
671
// we are eligible to update AND the channel isn't currently flushing the
672
// outgoing half of the channel.
673
//
674
// NOTE: MUST NOT be called from the main event loop.
675
func (l *channelLink) EligibleToForward() bool {
616✔
676
        l.RLock()
616✔
677
        defer l.RUnlock()
616✔
678

616✔
679
        return l.eligibleToForward()
616✔
680
}
616✔
681

682
// eligibleToForward returns a bool indicating if the channel is able to
683
// actively accept requests to forward HTLC's. We're able to forward HTLC's if
684
// we are eligible to update AND the channel isn't currently flushing the
685
// outgoing half of the channel.
686
//
687
// NOTE: MUST be called from the main event loop.
688
func (l *channelLink) eligibleToForward() bool {
616✔
689
        return l.eligibleToUpdate() && !l.IsFlushing(Outgoing)
616✔
690
}
616✔
691

692
// eligibleToUpdate returns a bool indicating if the channel is able to update
693
// channel state. We're able to update channel state if we know the remote
694
// party's next revocation point. Otherwise, we can't initiate new channel
695
// state. We also require that the short channel ID not be the all-zero source
696
// ID, meaning that the channel has had its ID finalized.
697
//
698
// NOTE: MUST be called from the main event loop.
699
func (l *channelLink) eligibleToUpdate() bool {
619✔
700
        return l.channel.RemoteNextRevocation() != nil &&
619✔
701
                l.channel.ShortChanID() != hop.Source &&
619✔
702
                l.isReestablished() &&
619✔
703
                l.quiescer.CanSendUpdates()
619✔
704
}
619✔
705

706
// EnableAdds sets the ChannelUpdateHandler state to allow UpdateAddHtlc's in
707
// the specified direction. It returns true if the state was changed and false
708
// if the desired state was already set before the method was called.
709
func (l *channelLink) EnableAdds(linkDirection LinkDirection) bool {
16✔
710
        if linkDirection == Outgoing {
24✔
711
                return l.isOutgoingAddBlocked.Swap(false)
8✔
712
        }
8✔
713

714
        return l.isIncomingAddBlocked.Swap(false)
8✔
715
}
716

717
// DisableAdds sets the ChannelUpdateHandler state to allow UpdateAddHtlc's in
718
// the specified direction. It returns true if the state was changed and false
719
// if the desired state was already set before the method was called.
720
func (l *channelLink) DisableAdds(linkDirection LinkDirection) bool {
16✔
721
        if linkDirection == Outgoing {
26✔
722
                return !l.isOutgoingAddBlocked.Swap(true)
10✔
723
        }
10✔
724

725
        return !l.isIncomingAddBlocked.Swap(true)
9✔
726
}
727

728
// IsFlushing returns true when UpdateAddHtlc's are disabled in the direction of
729
// the argument.
730
func (l *channelLink) IsFlushing(linkDirection LinkDirection) bool {
1,594✔
731
        if linkDirection == Outgoing {
2,714✔
732
                return l.isOutgoingAddBlocked.Load()
1,120✔
733
        }
1,120✔
734

735
        return l.isIncomingAddBlocked.Load()
477✔
736
}
737

738
// OnFlushedOnce adds a hook that will be called the next time the channel
739
// state reaches zero htlcs. This hook will only ever be called once. If the
740
// channel state already has zero htlcs, then this will be called immediately.
741
func (l *channelLink) OnFlushedOnce(hook func()) {
4✔
742
        select {
4✔
743
        case l.flushHooks.newTransients <- hook:
4✔
744
        case <-l.cg.Done():
×
745
        }
746
}
747

748
// OnCommitOnce adds a hook that will be called the next time a CommitSig
749
// message is sent in the argument's LinkDirection. This hook will only ever be
750
// called once. If no CommitSig is owed in the argument's LinkDirection, then
751
// we will call this hook be run immediately.
752
func (l *channelLink) OnCommitOnce(direction LinkDirection, hook func()) {
4✔
753
        var queue chan func()
4✔
754

4✔
755
        if direction == Outgoing {
8✔
756
                queue = l.outgoingCommitHooks.newTransients
4✔
757
        } else {
4✔
758
                queue = l.incomingCommitHooks.newTransients
×
759
        }
×
760

761
        select {
4✔
762
        case queue <- hook:
4✔
763
        case <-l.cg.Done():
×
764
        }
765
}
766

767
// InitStfu allows us to initiate quiescence on this link. It returns a receive
768
// only channel that will block until quiescence has been achieved, or
769
// definitively fails.
770
//
771
// This operation has been added to allow channels to be quiesced via RPC. It
772
// may be removed or reworked in the future as RPC initiated quiescence is a
773
// holdover until we have downstream protocols that use it.
774
func (l *channelLink) InitStfu() <-chan fn.Result[lntypes.ChannelParty] {
4✔
775
        req, out := fn.NewReq[fn.Unit, fn.Result[lntypes.ChannelParty]](
4✔
776
                fn.Unit{},
4✔
777
        )
4✔
778

4✔
779
        select {
4✔
780
        case l.quiescenceReqs <- req:
4✔
781
        case <-l.cg.Done():
×
782
                req.Resolve(fn.Err[lntypes.ChannelParty](ErrLinkShuttingDown))
×
783
        }
784

785
        return out
4✔
786
}
787

788
// isReestablished returns true if the link has successfully completed the
789
// channel reestablishment dance.
790
func (l *channelLink) isReestablished() bool {
619✔
791
        return atomic.LoadInt32(&l.reestablished) == 1
619✔
792
}
619✔
793

794
// markReestablished signals that the remote peer has successfully exchanged
795
// channel reestablish messages and that the channel is ready to process
796
// subsequent messages.
797
func (l *channelLink) markReestablished() {
216✔
798
        atomic.StoreInt32(&l.reestablished, 1)
216✔
799
}
216✔
800

801
// IsUnadvertised returns true if the underlying channel is unadvertised.
802
func (l *channelLink) IsUnadvertised() bool {
5✔
803
        state := l.channel.State()
5✔
804
        return state.ChannelFlags&lnwire.FFAnnounceChannel == 0
5✔
805
}
5✔
806

807
// sampleNetworkFee samples the current fee rate on the network to get into the
808
// chain in a timely manner. The returned value is expressed in fee-per-kw, as
809
// this is the native rate used when computing the fee for commitment
810
// transactions, and the second-level HTLC transactions.
811
func (l *channelLink) sampleNetworkFee() (chainfee.SatPerKWeight, error) {
4✔
812
        // We'll first query for the sat/kw recommended to be confirmed within 3
4✔
813
        // blocks.
4✔
814
        feePerKw, err := l.cfg.FeeEstimator.EstimateFeePerKW(3)
4✔
815
        if err != nil {
4✔
816
                return 0, err
×
817
        }
×
818

819
        l.log.Debugf("sampled fee rate for 3 block conf: %v sat/kw",
4✔
820
                int64(feePerKw))
4✔
821

4✔
822
        return feePerKw, nil
4✔
823
}
824

825
// shouldAdjustCommitFee returns true if we should update our commitment fee to
826
// match that of the network fee. We'll only update our commitment fee if the
827
// network fee is +/- 10% to our commitment fee or if our current commitment
828
// fee is below the minimum relay fee.
829
func shouldAdjustCommitFee(netFee, chanFee,
830
        minRelayFee chainfee.SatPerKWeight) bool {
14✔
831

14✔
832
        switch {
14✔
833
        // If the network fee is greater than our current commitment fee and
834
        // our current commitment fee is below the minimum relay fee then
835
        // we should switch to it no matter if it is less than a 10% increase.
836
        case netFee > chanFee && chanFee < minRelayFee:
1✔
837
                return true
1✔
838

839
        // If the network fee is greater than the commitment fee, then we'll
840
        // switch to it if it's at least 10% greater than the commit fee.
841
        case netFee > chanFee && netFee >= (chanFee+(chanFee*10)/100):
4✔
842
                return true
4✔
843

844
        // If the network fee is less than our commitment fee, then we'll
845
        // switch to it if it's at least 10% less than the commitment fee.
846
        case netFee < chanFee && netFee <= (chanFee-(chanFee*10)/100):
2✔
847
                return true
2✔
848

849
        // Otherwise, we won't modify our fee.
850
        default:
7✔
851
                return false
7✔
852
        }
853
}
854

855
// failCb is used to cut down on the argument verbosity.
856
type failCb func(update *lnwire.ChannelUpdate1) lnwire.FailureMessage
857

858
// createFailureWithUpdate creates a ChannelUpdate when failing an incoming or
859
// outgoing HTLC. It may return a FailureMessage that references a channel's
860
// alias. If the channel does not have an alias, then the regular channel
861
// update from disk will be returned.
862
func (l *channelLink) createFailureWithUpdate(incoming bool,
863
        outgoingScid lnwire.ShortChannelID, cb failCb) lnwire.FailureMessage {
25✔
864

25✔
865
        // Determine which SCID to use in case we need to use aliases in the
25✔
866
        // ChannelUpdate.
25✔
867
        scid := outgoingScid
25✔
868
        if incoming {
25✔
869
                scid = l.ShortChanID()
×
870
        }
×
871

872
        // Try using the FailAliasUpdate function. If it returns nil, fallback
873
        // to the non-alias behavior.
874
        update := l.cfg.FailAliasUpdate(scid, incoming)
25✔
875
        if update == nil {
44✔
876
                // Fallback to the non-alias behavior.
19✔
877
                var err error
19✔
878
                update, err = l.cfg.FetchLastChannelUpdate(l.ShortChanID())
19✔
879
                if err != nil {
19✔
880
                        return &lnwire.FailTemporaryNodeFailure{}
×
881
                }
×
882
        }
883

884
        return cb(update)
25✔
885
}
886

887
// syncChanState attempts to synchronize channel states with the remote party.
888
// This method is to be called upon reconnection after the initial funding
889
// flow. We'll compare out commitment chains with the remote party, and re-send
890
// either a danging commit signature, a revocation, or both.
891
func (l *channelLink) syncChanStates(ctx context.Context) error {
173✔
892
        chanState := l.channel.State()
173✔
893

173✔
894
        l.log.Infof("Attempting to re-synchronize channel: %v", chanState)
173✔
895

173✔
896
        // First, we'll generate our ChanSync message to send to the other
173✔
897
        // side. Based on this message, the remote party will decide if they
173✔
898
        // need to retransmit any data or not.
173✔
899
        localChanSyncMsg, err := chanState.ChanSyncMsg()
173✔
900
        if err != nil {
173✔
901
                return fmt.Errorf("unable to generate chan sync message for "+
×
902
                        "ChannelPoint(%v)", l.channel.ChannelPoint())
×
903
        }
×
904
        if err := l.cfg.Peer.SendMessage(true, localChanSyncMsg); err != nil {
173✔
905
                return fmt.Errorf("unable to send chan sync message for "+
×
906
                        "ChannelPoint(%v): %v", l.channel.ChannelPoint(), err)
×
907
        }
×
908

909
        var msgsToReSend []lnwire.Message
173✔
910

173✔
911
        // Next, we'll wait indefinitely to receive the ChanSync message. The
173✔
912
        // first message sent MUST be the ChanSync message.
173✔
913
        select {
173✔
914
        case msg := <-l.upstream:
173✔
915
                l.log.Tracef("Received msg=%v from peer(%x)", msg.MsgType(),
173✔
916
                        l.cfg.Peer.PubKey())
173✔
917

173✔
918
                remoteChanSyncMsg, ok := msg.(*lnwire.ChannelReestablish)
173✔
919
                if !ok {
173✔
920
                        return fmt.Errorf("first message sent to sync "+
×
921
                                "should be ChannelReestablish, instead "+
×
922
                                "received: %T", msg)
×
923
                }
×
924

925
                // If the remote party indicates that they think we haven't
926
                // done any state updates yet, then we'll retransmit the
927
                // channel_ready message first. We do this, as at this point
928
                // we can't be sure if they've really received the
929
                // ChannelReady message.
930
                if remoteChanSyncMsg.NextLocalCommitHeight == 1 &&
173✔
931
                        localChanSyncMsg.NextLocalCommitHeight == 1 &&
173✔
932
                        !l.channel.IsPending() {
340✔
933

167✔
934
                        l.log.Infof("resending ChannelReady message to peer")
167✔
935

167✔
936
                        nextRevocation, err := l.channel.NextRevocationKey()
167✔
937
                        if err != nil {
167✔
938
                                return fmt.Errorf("unable to create next "+
×
939
                                        "revocation: %v", err)
×
940
                        }
×
941

942
                        channelReadyMsg := lnwire.NewChannelReady(
167✔
943
                                l.ChanID(), nextRevocation,
167✔
944
                        )
167✔
945

167✔
946
                        // If this is a taproot channel, then we'll send the
167✔
947
                        // very same nonce that we sent above, as they should
167✔
948
                        // take the latest verification nonce we send.
167✔
949
                        if chanState.ChanType.IsTaproot() {
170✔
950
                                //nolint:ll
3✔
951
                                channelReadyMsg.NextLocalNonce = localChanSyncMsg.LocalNonce
3✔
952
                        }
3✔
953

954
                        // For channels that negotiated the option-scid-alias
955
                        // feature bit, ensure that we send over the alias in
956
                        // the channel_ready message. We'll send the first
957
                        // alias we find for the channel since it does not
958
                        // matter which alias we send. We'll error out if no
959
                        // aliases are found.
960
                        if l.negotiatedAliasFeature() {
170✔
961
                                aliases := l.getAliases()
3✔
962
                                if len(aliases) == 0 {
3✔
963
                                        // This shouldn't happen since we
×
964
                                        // always add at least one alias before
×
965
                                        // the channel reaches the link.
×
966
                                        return fmt.Errorf("no aliases found")
×
967
                                }
×
968

969
                                // getAliases returns a copy of the alias slice
970
                                // so it is ok to use a pointer to the first
971
                                // entry.
972
                                channelReadyMsg.AliasScid = &aliases[0]
3✔
973
                        }
974

975
                        err = l.cfg.Peer.SendMessage(false, channelReadyMsg)
167✔
976
                        if err != nil {
167✔
977
                                return fmt.Errorf("unable to re-send "+
×
978
                                        "ChannelReady: %v", err)
×
979
                        }
×
980
                }
981

982
                // In any case, we'll then process their ChanSync message.
983
                l.log.Info("received re-establishment message from remote side")
173✔
984

173✔
985
                var (
173✔
986
                        openedCircuits []CircuitKey
173✔
987
                        closedCircuits []CircuitKey
173✔
988
                )
173✔
989

173✔
990
                // We've just received a ChanSync message from the remote
173✔
991
                // party, so we'll process the message  in order to determine
173✔
992
                // if we need to re-transmit any messages to the remote party.
173✔
993
                ctx, cancel := l.cg.Create(ctx)
173✔
994
                defer cancel()
173✔
995
                msgsToReSend, openedCircuits, closedCircuits, err =
173✔
996
                        l.channel.ProcessChanSyncMsg(ctx, remoteChanSyncMsg)
173✔
997
                if err != nil {
176✔
998
                        return err
3✔
999
                }
3✔
1000

1001
                // Repopulate any identifiers for circuits that may have been
1002
                // opened or unclosed. This may happen if we needed to
1003
                // retransmit a commitment signature message.
1004
                l.openedCircuits = openedCircuits
173✔
1005
                l.closedCircuits = closedCircuits
173✔
1006

173✔
1007
                // Ensure that all packets have been have been removed from the
173✔
1008
                // link's mailbox.
173✔
1009
                if err := l.ackDownStreamPackets(); err != nil {
173✔
1010
                        return err
×
1011
                }
×
1012

1013
                if len(msgsToReSend) > 0 {
178✔
1014
                        l.log.Infof("sending %v updates to synchronize the "+
5✔
1015
                                "state", len(msgsToReSend))
5✔
1016
                }
5✔
1017

1018
                // If we have any messages to retransmit, we'll do so
1019
                // immediately so we return to a synchronized state as soon as
1020
                // possible.
1021
                for _, msg := range msgsToReSend {
184✔
1022
                        l.cfg.Peer.SendMessage(false, msg)
11✔
1023
                }
11✔
1024

1025
        case <-l.cg.Done():
3✔
1026
                return ErrLinkShuttingDown
3✔
1027
        }
1028

1029
        return nil
173✔
1030
}
1031

1032
// resolveFwdPkgs loads any forwarding packages for this link from disk, and
1033
// reprocesses them in order. The primary goal is to make sure that any HTLCs
1034
// we previously received are reinstated in memory, and forwarded to the switch
1035
// if necessary. After a restart, this will also delete any previously
1036
// completed packages.
1037
func (l *channelLink) resolveFwdPkgs(ctx context.Context) error {
216✔
1038
        fwdPkgs, err := l.channel.LoadFwdPkgs()
216✔
1039
        if err != nil {
216✔
1040
                return err
×
1041
        }
×
1042

1043
        l.log.Debugf("loaded %d fwd pks", len(fwdPkgs))
216✔
1044

216✔
1045
        for _, fwdPkg := range fwdPkgs {
225✔
1046
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
9✔
1047
                        return err
×
1048
                }
×
1049
        }
1050

1051
        // If any of our reprocessing steps require an update to the commitment
1052
        // txn, we initiate a state transition to capture all relevant changes.
1053
        if l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote) > 0 {
219✔
1054
                return l.updateCommitTx(ctx)
3✔
1055
        }
3✔
1056

1057
        return nil
216✔
1058
}
1059

1060
// resolveFwdPkg interprets the FwdState of the provided package, either
1061
// reprocesses any outstanding htlcs in the package, or performs garbage
1062
// collection on the package.
1063
func (l *channelLink) resolveFwdPkg(fwdPkg *channeldb.FwdPkg) error {
9✔
1064
        // Remove any completed packages to clear up space.
9✔
1065
        if fwdPkg.State == channeldb.FwdStateCompleted {
12✔
1066
                l.log.Debugf("removing completed fwd pkg for height=%d",
3✔
1067
                        fwdPkg.Height)
3✔
1068

3✔
1069
                err := l.channel.RemoveFwdPkgs(fwdPkg.Height)
3✔
1070
                if err != nil {
3✔
1071
                        l.log.Errorf("unable to remove fwd pkg for height=%d: "+
×
1072
                                "%v", fwdPkg.Height, err)
×
1073
                        return err
×
1074
                }
×
1075
        }
1076

1077
        // Otherwise this is either a new package or one has gone through
1078
        // processing, but contains htlcs that need to be restored in memory.
1079
        // We replay this forwarding package to make sure our local mem state
1080
        // is resurrected, we mimic any original responses back to the remote
1081
        // party, and re-forward the relevant HTLCs to the switch.
1082

1083
        // If the package is fully acked but not completed, it must still have
1084
        // settles and fails to propagate.
1085
        if !fwdPkg.SettleFailFilter.IsFull() {
12✔
1086
                l.processRemoteSettleFails(fwdPkg)
3✔
1087
        }
3✔
1088

1089
        // Finally, replay *ALL ADDS* in this forwarding package. The
1090
        // downstream logic is able to filter out any duplicates, but we must
1091
        // shove the entire, original set of adds down the pipeline so that the
1092
        // batch of adds presented to the sphinx router does not ever change.
1093
        if !fwdPkg.AckFilter.IsFull() {
15✔
1094
                l.processRemoteAdds(fwdPkg)
6✔
1095

6✔
1096
                // If the link failed during processing the adds, we must
6✔
1097
                // return to ensure we won't attempted to update the state
6✔
1098
                // further.
6✔
1099
                if l.failed {
6✔
1100
                        return fmt.Errorf("link failed while " +
×
1101
                                "processing remote adds")
×
1102
                }
×
1103
        }
1104

1105
        return nil
9✔
1106
}
1107

1108
// fwdPkgGarbager periodically reads all forwarding packages from disk and
1109
// removes those that can be discarded. It is safe to do this entirely in the
1110
// background, since all state is coordinated on disk. This also ensures the
1111
// link can continue to process messages and interleave database accesses.
1112
//
1113
// NOTE: This MUST be run as a goroutine.
1114
func (l *channelLink) fwdPkgGarbager() {
216✔
1115
        defer l.cg.WgDone()
216✔
1116

216✔
1117
        l.cfg.FwdPkgGCTicker.Resume()
216✔
1118
        defer l.cfg.FwdPkgGCTicker.Stop()
216✔
1119

216✔
1120
        if err := l.loadAndRemove(); err != nil {
216✔
1121
                l.log.Warnf("unable to run initial fwd pkgs gc: %v", err)
×
1122
        }
×
1123

1124
        for {
453✔
1125
                select {
237✔
1126
                case <-l.cfg.FwdPkgGCTicker.Ticks():
21✔
1127
                        if err := l.loadAndRemove(); err != nil {
42✔
1128
                                l.log.Warnf("unable to remove fwd pkgs: %v",
21✔
1129
                                        err)
21✔
1130
                                continue
21✔
1131
                        }
1132
                case <-l.cg.Done():
205✔
1133
                        return
205✔
1134
                }
1135
        }
1136
}
1137

1138
// loadAndRemove loads all the channels forwarding packages and determines if
1139
// they can be removed. It is called once before the FwdPkgGCTicker ticks so that
1140
// a longer tick interval can be used.
1141
func (l *channelLink) loadAndRemove() error {
237✔
1142
        fwdPkgs, err := l.channel.LoadFwdPkgs()
237✔
1143
        if err != nil {
258✔
1144
                return err
21✔
1145
        }
21✔
1146

1147
        var removeHeights []uint64
216✔
1148
        for _, fwdPkg := range fwdPkgs {
225✔
1149
                if fwdPkg.State != channeldb.FwdStateCompleted {
18✔
1150
                        continue
9✔
1151
                }
1152

1153
                removeHeights = append(removeHeights, fwdPkg.Height)
3✔
1154
        }
1155

1156
        // If removeHeights is empty, return early so we don't use a db
1157
        // transaction.
1158
        if len(removeHeights) == 0 {
432✔
1159
                return nil
216✔
1160
        }
216✔
1161

1162
        return l.channel.RemoveFwdPkgs(removeHeights...)
3✔
1163
}
1164

1165
// handleChanSyncErr performs the error handling logic in the case where we
1166
// could not successfully syncChanStates with our channel peer.
1167
func (l *channelLink) handleChanSyncErr(err error) {
3✔
1168
        l.log.Warnf("error when syncing channel states: %v", err)
3✔
1169

3✔
1170
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
3✔
1171

3✔
1172
        switch {
3✔
1173
        case errors.Is(err, ErrLinkShuttingDown):
3✔
1174
                l.log.Debugf("unable to sync channel states, link is " +
3✔
1175
                        "shutting down")
3✔
1176
                return
3✔
1177

1178
        // We failed syncing the commit chains, probably because the remote has
1179
        // lost state. We should force close the channel.
1180
        case errors.Is(err, lnwallet.ErrCommitSyncRemoteDataLoss):
3✔
1181
                fallthrough
3✔
1182

1183
        // The remote sent us an invalid last commit secret, we should force
1184
        // close the channel.
1185
        // TODO(halseth): and permanently ban the peer?
1186
        case errors.Is(err, lnwallet.ErrInvalidLastCommitSecret):
3✔
1187
                fallthrough
3✔
1188

1189
        // The remote sent us a commit point different from what they sent us
1190
        // before.
1191
        // TODO(halseth): ban peer?
1192
        case errors.Is(err, lnwallet.ErrInvalidLocalUnrevokedCommitPoint):
3✔
1193
                // We'll fail the link and tell the peer to force close the
3✔
1194
                // channel. Note that the database state is not updated here,
3✔
1195
                // but will be updated when the close transaction is ready to
3✔
1196
                // avoid that we go down before storing the transaction in the
3✔
1197
                // db.
3✔
1198
                l.failf(
3✔
1199
                        LinkFailureError{
3✔
1200
                                code:          ErrSyncError,
3✔
1201
                                FailureAction: LinkFailureForceClose,
3✔
1202
                        },
3✔
1203
                        "unable to synchronize channel states: %v", err,
3✔
1204
                )
3✔
1205

1206
        // We have lost state and cannot safely force close the channel. Fail
1207
        // the channel and wait for the remote to hopefully force close it. The
1208
        // remote has sent us its latest unrevoked commitment point, and we'll
1209
        // store it in the database, such that we can attempt to recover the
1210
        // funds if the remote force closes the channel.
1211
        case errors.As(err, &errDataLoss):
3✔
1212
                err := l.channel.MarkDataLoss(
3✔
1213
                        errDataLoss.CommitPoint,
3✔
1214
                )
3✔
1215
                if err != nil {
3✔
1216
                        l.log.Errorf("unable to mark channel data loss: %v",
×
1217
                                err)
×
1218
                }
×
1219

1220
        // We determined the commit chains were not possible to sync. We
1221
        // cautiously fail the channel, but don't force close.
1222
        // TODO(halseth): can we safely force close in any cases where this
1223
        // error is returned?
1224
        case errors.Is(err, lnwallet.ErrCannotSyncCommitChains):
×
1225
                if err := l.channel.MarkBorked(); err != nil {
×
1226
                        l.log.Errorf("unable to mark channel borked: %v", err)
×
1227
                }
×
1228

1229
        // Other, unspecified error.
1230
        default:
×
1231
        }
1232

1233
        l.failf(
3✔
1234
                LinkFailureError{
3✔
1235
                        code:          ErrRecoveryError,
3✔
1236
                        FailureAction: LinkFailureForceNone,
3✔
1237
                },
3✔
1238
                "unable to synchronize channel states: %v", err,
3✔
1239
        )
3✔
1240
}
1241

1242
// htlcManager is the primary goroutine which drives a channel's commitment
1243
// update state-machine in response to messages received via several channels.
1244
// This goroutine reads messages from the upstream (remote) peer, and also from
1245
// downstream channel managed by the channel link. In the event that an htlc
1246
// needs to be forwarded, then send-only forward handler is used which sends
1247
// htlc packets to the switch. Additionally, this goroutine handles acting upon
1248
// all timeouts for any active HTLCs, manages the channel's revocation window,
1249
// and also the htlc trickle queue+timer for this active channels.
1250
//
1251
// NOTE: This MUST be run as a goroutine.
1252
//
1253
//nolint:funlen
1254
func (l *channelLink) htlcManager(ctx context.Context) {
216✔
1255
        defer func() {
422✔
1256
                l.cfg.BatchTicker.Stop()
206✔
1257
                l.cg.WgDone()
206✔
1258
                l.log.Infof("exited")
206✔
1259
        }()
206✔
1260

1261
        l.log.Infof("HTLC manager started, bandwidth=%v", l.Bandwidth())
216✔
1262

216✔
1263
        // Notify any clients that the link is now in the switch via an
216✔
1264
        // ActiveLinkEvent. We'll also defer an inactive link notification for
216✔
1265
        // when the link exits to ensure that every active notification is
216✔
1266
        // matched by an inactive one.
216✔
1267
        l.cfg.NotifyActiveLink(l.ChannelPoint())
216✔
1268
        defer l.cfg.NotifyInactiveLinkEvent(l.ChannelPoint())
216✔
1269

216✔
1270
        // TODO(roasbeef): need to call wipe chan whenever D/C?
216✔
1271

216✔
1272
        // If this isn't the first time that this channel link has been
216✔
1273
        // created, then we'll need to check to see if we need to
216✔
1274
        // re-synchronize state with the remote peer. settledHtlcs is a map of
216✔
1275
        // HTLC's that we re-settled as part of the channel state sync.
216✔
1276
        if l.cfg.SyncStates {
389✔
1277
                err := l.syncChanStates(ctx)
173✔
1278
                if err != nil {
176✔
1279
                        l.handleChanSyncErr(err)
3✔
1280
                        return
3✔
1281
                }
3✔
1282
        }
1283

1284
        // If a shutdown message has previously been sent on this link, then we
1285
        // need to make sure that we have disabled any HTLC adds on the outgoing
1286
        // direction of the link and that we re-resend the same shutdown message
1287
        // that we previously sent.
1288
        l.cfg.PreviouslySentShutdown.WhenSome(func(shutdown lnwire.Shutdown) {
219✔
1289
                // Immediately disallow any new outgoing HTLCs.
3✔
1290
                if !l.DisableAdds(Outgoing) {
3✔
1291
                        l.log.Warnf("Outgoing link adds already disabled")
×
1292
                }
×
1293

1294
                // Re-send the shutdown message the peer. Since syncChanStates
1295
                // would have sent any outstanding CommitSig, it is fine for us
1296
                // to immediately queue the shutdown message now.
1297
                err := l.cfg.Peer.SendMessage(false, &shutdown)
3✔
1298
                if err != nil {
3✔
1299
                        l.log.Warnf("Error sending shutdown message: %v", err)
×
1300
                }
×
1301
        })
1302

1303
        // We've successfully reestablished the channel, mark it as such to
1304
        // allow the switch to forward HTLCs in the outbound direction.
1305
        l.markReestablished()
216✔
1306

216✔
1307
        // Now that we've received both channel_ready and channel reestablish,
216✔
1308
        // we can go ahead and send the active channel notification. We'll also
216✔
1309
        // defer the inactive notification for when the link exits to ensure
216✔
1310
        // that every active notification is matched by an inactive one.
216✔
1311
        l.cfg.NotifyActiveChannel(l.ChannelPoint())
216✔
1312
        defer l.cfg.NotifyInactiveChannel(l.ChannelPoint())
216✔
1313

216✔
1314
        // With the channel states synced, we now reset the mailbox to ensure
216✔
1315
        // we start processing all unacked packets in order. This is done here
216✔
1316
        // to ensure that all acknowledgments that occur during channel
216✔
1317
        // resynchronization have taken affect, causing us only to pull unacked
216✔
1318
        // packets after starting to read from the downstream mailbox.
216✔
1319
        l.mailBox.ResetPackets()
216✔
1320

216✔
1321
        // After cleaning up any memory pertaining to incoming packets, we now
216✔
1322
        // replay our forwarding packages to handle any htlcs that can be
216✔
1323
        // processed locally, or need to be forwarded out to the switch. We will
216✔
1324
        // only attempt to resolve packages if our short chan id indicates that
216✔
1325
        // the channel is not pending, otherwise we should have no htlcs to
216✔
1326
        // reforward.
216✔
1327
        if l.ShortChanID() != hop.Source {
432✔
1328
                err := l.resolveFwdPkgs(ctx)
216✔
1329
                switch err {
216✔
1330
                // No error was encountered, success.
1331
                case nil:
216✔
1332

1333
                // If the duplicate keystone error was encountered, we'll fail
1334
                // without sending an Error message to the peer.
1335
                case ErrDuplicateKeystone:
×
1336
                        l.failf(LinkFailureError{code: ErrCircuitError},
×
1337
                                "temporary circuit error: %v", err)
×
1338
                        return
×
1339

1340
                // A non-nil error was encountered, send an Error message to
1341
                // the peer.
1342
                default:
×
1343
                        l.failf(LinkFailureError{code: ErrInternalError},
×
1344
                                "unable to resolve fwd pkgs: %v", err)
×
1345
                        return
×
1346
                }
1347

1348
                // With our link's in-memory state fully reconstructed, spawn a
1349
                // goroutine to manage the reclamation of disk space occupied by
1350
                // completed forwarding packages.
1351
                l.cg.WgAdd(1)
216✔
1352
                go l.fwdPkgGarbager()
216✔
1353
        }
1354

1355
        for {
4,425✔
1356
                // We must always check if we failed at some point processing
4,209✔
1357
                // the last update before processing the next.
4,209✔
1358
                if l.failed {
4,225✔
1359
                        l.log.Errorf("link failed, exiting htlcManager")
16✔
1360
                        return
16✔
1361
                }
16✔
1362

1363
                // If the previous event resulted in a non-empty batch, resume
1364
                // the batch ticker so that it can be cleared. Otherwise pause
1365
                // the ticker to prevent waking up the htlcManager while the
1366
                // batch is empty.
1367
                numUpdates := l.channel.NumPendingUpdates(
4,196✔
1368
                        lntypes.Local, lntypes.Remote,
4,196✔
1369
                )
4,196✔
1370
                if numUpdates > 0 {
4,706✔
1371
                        l.cfg.BatchTicker.Resume()
510✔
1372
                        l.log.Tracef("BatchTicker resumed, "+
510✔
1373
                                "NumPendingUpdates(Local, Remote)=%d",
510✔
1374
                                numUpdates,
510✔
1375
                        )
510✔
1376
                } else {
4,199✔
1377
                        l.cfg.BatchTicker.Pause()
3,689✔
1378
                        l.log.Trace("BatchTicker paused due to zero " +
3,689✔
1379
                                "NumPendingUpdates(Local, Remote)")
3,689✔
1380
                }
3,689✔
1381

1382
                select {
4,196✔
1383
                // We have a new hook that needs to be run when we reach a clean
1384
                // channel state.
1385
                case hook := <-l.flushHooks.newTransients:
4✔
1386
                        if l.channel.IsChannelClean() {
7✔
1387
                                hook()
3✔
1388
                        } else {
7✔
1389
                                l.flushHooks.alloc(hook)
4✔
1390
                        }
4✔
1391

1392
                // We have a new hook that needs to be run when we have
1393
                // committed all of our updates.
1394
                case hook := <-l.outgoingCommitHooks.newTransients:
4✔
1395
                        if !l.channel.OweCommitment() {
7✔
1396
                                hook()
3✔
1397
                        } else {
4✔
1398
                                l.outgoingCommitHooks.alloc(hook)
1✔
1399
                        }
1✔
1400

1401
                // We have a new hook that needs to be run when our peer has
1402
                // committed all of their updates.
1403
                case hook := <-l.incomingCommitHooks.newTransients:
×
1404
                        if !l.channel.NeedCommitment() {
×
1405
                                hook()
×
1406
                        } else {
×
1407
                                l.incomingCommitHooks.alloc(hook)
×
1408
                        }
×
1409

1410
                // Our update fee timer has fired, so we'll check the network
1411
                // fee to see if we should adjust our commitment fee.
1412
                case <-l.updateFeeTimer.C:
4✔
1413
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1414

4✔
1415
                        // If we're not the initiator of the channel, don't we
4✔
1416
                        // don't control the fees, so we can ignore this.
4✔
1417
                        if !l.channel.IsInitiator() {
4✔
1418
                                continue
×
1419
                        }
1420

1421
                        // If we are the initiator, then we'll sample the
1422
                        // current fee rate to get into the chain within 3
1423
                        // blocks.
1424
                        netFee, err := l.sampleNetworkFee()
4✔
1425
                        if err != nil {
4✔
1426
                                l.log.Errorf("unable to sample network fee: %v",
×
1427
                                        err)
×
1428
                                continue
×
1429
                        }
1430

1431
                        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
1432

4✔
1433
                        newCommitFee := l.channel.IdealCommitFeeRate(
4✔
1434
                                netFee, minRelayFee,
4✔
1435
                                l.cfg.MaxAnchorsCommitFeeRate,
4✔
1436
                                l.cfg.MaxFeeAllocation,
4✔
1437
                        )
4✔
1438

4✔
1439
                        // We determine if we should adjust the commitment fee
4✔
1440
                        // based on the current commitment fee, the suggested
4✔
1441
                        // new commitment fee and the current minimum relay fee
4✔
1442
                        // rate.
4✔
1443
                        commitFee := l.channel.CommitFeeRate()
4✔
1444
                        if !shouldAdjustCommitFee(
4✔
1445
                                newCommitFee, commitFee, minRelayFee,
4✔
1446
                        ) {
5✔
1447

1✔
1448
                                continue
1✔
1449
                        }
1450

1451
                        // If we do, then we'll send a new UpdateFee message to
1452
                        // the remote party, to be locked in with a new update.
1453
                        err = l.updateChannelFee(ctx, newCommitFee)
3✔
1454
                        if err != nil {
3✔
1455
                                l.log.Errorf("unable to update fee rate: %v",
×
1456
                                        err)
×
1457
                                continue
×
1458
                        }
1459

1460
                // The underlying channel has notified us of a unilateral close
1461
                // carried out by the remote peer. In the case of such an
1462
                // event, we'll wipe the channel state from the peer, and mark
1463
                // the contract as fully settled. Afterwards we can exit.
1464
                //
1465
                // TODO(roasbeef): add force closure? also breach?
1466
                case <-l.cfg.ChainEvents.RemoteUnilateralClosure:
3✔
1467
                        l.log.Warnf("remote peer has closed on-chain")
3✔
1468

3✔
1469
                        // TODO(roasbeef): remove all together
3✔
1470
                        go func() {
6✔
1471
                                chanPoint := l.channel.ChannelPoint()
3✔
1472
                                l.cfg.Peer.WipeChannel(&chanPoint)
3✔
1473
                        }()
3✔
1474

1475
                        return
3✔
1476

1477
                case <-l.cfg.BatchTicker.Ticks():
204✔
1478
                        // Attempt to extend the remote commitment chain
204✔
1479
                        // including all the currently pending entries. If the
204✔
1480
                        // send was unsuccessful, then abandon the update,
204✔
1481
                        // waiting for the revocation window to open up.
204✔
1482
                        if !l.updateCommitTxOrFail(ctx) {
204✔
1483
                                return
×
1484
                        }
×
1485

1486
                case <-l.cfg.PendingCommitTicker.Ticks():
1✔
1487
                        l.failf(
1✔
1488
                                LinkFailureError{
1✔
1489
                                        code:          ErrRemoteUnresponsive,
1✔
1490
                                        FailureAction: LinkFailureDisconnect,
1✔
1491
                                },
1✔
1492
                                "unable to complete dance",
1✔
1493
                        )
1✔
1494
                        return
1✔
1495

1496
                // A message from the switch was just received. This indicates
1497
                // that the link is an intermediate hop in a multi-hop HTLC
1498
                // circuit.
1499
                case pkt := <-l.downstream:
524✔
1500
                        l.handleDownstreamPkt(ctx, pkt)
524✔
1501

1502
                // A message from the connected peer was just received. This
1503
                // indicates that we have a new incoming HTLC, either directly
1504
                // for us, or part of a multi-hop HTLC circuit.
1505
                case msg := <-l.upstream:
3,212✔
1506
                        l.handleUpstreamMsg(ctx, msg)
3,212✔
1507

1508
                // A htlc resolution is received. This means that we now have a
1509
                // resolution for a previously accepted htlc.
1510
                case hodlItem := <-l.hodlQueue.ChanOut():
58✔
1511
                        htlcResolution := hodlItem.(invoices.HtlcResolution)
58✔
1512
                        err := l.processHodlQueue(ctx, htlcResolution)
58✔
1513
                        switch err {
58✔
1514
                        // No error, success.
1515
                        case nil:
57✔
1516

1517
                        // If the duplicate keystone error was encountered,
1518
                        // fail back gracefully.
1519
                        case ErrDuplicateKeystone:
×
1520
                                l.failf(LinkFailureError{
×
1521
                                        code: ErrCircuitError,
×
1522
                                }, "process hodl queue: "+
×
1523
                                        "temporary circuit error: %v",
×
1524
                                        err,
×
1525
                                )
×
1526

1527
                        // Send an Error message to the peer.
1528
                        default:
1✔
1529
                                l.failf(LinkFailureError{
1✔
1530
                                        code: ErrInternalError,
1✔
1531
                                }, "process hodl queue: unable to update "+
1✔
1532
                                        "commitment: %v", err,
1✔
1533
                                )
1✔
1534
                        }
1535

1536
                case qReq := <-l.quiescenceReqs:
4✔
1537
                        l.quiescer.InitStfu(qReq)
4✔
1538

4✔
1539
                        if l.noDanglingUpdates(lntypes.Local) {
8✔
1540
                                err := l.quiescer.SendOwedStfu()
4✔
1541
                                if err != nil {
4✔
1542
                                        l.stfuFailf(
×
1543
                                                "SendOwedStfu: %s", err.Error(),
×
1544
                                        )
×
1545
                                        res := fn.Err[lntypes.ChannelParty](err)
×
1546
                                        qReq.Resolve(res)
×
1547
                                }
×
1548
                        }
1549

1550
                case <-l.cg.Done():
192✔
1551
                        return
192✔
1552
                }
1553
        }
1554
}
1555

1556
// processHodlQueue processes a received htlc resolution and continues reading
1557
// from the hodl queue until no more resolutions remain. When this function
1558
// returns without an error, the commit tx should be updated.
1559
func (l *channelLink) processHodlQueue(ctx context.Context,
1560
        firstResolution invoices.HtlcResolution) error {
58✔
1561

58✔
1562
        // Try to read all waiting resolution messages, so that they can all be
58✔
1563
        // processed in a single commitment tx update.
58✔
1564
        htlcResolution := firstResolution
58✔
1565
loop:
58✔
1566
        for {
116✔
1567
                // Lookup all hodl htlcs that can be failed or settled with this event.
58✔
1568
                // The hodl htlc must be present in the map.
58✔
1569
                circuitKey := htlcResolution.CircuitKey()
58✔
1570
                hodlHtlc, ok := l.hodlMap[circuitKey]
58✔
1571
                if !ok {
58✔
1572
                        return fmt.Errorf("hodl htlc not found: %v", circuitKey)
×
1573
                }
×
1574

1575
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
58✔
1576
                        return err
×
1577
                }
×
1578

1579
                // Clean up hodl map.
1580
                delete(l.hodlMap, circuitKey)
58✔
1581

58✔
1582
                select {
58✔
1583
                case item := <-l.hodlQueue.ChanOut():
3✔
1584
                        htlcResolution = item.(invoices.HtlcResolution)
3✔
1585

1586
                // No need to process it if the link is broken.
1587
                case <-l.cg.Done():
×
1588
                        return ErrLinkShuttingDown
×
1589

1590
                default:
58✔
1591
                        break loop
58✔
1592
                }
1593
        }
1594

1595
        // Update the commitment tx.
1596
        if err := l.updateCommitTx(ctx); err != nil {
59✔
1597
                return err
1✔
1598
        }
1✔
1599

1600
        return nil
57✔
1601
}
1602

1603
// processHtlcResolution applies a received htlc resolution to the provided
1604
// htlc. When this function returns without an error, the commit tx should be
1605
// updated.
1606
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1607
        htlc hodlHtlc) error {
204✔
1608

204✔
1609
        circuitKey := resolution.CircuitKey()
204✔
1610

204✔
1611
        // Determine required action for the resolution based on the type of
204✔
1612
        // resolution we have received.
204✔
1613
        switch res := resolution.(type) {
204✔
1614
        // Settle htlcs that returned a settle resolution using the preimage
1615
        // in the resolution.
1616
        case *invoices.HtlcSettleResolution:
200✔
1617
                l.log.Debugf("received settle resolution for %v "+
200✔
1618
                        "with outcome: %v", circuitKey, res.Outcome)
200✔
1619

200✔
1620
                return l.settleHTLC(
200✔
1621
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
200✔
1622
                )
200✔
1623

1624
        // For htlc failures, we get the relevant failure message based
1625
        // on the failure resolution and then fail the htlc.
1626
        case *invoices.HtlcFailResolution:
7✔
1627
                l.log.Debugf("received cancel resolution for "+
7✔
1628
                        "%v with outcome: %v", circuitKey, res.Outcome)
7✔
1629

7✔
1630
                // Get the lnwire failure message based on the resolution
7✔
1631
                // result.
7✔
1632
                failure := getResolutionFailure(res, htlc.add.Amount)
7✔
1633

7✔
1634
                l.sendHTLCError(
7✔
1635
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
7✔
1636
                        true,
7✔
1637
                )
7✔
1638
                return nil
7✔
1639

1640
        // Fail if we do not get a settle of fail resolution, since we
1641
        // are only expecting to handle settles and fails.
1642
        default:
×
1643
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1644
                        resolution)
×
1645
        }
1646
}
1647

1648
// getResolutionFailure returns the wire message that a htlc resolution should
1649
// be failed with.
1650
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1651
        amount lnwire.MilliSatoshi) *LinkError {
7✔
1652

7✔
1653
        // If the resolution has been resolved as part of a MPP timeout,
7✔
1654
        // we need to fail the htlc with lnwire.FailMppTimeout.
7✔
1655
        if resolution.Outcome == invoices.ResultMppTimeout {
7✔
1656
                return NewDetailedLinkError(
×
1657
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1658
                )
×
1659
        }
×
1660

1661
        // If the htlc is not a MPP timeout, we fail it with
1662
        // FailIncorrectDetails. This error is sent for invoice payment
1663
        // failures such as underpayment/ expiry too soon and hodl invoices
1664
        // (which return FailIncorrectDetails to avoid leaking information).
1665
        incorrectDetails := lnwire.NewFailIncorrectDetails(
7✔
1666
                amount, uint32(resolution.AcceptHeight),
7✔
1667
        )
7✔
1668

7✔
1669
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
7✔
1670
}
1671

1672
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
1673
// within the link's configuration that will be used to determine when the link
1674
// should propose an update to its commitment fee rate.
1675
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
220✔
1676
        lower := int64(l.cfg.MinUpdateTimeout)
220✔
1677
        upper := int64(l.cfg.MaxUpdateTimeout)
220✔
1678
        return time.Duration(prand.Int63n(upper-lower) + lower)
220✔
1679
}
220✔
1680

1681
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1682
// downstream HTLC Switch.
1683
func (l *channelLink) handleDownstreamUpdateAdd(ctx context.Context,
1684
        pkt *htlcPacket) error {
483✔
1685

483✔
1686
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
483✔
1687
        if !ok {
483✔
1688
                return errors.New("not an UpdateAddHTLC packet")
×
1689
        }
×
1690

1691
        // If we are flushing the link in the outgoing direction or we have
1692
        // already sent Stfu, then we can't add new htlcs to the link and we
1693
        // need to bounce it.
1694
        if l.IsFlushing(Outgoing) || !l.quiescer.CanSendUpdates() {
483✔
1695
                l.mailBox.FailAdd(pkt)
×
1696

×
1697
                return NewDetailedLinkError(
×
1698
                        &lnwire.FailTemporaryChannelFailure{},
×
1699
                        OutgoingFailureLinkNotEligible,
×
1700
                )
×
1701
        }
×
1702

1703
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1704
        // arbitrary delays between the switch adding an ADD to the
1705
        // mailbox, and the HTLC being added to the commitment state.
1706
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
483✔
1707
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1708
                l.mailBox.AckPacket(pkt.inKey())
×
1709
                return nil
×
1710
        }
×
1711

1712
        // Check if we can add the HTLC here without exceededing the max fee
1713
        // exposure threshold.
1714
        if l.isOverexposedWithHtlc(htlc, false) {
487✔
1715
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1716
                        "exposure exceeded")
4✔
1717

4✔
1718
                l.mailBox.FailAdd(pkt)
4✔
1719

4✔
1720
                return NewDetailedLinkError(
4✔
1721
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1722
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1723
                )
4✔
1724
        }
4✔
1725

1726
        // A new payment has been initiated via the downstream channel,
1727
        // so we add the new HTLC to our local log, then update the
1728
        // commitment chains.
1729
        htlc.ChanID = l.ChanID()
479✔
1730
        openCircuitRef := pkt.inKey()
479✔
1731

479✔
1732
        // We enforce the fee buffer for the commitment transaction because
479✔
1733
        // we are in control of adding this htlc. Nothing has locked-in yet so
479✔
1734
        // we can securely enforce the fee buffer which is only relevant if we
479✔
1735
        // are the initiator of the channel.
479✔
1736
        index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
479✔
1737
        if err != nil {
483✔
1738
                // The HTLC was unable to be added to the state machine,
4✔
1739
                // as a result, we'll signal the switch to cancel the
4✔
1740
                // pending payment.
4✔
1741
                l.log.Warnf("Unable to handle downstream add HTLC: %v",
4✔
1742
                        err)
4✔
1743

4✔
1744
                // Remove this packet from the link's mailbox, this
4✔
1745
                // prevents it from being reprocessed if the link
4✔
1746
                // restarts and resets it mailbox. If this response
4✔
1747
                // doesn't make it back to the originating link, it will
4✔
1748
                // be rejected upon attempting to reforward the Add to
4✔
1749
                // the switch, since the circuit was never fully opened,
4✔
1750
                // and the forwarding package shows it as
4✔
1751
                // unacknowledged.
4✔
1752
                l.mailBox.FailAdd(pkt)
4✔
1753

4✔
1754
                return NewDetailedLinkError(
4✔
1755
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1756
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1757
                )
4✔
1758
        }
4✔
1759

1760
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
478✔
1761
                "local_log_index=%v, pend_updates=%v",
478✔
1762
                htlc.PaymentHash[:], index,
478✔
1763
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
478✔
1764

478✔
1765
        pkt.outgoingChanID = l.ShortChanID()
478✔
1766
        pkt.outgoingHTLCID = index
478✔
1767
        htlc.ID = index
478✔
1768

478✔
1769
        l.log.Debugf("queueing keystone of ADD open circuit: %s->%s",
478✔
1770
                pkt.inKey(), pkt.outKey())
478✔
1771

478✔
1772
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
478✔
1773
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
478✔
1774

478✔
1775
        _ = l.cfg.Peer.SendMessage(false, htlc)
478✔
1776

478✔
1777
        // Send a forward event notification to htlcNotifier.
478✔
1778
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
478✔
1779
                newHtlcKey(pkt),
478✔
1780
                HtlcInfo{
478✔
1781
                        IncomingTimeLock: pkt.incomingTimeout,
478✔
1782
                        IncomingAmt:      pkt.incomingAmount,
478✔
1783
                        OutgoingTimeLock: htlc.Expiry,
478✔
1784
                        OutgoingAmt:      htlc.Amount,
478✔
1785
                },
478✔
1786
                getEventType(pkt),
478✔
1787
        )
478✔
1788

478✔
1789
        l.tryBatchUpdateCommitTx(ctx)
478✔
1790

478✔
1791
        return nil
478✔
1792
}
1793

1794
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1795
// Switch. Possible messages sent by the switch include requests to forward new
1796
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1797
// cleared HTLCs with the upstream peer.
1798
//
1799
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1800
func (l *channelLink) handleDownstreamPkt(ctx context.Context,
1801
        pkt *htlcPacket) {
524✔
1802

524✔
1803
        if pkt.htlc.MsgType().IsChannelUpdate() &&
524✔
1804
                !l.quiescer.CanSendUpdates() {
524✔
1805

×
1806
                l.log.Warnf("unable to process channel update. "+
×
1807
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1808

×
1809
                return
×
1810
        }
×
1811

1812
        switch htlc := pkt.htlc.(type) {
524✔
1813
        case *lnwire.UpdateAddHTLC:
483✔
1814
                // Handle add message. The returned error can be ignored,
483✔
1815
                // because it is also sent through the mailbox.
483✔
1816
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
483✔
1817

1818
        case *lnwire.UpdateFulfillHTLC:
26✔
1819
                // If hodl.SettleOutgoing mode is active, we exit early to
26✔
1820
                // simulate arbitrary delays between the switch adding the
26✔
1821
                // SETTLE to the mailbox, and the HTLC being added to the
26✔
1822
                // commitment state.
26✔
1823
                if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
26✔
1824
                        l.log.Warnf(hodl.SettleOutgoing.Warning())
×
1825
                        l.mailBox.AckPacket(pkt.inKey())
×
1826
                        return
×
1827
                }
×
1828

1829
                // An HTLC we forward to the switch has just settled somewhere
1830
                // upstream. Therefore we settle the HTLC within the our local
1831
                // state machine.
1832
                inKey := pkt.inKey()
26✔
1833
                err := l.channel.SettleHTLC(
26✔
1834
                        htlc.PaymentPreimage,
26✔
1835
                        pkt.incomingHTLCID,
26✔
1836
                        pkt.sourceRef,
26✔
1837
                        pkt.destRef,
26✔
1838
                        &inKey,
26✔
1839
                )
26✔
1840
                if err != nil {
26✔
1841
                        l.log.Errorf("unable to settle incoming HTLC for "+
×
1842
                                "circuit-key=%v: %v", inKey, err)
×
1843

×
1844
                        // If the HTLC index for Settle response was not known
×
1845
                        // to our commitment state, it has already been
×
1846
                        // cleaned up by a prior response. We'll thus try to
×
1847
                        // clean up any lingering state to ensure we don't
×
1848
                        // continue reforwarding.
×
1849
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
×
1850
                                l.cleanupSpuriousResponse(pkt)
×
1851
                        }
×
1852

1853
                        // Remove the packet from the link's mailbox to ensure
1854
                        // it doesn't get replayed after a reconnection.
1855
                        l.mailBox.AckPacket(inKey)
×
1856

×
1857
                        return
×
1858
                }
1859

1860
                l.log.Debugf("queueing removal of SETTLE closed circuit: "+
26✔
1861
                        "%s->%s", pkt.inKey(), pkt.outKey())
26✔
1862

26✔
1863
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
26✔
1864

26✔
1865
                // With the HTLC settled, we'll need to populate the wire
26✔
1866
                // message to target the specific channel and HTLC to be
26✔
1867
                // canceled.
26✔
1868
                htlc.ChanID = l.ChanID()
26✔
1869
                htlc.ID = pkt.incomingHTLCID
26✔
1870

26✔
1871
                // Then we send the HTLC settle message to the connected peer
26✔
1872
                // so we can continue the propagation of the settle message.
26✔
1873
                l.cfg.Peer.SendMessage(false, htlc)
26✔
1874

26✔
1875
                // Send a settle event notification to htlcNotifier.
26✔
1876
                l.cfg.HtlcNotifier.NotifySettleEvent(
26✔
1877
                        newHtlcKey(pkt),
26✔
1878
                        htlc.PaymentPreimage,
26✔
1879
                        getEventType(pkt),
26✔
1880
                )
26✔
1881

26✔
1882
                // Immediately update the commitment tx to minimize latency.
26✔
1883
                l.updateCommitTxOrFail(ctx)
26✔
1884

1885
        case *lnwire.UpdateFailHTLC:
21✔
1886
                // If hodl.FailOutgoing mode is active, we exit early to
21✔
1887
                // simulate arbitrary delays between the switch adding a FAIL to
21✔
1888
                // the mailbox, and the HTLC being added to the commitment
21✔
1889
                // state.
21✔
1890
                if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
21✔
1891
                        l.log.Warnf(hodl.FailOutgoing.Warning())
×
1892
                        l.mailBox.AckPacket(pkt.inKey())
×
1893
                        return
×
1894
                }
×
1895

1896
                // An HTLC cancellation has been triggered somewhere upstream,
1897
                // we'll remove then HTLC from our local state machine.
1898
                inKey := pkt.inKey()
21✔
1899
                err := l.channel.FailHTLC(
21✔
1900
                        pkt.incomingHTLCID,
21✔
1901
                        htlc.Reason,
21✔
1902
                        pkt.sourceRef,
21✔
1903
                        pkt.destRef,
21✔
1904
                        &inKey,
21✔
1905
                )
21✔
1906
                if err != nil {
26✔
1907
                        l.log.Errorf("unable to cancel incoming HTLC for "+
5✔
1908
                                "circuit-key=%v: %v", inKey, err)
5✔
1909

5✔
1910
                        // If the HTLC index for Fail response was not known to
5✔
1911
                        // our commitment state, it has already been cleaned up
5✔
1912
                        // by a prior response. We'll thus try to clean up any
5✔
1913
                        // lingering state to ensure we don't continue
5✔
1914
                        // reforwarding.
5✔
1915
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
7✔
1916
                                l.cleanupSpuriousResponse(pkt)
2✔
1917
                        }
2✔
1918

1919
                        // Remove the packet from the link's mailbox to ensure
1920
                        // it doesn't get replayed after a reconnection.
1921
                        l.mailBox.AckPacket(inKey)
5✔
1922

5✔
1923
                        return
5✔
1924
                }
1925

1926
                l.log.Debugf("queueing removal of FAIL closed circuit: %s->%s",
19✔
1927
                        pkt.inKey(), pkt.outKey())
19✔
1928

19✔
1929
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
19✔
1930

19✔
1931
                // With the HTLC removed, we'll need to populate the wire
19✔
1932
                // message to target the specific channel and HTLC to be
19✔
1933
                // canceled. The "Reason" field will have already been set
19✔
1934
                // within the switch.
19✔
1935
                htlc.ChanID = l.ChanID()
19✔
1936
                htlc.ID = pkt.incomingHTLCID
19✔
1937

19✔
1938
                // We send the HTLC message to the peer which initially created
19✔
1939
                // the HTLC. If the incoming blinding point is non-nil, we
19✔
1940
                // know that we are a relaying node in a blinded path.
19✔
1941
                // Otherwise, we're either an introduction node or not part of
19✔
1942
                // a blinded path at all.
19✔
1943
                if err := l.sendIncomingHTLCFailureMsg(
19✔
1944
                        htlc.ID,
19✔
1945
                        pkt.obfuscator,
19✔
1946
                        htlc.Reason,
19✔
1947
                ); err != nil {
19✔
1948
                        l.log.Errorf("unable to send HTLC failure: %v",
×
1949
                                err)
×
1950

×
1951
                        return
×
1952
                }
×
1953

1954
                // If the packet does not have a link failure set, it failed
1955
                // further down the route so we notify a forwarding failure.
1956
                // Otherwise, we notify a link failure because it failed at our
1957
                // node.
1958
                if pkt.linkFailure != nil {
32✔
1959
                        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
13✔
1960
                                newHtlcKey(pkt),
13✔
1961
                                newHtlcInfo(pkt),
13✔
1962
                                getEventType(pkt),
13✔
1963
                                pkt.linkFailure,
13✔
1964
                                false,
13✔
1965
                        )
13✔
1966
                } else {
22✔
1967
                        l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
9✔
1968
                                newHtlcKey(pkt), getEventType(pkt),
9✔
1969
                        )
9✔
1970
                }
9✔
1971

1972
                // Immediately update the commitment tx to minimize latency.
1973
                l.updateCommitTxOrFail(ctx)
19✔
1974
        }
1975
}
1976

1977
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1978
// full.
1979
func (l *channelLink) tryBatchUpdateCommitTx(ctx context.Context) {
478✔
1980
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
478✔
1981
        if pending < uint64(l.cfg.BatchSize) {
944✔
1982
                return
466✔
1983
        }
466✔
1984

1985
        l.updateCommitTxOrFail(ctx)
15✔
1986
}
1987

1988
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1989
// associated with this packet. If successful in doing so, it will also purge
1990
// the open circuit from the circuit map and remove the packet from the link's
1991
// mailbox.
1992
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1993
        inKey := pkt.inKey()
2✔
1994

2✔
1995
        l.log.Debugf("cleaning up spurious response for incoming "+
2✔
1996
                "circuit-key=%v", inKey)
2✔
1997

2✔
1998
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
1999
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
2000
        if pkt.sourceRef == nil {
3✔
2001
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
2002
                        "circuit-key=%v, does not contain source reference",
1✔
2003
                        inKey)
1✔
2004
                return
1✔
2005
        }
1✔
2006

2007
        // If the source reference is present,  we will try to prevent this link
2008
        // from resending the packet to the switch. To do so, we ack the AddRef
2009
        // of the incoming HTLC belonging to this link.
2010
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
1✔
2011
        if err != nil {
1✔
2012
                l.log.Errorf("unable to ack AddRef for incoming "+
×
2013
                        "circuit-key=%v: %v", inKey, err)
×
2014

×
2015
                // If this operation failed, it is unsafe to attempt removal of
×
2016
                // the destination reference or circuit, so we exit early. The
×
2017
                // cleanup may proceed with a different packet in the future
×
2018
                // that succeeds on this step.
×
2019
                return
×
2020
        }
×
2021

2022
        // Now that we know this link will stop retransmitting Adds to the
2023
        // switch, we can begin to teardown the response reference and circuit
2024
        // map.
2025
        //
2026
        // If the packet includes a destination reference, then a response for
2027
        // this HTLC was locked into the outgoing channel. Attempt to remove
2028
        // this reference, so we stop retransmitting the response internally.
2029
        // Even if this fails, we will proceed in trying to delete the circuit.
2030
        // When retransmitting responses, the destination references will be
2031
        // cleaned up if an open circuit is not found in the circuit map.
2032
        if pkt.destRef != nil {
1✔
2033
                err := l.channel.AckSettleFails(*pkt.destRef)
×
2034
                if err != nil {
×
2035
                        l.log.Errorf("unable to ack SettleFailRef "+
×
2036
                                "for incoming circuit-key=%v: %v",
×
2037
                                inKey, err)
×
2038
                }
×
2039
        }
2040

2041
        l.log.Debugf("deleting circuit for incoming circuit-key=%x", inKey)
1✔
2042

1✔
2043
        // With all known references acked, we can now safely delete the circuit
1✔
2044
        // from the switch's circuit map, as the state is no longer needed.
1✔
2045
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
2046
        if err != nil {
1✔
2047
                l.log.Errorf("unable to delete circuit for "+
×
2048
                        "circuit-key=%v: %v", inKey, err)
×
2049
        }
×
2050
}
2051

2052
// handleUpstreamMsg processes wire messages related to commitment state
2053
// updates from the upstream peer. The upstream peer is the peer whom we have a
2054
// direct channel with, updating our respective commitment chains.
2055
//
2056
//nolint:funlen
2057
func (l *channelLink) handleUpstreamMsg(ctx context.Context,
2058
        msg lnwire.Message) {
3,212✔
2059

3,212✔
2060
        l.log.Tracef("receive upstream msg %v, handling now... ", msg.MsgType())
3,212✔
2061
        defer l.log.Tracef("handled upstream msg %v", msg.MsgType())
3,212✔
2062

3,212✔
2063
        // First check if the message is an update and we are capable of
3,212✔
2064
        // receiving updates right now.
3,212✔
2065
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
3,212✔
2066
                l.stfuFailf("update received after stfu: %T", msg)
×
2067
                return
×
2068
        }
×
2069

2070
        switch msg := msg.(type) {
3,212✔
2071
        case *lnwire.UpdateAddHTLC:
453✔
2072
                if l.IsFlushing(Incoming) {
453✔
2073
                        // This is forbidden by the protocol specification.
×
2074
                        // The best chance we have to deal with this is to drop
×
2075
                        // the connection. This should roll back the channel
×
2076
                        // state to the last CommitSig. If the remote has
×
2077
                        // already sent a CommitSig we haven't received yet,
×
2078
                        // channel state will be re-synchronized with a
×
2079
                        // ChannelReestablish message upon reconnection and the
×
2080
                        // protocol state that caused us to flush the link will
×
2081
                        // be rolled back. In the event that there was some
×
2082
                        // non-deterministic behavior in the remote that caused
×
2083
                        // them to violate the protocol, we have a decent shot
×
2084
                        // at correcting it this way, since reconnecting will
×
2085
                        // put us in the cleanest possible state to try again.
×
2086
                        //
×
2087
                        // In addition to the above, it is possible for us to
×
2088
                        // hit this case in situations where we improperly
×
2089
                        // handle message ordering due to concurrency choices.
×
2090
                        // An issue has been filed to address this here:
×
2091
                        // https://github.com/lightningnetwork/lnd/issues/8393
×
2092
                        l.failf(
×
2093
                                LinkFailureError{
×
2094
                                        code:             ErrInvalidUpdate,
×
2095
                                        FailureAction:    LinkFailureDisconnect,
×
2096
                                        PermanentFailure: false,
×
2097
                                        Warning:          true,
×
2098
                                },
×
2099
                                "received add while link is flushing",
×
2100
                        )
×
2101

×
2102
                        return
×
2103
                }
×
2104

2105
                // Disallow htlcs with blinding points set if we haven't
2106
                // enabled the feature. This saves us from having to process
2107
                // the onion at all, but will only catch blinded payments
2108
                // where we are a relaying node (as the blinding point will
2109
                // be in the payload when we're the introduction node).
2110
                if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
453✔
2111
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2112
                                "blinding point included when route blinding "+
×
2113
                                        "is disabled")
×
2114

×
2115
                        return
×
2116
                }
×
2117

2118
                // We have to check the limit here rather than later in the
2119
                // switch because the counterparty can keep sending HTLC's
2120
                // without sending a revoke. This would mean that the switch
2121
                // check would only occur later.
2122
                if l.isOverexposedWithHtlc(msg, true) {
453✔
2123
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2124
                                "peer sent us an HTLC that exceeded our max "+
×
2125
                                        "fee exposure")
×
2126

×
2127
                        return
×
2128
                }
×
2129

2130
                // We just received an add request from an upstream peer, so we
2131
                // add it to our state machine, then add the HTLC to our
2132
                // "settle" list in the event that we know the preimage.
2133
                index, err := l.channel.ReceiveHTLC(msg)
453✔
2134
                if err != nil {
453✔
2135
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2136
                                "unable to handle upstream add HTLC: %v", err)
×
2137
                        return
×
2138
                }
×
2139

2140
                l.log.Tracef("receive upstream htlc with payment hash(%x), "+
453✔
2141
                        "assigning index: %v", msg.PaymentHash[:], index)
453✔
2142

2143
        case *lnwire.UpdateFulfillHTLC:
230✔
2144
                pre := msg.PaymentPreimage
230✔
2145
                idx := msg.ID
230✔
2146

230✔
2147
                // Before we pipeline the settle, we'll check the set of active
230✔
2148
                // htlc's to see if the related UpdateAddHTLC has been fully
230✔
2149
                // locked-in.
230✔
2150
                var lockedin bool
230✔
2151
                htlcs := l.channel.ActiveHtlcs()
230✔
2152
                for _, add := range htlcs {
760✔
2153
                        // The HTLC will be outgoing and match idx.
530✔
2154
                        if !add.Incoming && add.HtlcIndex == idx {
758✔
2155
                                lockedin = true
228✔
2156
                                break
228✔
2157
                        }
2158
                }
2159

2160
                if !lockedin {
232✔
2161
                        l.failf(
2✔
2162
                                LinkFailureError{code: ErrInvalidUpdate},
2✔
2163
                                "unable to handle upstream settle",
2✔
2164
                        )
2✔
2165
                        return
2✔
2166
                }
2✔
2167

2168
                if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
231✔
2169
                        l.failf(
3✔
2170
                                LinkFailureError{
3✔
2171
                                        code:          ErrInvalidUpdate,
3✔
2172
                                        FailureAction: LinkFailureForceClose,
3✔
2173
                                },
3✔
2174
                                "unable to handle upstream settle HTLC: %v", err,
3✔
2175
                        )
3✔
2176
                        return
3✔
2177
                }
3✔
2178

2179
                settlePacket := &htlcPacket{
228✔
2180
                        outgoingChanID: l.ShortChanID(),
228✔
2181
                        outgoingHTLCID: idx,
228✔
2182
                        htlc: &lnwire.UpdateFulfillHTLC{
228✔
2183
                                PaymentPreimage: pre,
228✔
2184
                        },
228✔
2185
                }
228✔
2186

228✔
2187
                // Add the newly discovered preimage to our growing list of
228✔
2188
                // uncommitted preimage. These will be written to the witness
228✔
2189
                // cache just before accepting the next commitment signature
228✔
2190
                // from the remote peer.
228✔
2191
                l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
228✔
2192

228✔
2193
                // Pipeline this settle, send it to the switch.
228✔
2194
                go l.forwardBatch(false, settlePacket)
228✔
2195

2196
        case *lnwire.UpdateFailMalformedHTLC:
6✔
2197
                // Convert the failure type encoded within the HTLC fail
6✔
2198
                // message to the proper generic lnwire error code.
6✔
2199
                var failure lnwire.FailureMessage
6✔
2200
                switch msg.FailureCode {
6✔
2201
                case lnwire.CodeInvalidOnionVersion:
4✔
2202
                        failure = &lnwire.FailInvalidOnionVersion{
4✔
2203
                                OnionSHA256: msg.ShaOnionBlob,
4✔
2204
                        }
4✔
2205
                case lnwire.CodeInvalidOnionHmac:
×
2206
                        failure = &lnwire.FailInvalidOnionHmac{
×
2207
                                OnionSHA256: msg.ShaOnionBlob,
×
2208
                        }
×
2209

2210
                case lnwire.CodeInvalidOnionKey:
×
2211
                        failure = &lnwire.FailInvalidOnionKey{
×
2212
                                OnionSHA256: msg.ShaOnionBlob,
×
2213
                        }
×
2214

2215
                // Handle malformed errors that are part of a blinded route.
2216
                // This case is slightly different, because we expect every
2217
                // relaying node in the blinded portion of the route to send
2218
                // malformed errors. If we're also a relaying node, we're
2219
                // likely going to switch this error out anyway for our own
2220
                // malformed error, but we handle the case here for
2221
                // completeness.
2222
                case lnwire.CodeInvalidBlinding:
3✔
2223
                        failure = &lnwire.FailInvalidBlinding{
3✔
2224
                                OnionSHA256: msg.ShaOnionBlob,
3✔
2225
                        }
3✔
2226

2227
                default:
2✔
2228
                        l.log.Warnf("unexpected failure code received in "+
2✔
2229
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
2230

2✔
2231
                        // We don't just pass back the error we received from
2✔
2232
                        // our successor. Otherwise we might report a failure
2✔
2233
                        // that penalizes us more than needed. If the onion that
2✔
2234
                        // we forwarded was correct, the node should have been
2✔
2235
                        // able to send back its own failure. The node did not
2✔
2236
                        // send back its own failure, so we assume there was a
2✔
2237
                        // problem with the onion and report that back. We reuse
2✔
2238
                        // the invalid onion key failure because there is no
2✔
2239
                        // specific error for this case.
2✔
2240
                        failure = &lnwire.FailInvalidOnionKey{
2✔
2241
                                OnionSHA256: msg.ShaOnionBlob,
2✔
2242
                        }
2✔
2243
                }
2244

2245
                // With the error parsed, we'll convert the into it's opaque
2246
                // form.
2247
                var b bytes.Buffer
6✔
2248
                if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
6✔
2249
                        l.log.Errorf("unable to encode malformed error: %v", err)
×
2250
                        return
×
2251
                }
×
2252

2253
                // If remote side have been unable to parse the onion blob we
2254
                // have sent to it, than we should transform the malformed HTLC
2255
                // message to the usual HTLC fail message.
2256
                err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
6✔
2257
                if err != nil {
6✔
2258
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2259
                                "unable to handle upstream fail HTLC: %v", err)
×
2260
                        return
×
2261
                }
×
2262

2263
        case *lnwire.UpdateFailHTLC:
123✔
2264
                // Verify that the failure reason is at least 256 bytes plus
123✔
2265
                // overhead.
123✔
2266
                const minimumFailReasonLength = lnwire.FailureMessageLength +
123✔
2267
                        2 + 2 + 32
123✔
2268

123✔
2269
                if len(msg.Reason) < minimumFailReasonLength {
124✔
2270
                        // We've received a reason with a non-compliant length.
1✔
2271
                        // Older nodes happily relay back these failures that
1✔
2272
                        // may originate from a node further downstream.
1✔
2273
                        // Therefore we can't just fail the channel.
1✔
2274
                        //
1✔
2275
                        // We want to be compliant ourselves, so we also can't
1✔
2276
                        // pass back the reason unmodified. And we must make
1✔
2277
                        // sure that we don't hit the magic length check of 260
1✔
2278
                        // bytes in processRemoteSettleFails either.
1✔
2279
                        //
1✔
2280
                        // Because the reason is unreadable for the payer
1✔
2281
                        // anyway, we just replace it by a compliant-length
1✔
2282
                        // series of random bytes.
1✔
2283
                        msg.Reason = make([]byte, minimumFailReasonLength)
1✔
2284
                        _, err := crand.Read(msg.Reason[:])
1✔
2285
                        if err != nil {
1✔
2286
                                l.log.Errorf("Random generation error: %v", err)
×
2287

×
2288
                                return
×
2289
                        }
×
2290
                }
2291

2292
                // Add fail to the update log.
2293
                idx := msg.ID
123✔
2294
                err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
123✔
2295
                if err != nil {
123✔
2296
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2297
                                "unable to handle upstream fail HTLC: %v", err)
×
2298
                        return
×
2299
                }
×
2300

2301
        case *lnwire.CommitSig:
1,210✔
2302
                // Since we may have learned new preimages for the first time,
1,210✔
2303
                // we'll add them to our preimage cache. By doing this, we
1,210✔
2304
                // ensure any contested contracts watched by any on-chain
1,210✔
2305
                // arbitrators can now sweep this HTLC on-chain. We delay
1,210✔
2306
                // committing the preimages until just before accepting the new
1,210✔
2307
                // remote commitment, as afterwards the peer won't resend the
1,210✔
2308
                // Settle messages on the next channel reestablishment. Doing so
1,210✔
2309
                // allows us to more effectively batch this operation, instead
1,210✔
2310
                // of doing a single write per preimage.
1,210✔
2311
                err := l.cfg.PreimageCache.AddPreimages(
1,210✔
2312
                        l.uncommittedPreimages...,
1,210✔
2313
                )
1,210✔
2314
                if err != nil {
1,210✔
2315
                        l.failf(
×
2316
                                LinkFailureError{code: ErrInternalError},
×
2317
                                "unable to add preimages=%v to cache: %v",
×
2318
                                l.uncommittedPreimages, err,
×
2319
                        )
×
2320
                        return
×
2321
                }
×
2322

2323
                // Instead of truncating the slice to conserve memory
2324
                // allocations, we simply set the uncommitted preimage slice to
2325
                // nil so that a new one will be initialized if any more
2326
                // witnesses are discovered. We do this because the maximum size
2327
                // that the slice can occupy is 15KB, and we want to ensure we
2328
                // release that memory back to the runtime.
2329
                l.uncommittedPreimages = nil
1,210✔
2330

1,210✔
2331
                // We just received a new updates to our local commitment
1,210✔
2332
                // chain, validate this new commitment, closing the link if
1,210✔
2333
                // invalid.
1,210✔
2334
                auxSigBlob, err := msg.CustomRecords.Serialize()
1,210✔
2335
                if err != nil {
1,210✔
2336
                        l.failf(
×
2337
                                LinkFailureError{code: ErrInvalidCommitment},
×
2338
                                "unable to serialize custom records: %v", err,
×
2339
                        )
×
2340

×
2341
                        return
×
2342
                }
×
2343
                err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
1,210✔
2344
                        CommitSig:  msg.CommitSig,
1,210✔
2345
                        HtlcSigs:   msg.HtlcSigs,
1,210✔
2346
                        PartialSig: msg.PartialSig,
1,210✔
2347
                        AuxSigBlob: auxSigBlob,
1,210✔
2348
                })
1,210✔
2349
                if err != nil {
1,210✔
2350
                        // If we were unable to reconstruct their proposed
×
2351
                        // commitment, then we'll examine the type of error. If
×
2352
                        // it's an InvalidCommitSigError, then we'll send a
×
2353
                        // direct error.
×
2354
                        var sendData []byte
×
2355
                        switch err.(type) {
×
2356
                        case *lnwallet.InvalidCommitSigError:
×
2357
                                sendData = []byte(err.Error())
×
2358
                        case *lnwallet.InvalidHtlcSigError:
×
2359
                                sendData = []byte(err.Error())
×
2360
                        }
2361
                        l.failf(
×
2362
                                LinkFailureError{
×
2363
                                        code:          ErrInvalidCommitment,
×
2364
                                        FailureAction: LinkFailureForceClose,
×
2365
                                        SendData:      sendData,
×
2366
                                },
×
2367
                                "ChannelPoint(%v): unable to accept new "+
×
2368
                                        "commitment: %v",
×
2369
                                l.channel.ChannelPoint(), err,
×
2370
                        )
×
2371
                        return
×
2372
                }
2373

2374
                // As we've just accepted a new state, we'll now
2375
                // immediately send the remote peer a revocation for our prior
2376
                // state.
2377
                nextRevocation, currentHtlcs, finalHTLCs, err :=
1,210✔
2378
                        l.channel.RevokeCurrentCommitment()
1,210✔
2379
                if err != nil {
1,210✔
2380
                        l.log.Errorf("unable to revoke commitment: %v", err)
×
2381

×
2382
                        // We need to fail the channel in case revoking our
×
2383
                        // local commitment does not succeed. We might have
×
2384
                        // already advanced our channel state which would lead
×
2385
                        // us to proceed with an unclean state.
×
2386
                        //
×
2387
                        // NOTE: We do not trigger a force close because this
×
2388
                        // could resolve itself in case our db was just busy
×
2389
                        // not accepting new transactions.
×
2390
                        l.failf(
×
2391
                                LinkFailureError{
×
2392
                                        code:          ErrInternalError,
×
2393
                                        Warning:       true,
×
2394
                                        FailureAction: LinkFailureDisconnect,
×
2395
                                },
×
2396
                                "ChannelPoint(%v): unable to accept new "+
×
2397
                                        "commitment: %v",
×
2398
                                l.channel.ChannelPoint(), err,
×
2399
                        )
×
2400
                        return
×
2401
                }
×
2402

2403
                // As soon as we are ready to send our next revocation, we can
2404
                // invoke the incoming commit hooks.
2405
                l.RWMutex.Lock()
1,210✔
2406
                l.incomingCommitHooks.invoke()
1,210✔
2407
                l.RWMutex.Unlock()
1,210✔
2408

1,210✔
2409
                l.cfg.Peer.SendMessage(false, nextRevocation)
1,210✔
2410

1,210✔
2411
                // Notify the incoming htlcs of which the resolutions were
1,210✔
2412
                // locked in.
1,210✔
2413
                for id, settled := range finalHTLCs {
1,544✔
2414
                        l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
334✔
2415
                                models.CircuitKey{
334✔
2416
                                        ChanID: l.ShortChanID(),
334✔
2417
                                        HtlcID: id,
334✔
2418
                                },
334✔
2419
                                channeldb.FinalHtlcInfo{
334✔
2420
                                        Settled:  settled,
334✔
2421
                                        Offchain: true,
334✔
2422
                                },
334✔
2423
                        )
334✔
2424
                }
334✔
2425

2426
                // Since we just revoked our commitment, we may have a new set
2427
                // of HTLC's on our commitment, so we'll send them using our
2428
                // function closure NotifyContractUpdate.
2429
                newUpdate := &contractcourt.ContractUpdate{
1,210✔
2430
                        HtlcKey: contractcourt.LocalHtlcSet,
1,210✔
2431
                        Htlcs:   currentHtlcs,
1,210✔
2432
                }
1,210✔
2433
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,210✔
2434
                if err != nil {
1,210✔
2435
                        l.log.Errorf("unable to notify contract update: %v",
×
2436
                                err)
×
2437
                        return
×
2438
                }
×
2439

2440
                select {
1,210✔
2441
                case <-l.cg.Done():
×
2442
                        return
×
2443
                default:
1,210✔
2444
                }
2445

2446
                // If the remote party initiated the state transition,
2447
                // we'll reply with a signature to provide them with their
2448
                // version of the latest commitment. Otherwise, both commitment
2449
                // chains are fully synced from our PoV, then we don't need to
2450
                // reply with a signature as both sides already have a
2451
                // commitment with the latest accepted.
2452
                if l.channel.OweCommitment() {
1,873✔
2453
                        if !l.updateCommitTxOrFail(ctx) {
663✔
2454
                                return
×
2455
                        }
×
2456
                }
2457

2458
                // If we need to send out an Stfu, this would be the time to do
2459
                // so.
2460
                if l.noDanglingUpdates(lntypes.Local) {
2,310✔
2461
                        err = l.quiescer.SendOwedStfu()
1,100✔
2462
                        if err != nil {
1,100✔
2463
                                l.stfuFailf("sendOwedStfu: %v", err.Error())
×
2464
                        }
×
2465
                }
2466

2467
                // Now that we have finished processing the incoming CommitSig
2468
                // and sent out our RevokeAndAck, we invoke the flushHooks if
2469
                // the channel state is clean.
2470
                l.RWMutex.Lock()
1,210✔
2471
                if l.channel.IsChannelClean() {
1,411✔
2472
                        l.flushHooks.invoke()
201✔
2473
                }
201✔
2474
                l.RWMutex.Unlock()
1,210✔
2475

2476
        case *lnwire.RevokeAndAck:
1,199✔
2477
                // We've received a revocation from the remote chain, if valid,
1,199✔
2478
                // this moves the remote chain forward, and expands our
1,199✔
2479
                // revocation window.
1,199✔
2480

1,199✔
2481
                // We now process the message and advance our remote commit
1,199✔
2482
                // chain.
1,199✔
2483
                fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
1,199✔
2484
                if err != nil {
1,199✔
2485
                        // TODO(halseth): force close?
×
2486
                        l.failf(
×
2487
                                LinkFailureError{
×
2488
                                        code:          ErrInvalidRevocation,
×
2489
                                        FailureAction: LinkFailureDisconnect,
×
2490
                                },
×
2491
                                "unable to accept revocation: %v", err,
×
2492
                        )
×
2493
                        return
×
2494
                }
×
2495

2496
                // The remote party now has a new primary commitment, so we'll
2497
                // update the contract court to be aware of this new set (the
2498
                // prior old remote pending).
2499
                newUpdate := &contractcourt.ContractUpdate{
1,199✔
2500
                        HtlcKey: contractcourt.RemoteHtlcSet,
1,199✔
2501
                        Htlcs:   remoteHTLCs,
1,199✔
2502
                }
1,199✔
2503
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,199✔
2504
                if err != nil {
1,199✔
2505
                        l.log.Errorf("unable to notify contract update: %v",
×
2506
                                err)
×
2507
                        return
×
2508
                }
×
2509

2510
                select {
1,199✔
2511
                case <-l.cg.Done():
1✔
2512
                        return
1✔
2513
                default:
1,198✔
2514
                }
2515

2516
                // If we have a tower client for this channel type, we'll
2517
                // create a backup for the current state.
2518
                if l.cfg.TowerClient != nil {
1,201✔
2519
                        state := l.channel.State()
3✔
2520
                        chanID := l.ChanID()
3✔
2521

3✔
2522
                        err = l.cfg.TowerClient.BackupState(
3✔
2523
                                &chanID, state.RemoteCommitment.CommitHeight-1,
3✔
2524
                        )
3✔
2525
                        if err != nil {
3✔
2526
                                l.failf(LinkFailureError{
×
2527
                                        code: ErrInternalError,
×
2528
                                }, "unable to queue breach backup: %v", err)
×
2529
                                return
×
2530
                        }
×
2531
                }
2532

2533
                // If we can send updates then we can process adds in case we
2534
                // are the exit hop and need to send back resolutions, or in
2535
                // case there are validity issues with the packets. Otherwise
2536
                // we defer the action until resume.
2537
                //
2538
                // We are free to process the settles and fails without this
2539
                // check since processing those can't result in further updates
2540
                // to this channel link.
2541
                if l.quiescer.CanSendUpdates() {
2,395✔
2542
                        l.processRemoteAdds(fwdPkg)
1,197✔
2543
                } else {
1,198✔
2544
                        l.quiescer.OnResume(func() {
1✔
2545
                                l.processRemoteAdds(fwdPkg)
×
2546
                        })
×
2547
                }
2548
                l.processRemoteSettleFails(fwdPkg)
1,198✔
2549

1,198✔
2550
                // If the link failed during processing the adds, we must
1,198✔
2551
                // return to ensure we won't attempted to update the state
1,198✔
2552
                // further.
1,198✔
2553
                if l.failed {
1,198✔
2554
                        return
×
2555
                }
×
2556

2557
                // The revocation window opened up. If there are pending local
2558
                // updates, try to update the commit tx. Pending updates could
2559
                // already have been present because of a previously failed
2560
                // update to the commit tx or freshly added in by
2561
                // processRemoteAdds. Also in case there are no local updates,
2562
                // but there are still remote updates that are not in the remote
2563
                // commit tx yet, send out an update.
2564
                if l.channel.OweCommitment() {
1,529✔
2565
                        if !l.updateCommitTxOrFail(ctx) {
338✔
2566
                                return
7✔
2567
                        }
7✔
2568
                }
2569

2570
                // Now that we have finished processing the RevokeAndAck, we
2571
                // can invoke the flushHooks if the channel state is clean.
2572
                l.RWMutex.Lock()
1,191✔
2573
                if l.channel.IsChannelClean() {
1,355✔
2574
                        l.flushHooks.invoke()
164✔
2575
                }
164✔
2576
                l.RWMutex.Unlock()
1,191✔
2577

2578
        case *lnwire.UpdateFee:
3✔
2579
                // Check and see if their proposed fee-rate would make us
3✔
2580
                // exceed the fee threshold.
3✔
2581
                fee := chainfee.SatPerKWeight(msg.FeePerKw)
3✔
2582

3✔
2583
                isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
2584
                if err != nil {
3✔
2585
                        // This shouldn't typically happen. If it does, it
×
2586
                        // indicates something is wrong with our channel state.
×
2587
                        l.log.Errorf("Unable to determine if fee threshold " +
×
2588
                                "exceeded")
×
2589
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2590
                                "error calculating fee exposure: %v", err)
×
2591

×
2592
                        return
×
2593
                }
×
2594

2595
                if isDust {
3✔
2596
                        // The proposed fee-rate makes us exceed the fee
×
2597
                        // threshold.
×
2598
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2599
                                "fee threshold exceeded: %v", err)
×
2600
                        return
×
2601
                }
×
2602

2603
                // We received fee update from peer. If we are the initiator we
2604
                // will fail the channel, if not we will apply the update.
2605
                if err := l.channel.ReceiveUpdateFee(fee); err != nil {
3✔
2606
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2607
                                "error receiving fee update: %v", err)
×
2608
                        return
×
2609
                }
×
2610

2611
                // Update the mailbox's feerate as well.
2612
                l.mailBox.SetFeeRate(fee)
3✔
2613

2614
        case *lnwire.Stfu:
5✔
2615
                err := l.handleStfu(msg)
5✔
2616
                if err != nil {
5✔
2617
                        l.stfuFailf("handleStfu: %v", err.Error())
×
2618
                }
×
2619

2620
        // In the case where we receive a warning message from our peer, just
2621
        // log it and move on. We choose not to disconnect from our peer,
2622
        // although we "MAY" do so according to the specification.
2623
        case *lnwire.Warning:
1✔
2624
                l.log.Warnf("received warning message from peer: %v",
1✔
2625
                        msg.Warning())
1✔
2626

2627
        case *lnwire.Error:
2✔
2628
                // Error received from remote, MUST fail channel, but should
2✔
2629
                // only print the contents of the error message if all
2✔
2630
                // characters are printable ASCII.
2✔
2631
                l.failf(
2✔
2632
                        LinkFailureError{
2✔
2633
                                code: ErrRemoteError,
2✔
2634

2✔
2635
                                // TODO(halseth): we currently don't fail the
2✔
2636
                                // channel permanently, as there are some sync
2✔
2637
                                // issues with other implementations that will
2✔
2638
                                // lead to them sending an error message, but
2✔
2639
                                // we can recover from on next connection. See
2✔
2640
                                // https://github.com/ElementsProject/lightning/issues/4212
2✔
2641
                                PermanentFailure: false,
2✔
2642
                        },
2✔
2643
                        "ChannelPoint(%v): received error from peer: %v",
2✔
2644
                        l.channel.ChannelPoint(), msg.Error(),
2✔
2645
                )
2✔
2646
        default:
×
2647
                l.log.Warnf("received unknown message of type %T", msg)
×
2648
        }
2649

2650
}
2651

2652
// handleStfu implements the top-level logic for handling the Stfu message from
2653
// our peer.
2654
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
5✔
2655
        if !l.noDanglingUpdates(lntypes.Remote) {
5✔
2656
                return ErrPendingRemoteUpdates
×
2657
        }
×
2658
        err := l.quiescer.RecvStfu(*stfu)
5✔
2659
        if err != nil {
5✔
2660
                return err
×
2661
        }
×
2662

2663
        // If we can immediately send an Stfu response back, we will.
2664
        if l.noDanglingUpdates(lntypes.Local) {
9✔
2665
                return l.quiescer.SendOwedStfu()
4✔
2666
        }
4✔
2667

2668
        return nil
1✔
2669
}
2670

2671
// stfuFailf fails the link in the case where the requirements of the quiescence
2672
// protocol are violated. In all cases we opt to drop the connection as only
2673
// link state (as opposed to channel state) is affected.
2674
func (l *channelLink) stfuFailf(format string, args ...interface{}) {
×
2675
        l.failf(LinkFailureError{
×
2676
                code:             ErrStfuViolation,
×
2677
                FailureAction:    LinkFailureDisconnect,
×
2678
                PermanentFailure: false,
×
2679
                Warning:          true,
×
2680
        }, format, args...)
×
2681
}
×
2682

2683
// noDanglingUpdates returns true when there are 0 updates that were originally
2684
// issued by whose on either the Local or Remote commitment transaction.
2685
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
1,215✔
2686
        pendingOnLocal := l.channel.NumPendingUpdates(
1,215✔
2687
                whose, lntypes.Local,
1,215✔
2688
        )
1,215✔
2689
        pendingOnRemote := l.channel.NumPendingUpdates(
1,215✔
2690
                whose, lntypes.Remote,
1,215✔
2691
        )
1,215✔
2692

1,215✔
2693
        return pendingOnLocal == 0 && pendingOnRemote == 0
1,215✔
2694
}
1,215✔
2695

2696
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
2697
// for packets delivered from server, and cleaning up any circuits closed by
2698
// signing a previous commitment txn. This method ensures that the circuits are
2699
// removed from the circuit map before removing them from the link's mailbox,
2700
// otherwise it could be possible for some circuit to be missed if this link
2701
// flaps.
2702
func (l *channelLink) ackDownStreamPackets() error {
1,389✔
2703
        // First, remove the downstream Add packets that were included in the
1,389✔
2704
        // previous commitment signature. This will prevent the Adds from being
1,389✔
2705
        // replayed if this link disconnects.
1,389✔
2706
        for _, inKey := range l.openedCircuits {
1,856✔
2707
                // In order to test the sphinx replay logic of the remote
467✔
2708
                // party, unsafe replay does not acknowledge the packets from
467✔
2709
                // the mailbox. We can then force a replay of any Add packets
467✔
2710
                // held in memory by disconnecting and reconnecting the link.
467✔
2711
                if l.cfg.UnsafeReplay {
470✔
2712
                        continue
3✔
2713
                }
2714

2715
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
467✔
2716
                l.mailBox.AckPacket(inKey)
467✔
2717
        }
2718

2719
        // Now, we will delete all circuits closed by the previous commitment
2720
        // signature, which is the result of downstream Settle/Fail packets. We
2721
        // batch them here to ensure circuits are closed atomically and for
2722
        // performance.
2723
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
1,389✔
2724
        switch err {
1,389✔
2725
        case nil:
1,389✔
2726
                // Successful deletion.
2727

2728
        default:
×
2729
                l.log.Errorf("unable to delete %d circuits: %v",
×
2730
                        len(l.closedCircuits), err)
×
2731
                return err
×
2732
        }
2733

2734
        // With the circuits removed from memory and disk, we now ack any
2735
        // Settle/Fails in the mailbox to ensure they do not get redelivered
2736
        // after startup. If forgive is enabled and we've reached this point,
2737
        // the circuits must have been removed at some point, so it is now safe
2738
        // to un-queue the corresponding Settle/Fails.
2739
        for _, inKey := range l.closedCircuits {
1,431✔
2740
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
42✔
2741
                        inKey)
42✔
2742
                l.mailBox.AckPacket(inKey)
42✔
2743
        }
42✔
2744

2745
        // Lastly, reset our buffers to be empty while keeping any acquired
2746
        // growth in the backing array.
2747
        l.openedCircuits = l.openedCircuits[:0]
1,389✔
2748
        l.closedCircuits = l.closedCircuits[:0]
1,389✔
2749

1,389✔
2750
        return nil
1,389✔
2751
}
2752

2753
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
2754
// the link.
2755
func (l *channelLink) updateCommitTxOrFail(ctx context.Context) bool {
1,243✔
2756
        err := l.updateCommitTx(ctx)
1,243✔
2757
        switch err {
1,243✔
2758
        // No error encountered, success.
2759
        case nil:
1,233✔
2760

2761
        // A duplicate keystone error should be resolved and is not fatal, so
2762
        // we won't send an Error message to the peer.
2763
        case ErrDuplicateKeystone:
×
2764
                l.failf(LinkFailureError{code: ErrCircuitError},
×
2765
                        "temporary circuit error: %v", err)
×
2766
                return false
×
2767

2768
        // Any other error is treated results in an Error message being sent to
2769
        // the peer.
2770
        default:
10✔
2771
                l.failf(LinkFailureError{code: ErrInternalError},
10✔
2772
                        "unable to update commitment: %v", err)
10✔
2773
                return false
10✔
2774
        }
2775

2776
        return true
1,233✔
2777
}
2778

2779
// updateCommitTx signs, then sends an update to the remote peer adding a new
2780
// commitment to their commitment chain which includes all the latest updates
2781
// we've received+processed up to this point.
2782
func (l *channelLink) updateCommitTx(ctx context.Context) error {
1,301✔
2783
        // Preemptively write all pending keystones to disk, just in case the
1,301✔
2784
        // HTLCs we have in memory are included in the subsequent attempt to
1,301✔
2785
        // sign a commitment state.
1,301✔
2786
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
1,301✔
2787
        if err != nil {
1,301✔
2788
                // If ErrDuplicateKeystone is returned, the caller will catch
×
2789
                // it.
×
2790
                return err
×
2791
        }
×
2792

2793
        // Reset the batch, but keep the backing buffer to avoid reallocating.
2794
        l.keystoneBatch = l.keystoneBatch[:0]
1,301✔
2795

1,301✔
2796
        // If hodl.Commit mode is active, we will refrain from attempting to
1,301✔
2797
        // commit any in-memory modifications to the channel state. Exiting here
1,301✔
2798
        // permits testing of either the switch or link's ability to trim
1,301✔
2799
        // circuits that have been opened, but unsuccessfully committed.
1,301✔
2800
        if l.cfg.HodlMask.Active(hodl.Commit) {
1,308✔
2801
                l.log.Warnf(hodl.Commit.Warning())
7✔
2802
                return nil
7✔
2803
        }
7✔
2804

2805
        ctx, done := l.cg.Create(ctx)
1,297✔
2806
        defer done()
1,297✔
2807

1,297✔
2808
        newCommit, err := l.channel.SignNextCommitment(ctx)
1,297✔
2809
        if err == lnwallet.ErrNoWindow {
1,378✔
2810
                l.cfg.PendingCommitTicker.Resume()
81✔
2811
                l.log.Trace("PendingCommitTicker resumed")
81✔
2812

81✔
2813
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
81✔
2814
                l.log.Tracef("revocation window exhausted, unable to send: "+
81✔
2815
                        "%v, pend_updates=%v, dangling_closes%v", n,
81✔
2816
                        lnutils.SpewLogClosure(l.openedCircuits),
81✔
2817
                        lnutils.SpewLogClosure(l.closedCircuits))
81✔
2818

81✔
2819
                return nil
81✔
2820
        } else if err != nil {
1,300✔
2821
                return err
×
2822
        }
×
2823

2824
        if err := l.ackDownStreamPackets(); err != nil {
1,219✔
2825
                return err
×
2826
        }
×
2827

2828
        l.cfg.PendingCommitTicker.Pause()
1,219✔
2829
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
1,219✔
2830

1,219✔
2831
        // The remote party now has a new pending commitment, so we'll update
1,219✔
2832
        // the contract court to be aware of this new set (the prior old remote
1,219✔
2833
        // pending).
1,219✔
2834
        newUpdate := &contractcourt.ContractUpdate{
1,219✔
2835
                HtlcKey: contractcourt.RemotePendingHtlcSet,
1,219✔
2836
                Htlcs:   newCommit.PendingHTLCs,
1,219✔
2837
        }
1,219✔
2838
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,219✔
2839
        if err != nil {
1,219✔
2840
                l.log.Errorf("unable to notify contract update: %v", err)
×
2841
                return err
×
2842
        }
×
2843

2844
        select {
1,219✔
2845
        case <-l.cg.Done():
11✔
2846
                return ErrLinkShuttingDown
11✔
2847
        default:
1,208✔
2848
        }
2849

2850
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
1,208✔
2851
        if err != nil {
1,208✔
2852
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
2853
        }
×
2854

2855
        commitSig := &lnwire.CommitSig{
1,208✔
2856
                ChanID:        l.ChanID(),
1,208✔
2857
                CommitSig:     newCommit.CommitSig,
1,208✔
2858
                HtlcSigs:      newCommit.HtlcSigs,
1,208✔
2859
                PartialSig:    newCommit.PartialSig,
1,208✔
2860
                CustomRecords: auxBlobRecords,
1,208✔
2861
        }
1,208✔
2862
        l.cfg.Peer.SendMessage(false, commitSig)
1,208✔
2863

1,208✔
2864
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
1,208✔
2865
        // of commit hooks.
1,208✔
2866
        l.RWMutex.Lock()
1,208✔
2867
        l.outgoingCommitHooks.invoke()
1,208✔
2868
        l.RWMutex.Unlock()
1,208✔
2869

1,208✔
2870
        return nil
1,208✔
2871
}
2872

2873
// Peer returns the representation of remote peer with which we have the
2874
// channel link opened.
2875
//
2876
// NOTE: Part of the ChannelLink interface.
2877
func (l *channelLink) PeerPubKey() [33]byte {
444✔
2878
        return l.cfg.Peer.PubKey()
444✔
2879
}
444✔
2880

2881
// ChannelPoint returns the channel outpoint for the channel link.
2882
// NOTE: Part of the ChannelLink interface.
2883
func (l *channelLink) ChannelPoint() wire.OutPoint {
855✔
2884
        return l.channel.ChannelPoint()
855✔
2885
}
855✔
2886

2887
// ShortChanID returns the short channel ID for the channel link. The short
2888
// channel ID encodes the exact location in the main chain that the original
2889
// funding output can be found.
2890
//
2891
// NOTE: Part of the ChannelLink interface.
2892
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
4,251✔
2893
        l.RLock()
4,251✔
2894
        defer l.RUnlock()
4,251✔
2895

4,251✔
2896
        return l.channel.ShortChanID()
4,251✔
2897
}
4,251✔
2898

2899
// UpdateShortChanID updates the short channel ID for a link. This may be
2900
// required in the event that a link is created before the short chan ID for it
2901
// is known, or a re-org occurs, and the funding transaction changes location
2902
// within the chain.
2903
//
2904
// NOTE: Part of the ChannelLink interface.
2905
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
3✔
2906
        chanID := l.ChanID()
3✔
2907

3✔
2908
        // Refresh the channel state's short channel ID by loading it from disk.
3✔
2909
        // This ensures that the channel state accurately reflects the updated
3✔
2910
        // short channel ID.
3✔
2911
        err := l.channel.State().Refresh()
3✔
2912
        if err != nil {
3✔
2913
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2914
                        "%v", chanID, err)
×
2915
                return hop.Source, err
×
2916
        }
×
2917

2918
        return hop.Source, nil
3✔
2919
}
2920

2921
// ChanID returns the channel ID for the channel link. The channel ID is a more
2922
// compact representation of a channel's full outpoint.
2923
//
2924
// NOTE: Part of the ChannelLink interface.
2925
func (l *channelLink) ChanID() lnwire.ChannelID {
3,947✔
2926
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3,947✔
2927
}
3,947✔
2928

2929
// Bandwidth returns the total amount that can flow through the channel link at
2930
// this given instance. The value returned is expressed in millisatoshi and can
2931
// be used by callers when making forwarding decisions to determine if a link
2932
// can accept an HTLC.
2933
//
2934
// NOTE: Part of the ChannelLink interface.
2935
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
814✔
2936
        // Get the balance available on the channel for new HTLCs. This takes
814✔
2937
        // the channel reserve into account so HTLCs up to this value won't
814✔
2938
        // violate it.
814✔
2939
        return l.channel.AvailableBalance()
814✔
2940
}
814✔
2941

2942
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2943
// amount provided to the link. This check does not reserve a space, since
2944
// forwards or other payments may use the available slot, so it should be
2945
// considered best-effort.
2946
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
3✔
2947
        return l.channel.MayAddOutgoingHtlc(amt)
3✔
2948
}
3✔
2949

2950
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2951
// method.
2952
//
2953
// NOTE: Part of the dustHandler interface.
2954
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2955
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
2,526✔
2956

2,526✔
2957
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
2,526✔
2958
}
2,526✔
2959

2960
// getFeeRate is a wrapper method that retrieves the underlying channel's
2961
// feerate.
2962
//
2963
// NOTE: Part of the dustHandler interface.
2964
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
672✔
2965
        return l.channel.CommitFeeRate()
672✔
2966
}
672✔
2967

2968
// getDustClosure returns a closure that can be used by the switch or mailbox
2969
// to evaluate whether a given HTLC is dust.
2970
//
2971
// NOTE: Part of the dustHandler interface.
2972
func (l *channelLink) getDustClosure() dustClosure {
1,602✔
2973
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
1,602✔
2974
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
1,602✔
2975
        chanType := l.channel.State().ChanType
1,602✔
2976

1,602✔
2977
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
1,602✔
2978
}
1,602✔
2979

2980
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2981
// is used so that the Switch can have access to the commitment fee without
2982
// needing to have a *LightningChannel. This doesn't include dust.
2983
//
2984
// NOTE: Part of the dustHandler interface.
2985
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
1,900✔
2986
        if remote {
2,870✔
2987
                return l.channel.State().RemoteCommitment.CommitFee
970✔
2988
        }
970✔
2989

2990
        return l.channel.State().LocalCommitment.CommitFee
933✔
2991
}
2992

2993
// exceedsFeeExposureLimit returns whether or not the new proposed fee-rate
2994
// increases the total dust and fees within the channel past the configured
2995
// fee threshold. It first calculates the dust sum over every update in the
2996
// update log with the proposed fee-rate and taking into account both the local
2997
// and remote dust limits. It uses every update in the update log instead of
2998
// what is actually on the local and remote commitments because it is assumed
2999
// that in a worst-case scenario, every update in the update log could
3000
// theoretically be on either commitment transaction and this needs to be
3001
// accounted for with this fee-rate. It then calculates the local and remote
3002
// commitment fees given the proposed fee-rate. Finally, it tallies the results
3003
// and determines if the fee threshold has been exceeded.
3004
func (l *channelLink) exceedsFeeExposureLimit(
3005
        feePerKw chainfee.SatPerKWeight) (bool, error) {
6✔
3006

6✔
3007
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
3008

6✔
3009
        // Get the sum of dust for both the local and remote commitments using
6✔
3010
        // this "dry-run" fee.
6✔
3011
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
3012
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
3013

6✔
3014
        // Calculate the local and remote commitment fees using this dry-run
6✔
3015
        // fee.
6✔
3016
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
3017
        if err != nil {
6✔
3018
                return false, err
×
3019
        }
×
3020

3021
        // Finally, check whether the max fee exposure was exceeded on either
3022
        // future commitment transaction with the fee-rate.
3023
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
6✔
3024
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
3025
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3026
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
3027
                        totalLocalDust, localFee)
×
3028

×
3029
                return true, nil
×
3030
        }
×
3031

3032
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
3033
                remoteFee,
6✔
3034
        )
6✔
3035

6✔
3036
        if totalRemoteDust > l.cfg.MaxFeeExposure {
6✔
3037
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3038
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
3039
                        totalRemoteDust, remoteFee)
×
3040

×
3041
                return true, nil
×
3042
        }
×
3043

3044
        return false, nil
6✔
3045
}
3046

3047
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
3048
// channel exceed the fee threshold. It first fetches the largest fee-rate that
3049
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
3050
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
3051
// the overall dust sum. If it is not dust, it contributes to weight, which
3052
// also adds to the overall dust sum by an increase in fees. If the dust sum on
3053
// either commitment exceeds the configured fee threshold, this function
3054
// returns true.
3055
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
3056
        incoming bool) bool {
933✔
3057

933✔
3058
        dustClosure := l.getDustClosure()
933✔
3059

933✔
3060
        feeRate := l.channel.WorstCaseFeeRate()
933✔
3061

933✔
3062
        amount := htlc.Amount.ToSatoshis()
933✔
3063

933✔
3064
        // See if this HTLC is dust on both the local and remote commitments.
933✔
3065
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
933✔
3066
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
933✔
3067

933✔
3068
        // Calculate the dust sum for the local and remote commitments.
933✔
3069
        localDustSum := l.getDustSum(
933✔
3070
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
933✔
3071
        )
933✔
3072
        remoteDustSum := l.getDustSum(
933✔
3073
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
933✔
3074
        )
933✔
3075

933✔
3076
        // Grab the larger of the local and remote commitment fees w/o dust.
933✔
3077
        commitFee := l.getCommitFee(false)
933✔
3078

933✔
3079
        if l.getCommitFee(true) > commitFee {
971✔
3080
                commitFee = l.getCommitFee(true)
38✔
3081
        }
38✔
3082

3083
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
933✔
3084

933✔
3085
        localDustSum += commitFeeMSat
933✔
3086
        remoteDustSum += commitFeeMSat
933✔
3087

933✔
3088
        // Calculate the additional fee increase if this is a non-dust HTLC.
933✔
3089
        weight := lntypes.WeightUnit(input.HTLCWeight)
933✔
3090
        additional := lnwire.NewMSatFromSatoshis(
933✔
3091
                feeRate.FeeForWeight(weight),
933✔
3092
        )
933✔
3093

933✔
3094
        if isLocalDust {
1,569✔
3095
                // If this is dust, it doesn't contribute to weight but does
636✔
3096
                // contribute to the overall dust sum.
636✔
3097
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
636✔
3098
        } else {
936✔
3099
                // Account for the fee increase that comes with an increase in
300✔
3100
                // weight.
300✔
3101
                localDustSum += additional
300✔
3102
        }
300✔
3103

3104
        if localDustSum > l.cfg.MaxFeeExposure {
937✔
3105
                // The max fee exposure was exceeded.
4✔
3106
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
4✔
3107
                        "overexposed, total local dust: %v (current commit "+
4✔
3108
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
4✔
3109

4✔
3110
                return true
4✔
3111
        }
4✔
3112

3113
        if isRemoteDust {
1,562✔
3114
                // If this is dust, it doesn't contribute to weight but does
633✔
3115
                // contribute to the overall dust sum.
633✔
3116
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
633✔
3117
        } else {
932✔
3118
                // Account for the fee increase that comes with an increase in
299✔
3119
                // weight.
299✔
3120
                remoteDustSum += additional
299✔
3121
        }
299✔
3122

3123
        if remoteDustSum > l.cfg.MaxFeeExposure {
929✔
3124
                // The max fee exposure was exceeded.
×
3125
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
3126
                        "overexposed, total remote dust: %v (current commit "+
×
3127
                        "fee: %v)", l.ShortChanID(), htlc, remoteDustSum)
×
3128

×
3129
                return true
×
3130
        }
×
3131

3132
        return false
929✔
3133
}
3134

3135
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
3136
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
3137
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
3138
// whether to evaluate on the local or remote commit, and finally an HTLC
3139
// amount to test.
3140
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
3141
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
3142

3143
// dustHelper is used to construct the dustClosure.
3144
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
3145
        remoteDustLimit btcutil.Amount) dustClosure {
1,802✔
3146

1,802✔
3147
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
1,802✔
3148
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
11,441✔
3149

9,639✔
3150
                var dustLimit btcutil.Amount
9,639✔
3151
                if whoseCommit.IsLocal() {
14,460✔
3152
                        dustLimit = localDustLimit
4,821✔
3153
                } else {
9,642✔
3154
                        dustLimit = remoteDustLimit
4,821✔
3155
                }
4,821✔
3156

3157
                return lnwallet.HtlcIsDust(
9,639✔
3158
                        chantype, incoming, whoseCommit, feerate, amt,
9,639✔
3159
                        dustLimit,
9,639✔
3160
                )
9,639✔
3161
        }
3162

3163
        return isDust
1,802✔
3164
}
3165

3166
// zeroConfConfirmed returns whether or not the zero-conf channel has
3167
// confirmed on-chain.
3168
//
3169
// Part of the scidAliasHandler interface.
3170
func (l *channelLink) zeroConfConfirmed() bool {
6✔
3171
        return l.channel.State().ZeroConfConfirmed()
6✔
3172
}
6✔
3173

3174
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
3175
// should not be called for non-zero-conf channels.
3176
//
3177
// Part of the scidAliasHandler interface.
3178
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
6✔
3179
        return l.channel.State().ZeroConfRealScid()
6✔
3180
}
6✔
3181

3182
// isZeroConf returns whether or not the underlying channel is a zero-conf
3183
// channel.
3184
//
3185
// Part of the scidAliasHandler interface.
3186
func (l *channelLink) isZeroConf() bool {
216✔
3187
        return l.channel.State().IsZeroConf()
216✔
3188
}
216✔
3189

3190
// negotiatedAliasFeature returns whether or not the underlying channel has
3191
// negotiated the option-scid-alias feature bit. This will be true for both
3192
// option-scid-alias and zero-conf channel-types. It will also be true for
3193
// channels with the feature bit but without the above channel-types.
3194
//
3195
// Part of the scidAliasFeature interface.
3196
func (l *channelLink) negotiatedAliasFeature() bool {
377✔
3197
        return l.channel.State().NegotiatedAliasFeature()
377✔
3198
}
377✔
3199

3200
// getAliases returns the set of aliases for the underlying channel.
3201
//
3202
// Part of the scidAliasHandler interface.
3203
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
222✔
3204
        return l.cfg.GetAliases(l.ShortChanID())
222✔
3205
}
222✔
3206

3207
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
3208
//
3209
// Part of the scidAliasHandler interface.
3210
func (l *channelLink) attachFailAliasUpdate(closure func(
3211
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
217✔
3212

217✔
3213
        l.Lock()
217✔
3214
        l.cfg.FailAliasUpdate = closure
217✔
3215
        l.Unlock()
217✔
3216
}
217✔
3217

3218
// AttachMailBox updates the current mailbox used by this link, and hooks up
3219
// the mailbox's message and packet outboxes to the link's upstream and
3220
// downstream chans, respectively.
3221
func (l *channelLink) AttachMailBox(mailbox MailBox) {
216✔
3222
        l.Lock()
216✔
3223
        l.mailBox = mailbox
216✔
3224
        l.upstream = mailbox.MessageOutBox()
216✔
3225
        l.downstream = mailbox.PacketOutBox()
216✔
3226
        l.Unlock()
216✔
3227

216✔
3228
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
216✔
3229
        // never committed.
216✔
3230
        l.mailBox.SetFeeRate(l.getFeeRate())
216✔
3231

216✔
3232
        // Also set the mailbox's dust closure so that it can query whether HTLC's
216✔
3233
        // are dust given the current feerate.
216✔
3234
        l.mailBox.SetDustClosure(l.getDustClosure())
216✔
3235
}
216✔
3236

3237
// UpdateForwardingPolicy updates the forwarding policy for the target
3238
// ChannelLink. Once updated, the link will use the new forwarding policy to
3239
// govern if it an incoming HTLC should be forwarded or not. We assume that
3240
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
3241
// update all of the link's FwrdingPolicy's values.
3242
//
3243
// NOTE: Part of the ChannelLink interface.
3244
func (l *channelLink) UpdateForwardingPolicy(
3245
        newPolicy models.ForwardingPolicy) {
15✔
3246

15✔
3247
        l.Lock()
15✔
3248
        defer l.Unlock()
15✔
3249

15✔
3250
        l.cfg.FwrdingPolicy = newPolicy
15✔
3251
}
15✔
3252

3253
// CheckHtlcForward should return a nil error if the passed HTLC details
3254
// satisfy the current forwarding policy fo the target link. Otherwise,
3255
// a LinkError with a valid protocol failure message should be returned
3256
// in order to signal to the source of the HTLC, the policy consistency
3257
// issue.
3258
//
3259
// NOTE: Part of the ChannelLink interface.
3260
func (l *channelLink) CheckHtlcForward(payHash [32]byte, incomingHtlcAmt,
3261
        amtToForward lnwire.MilliSatoshi, incomingTimeout,
3262
        outgoingTimeout uint32, inboundFee models.InboundFee,
3263
        heightNow uint32, originalScid lnwire.ShortChannelID,
3264
        customRecords lnwire.CustomRecords) *LinkError {
52✔
3265

52✔
3266
        l.RLock()
52✔
3267
        policy := l.cfg.FwrdingPolicy
52✔
3268
        l.RUnlock()
52✔
3269

52✔
3270
        // Using the outgoing HTLC amount, we'll calculate the outgoing
52✔
3271
        // fee this incoming HTLC must carry in order to satisfy the constraints
52✔
3272
        // of the outgoing link.
52✔
3273
        outFee := ExpectedFee(policy, amtToForward)
52✔
3274

52✔
3275
        // Then calculate the inbound fee that we charge based on the sum of
52✔
3276
        // outgoing HTLC amount and outgoing fee.
52✔
3277
        inFee := inboundFee.CalcFee(amtToForward + outFee)
52✔
3278

52✔
3279
        // Add up both fee components. It is important to calculate both fees
52✔
3280
        // separately. An alternative way of calculating is to first determine
52✔
3281
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
52✔
3282
        // rounding may cause the result to be slightly higher than in the case
52✔
3283
        // of separately rounded fee components. This potentially causes failed
52✔
3284
        // forwards for senders and is something to be avoided.
52✔
3285
        expectedFee := inFee + int64(outFee)
52✔
3286

52✔
3287
        // If the actual fee is less than our expected fee, then we'll reject
52✔
3288
        // this HTLC as it didn't provide a sufficient amount of fees, or the
52✔
3289
        // values have been tampered with, or the send used incorrect/dated
52✔
3290
        // information to construct the forwarding information for this hop. In
52✔
3291
        // any case, we'll cancel this HTLC.
52✔
3292
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
52✔
3293
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
61✔
3294
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
9✔
3295
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
9✔
3296
                        "inboundFee=%v",
9✔
3297
                        payHash[:], expectedFee, actualFee,
9✔
3298
                        incomingHtlcAmt, amtToForward, inboundFee,
9✔
3299
                )
9✔
3300

9✔
3301
                // As part of the returned error, we'll send our latest routing
9✔
3302
                // policy so the sending node obtains the most up to date data.
9✔
3303
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
18✔
3304
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
9✔
3305
                }
9✔
3306
                failure := l.createFailureWithUpdate(false, originalScid, cb)
9✔
3307
                return NewLinkError(failure)
9✔
3308
        }
3309

3310
        // Check whether the outgoing htlc satisfies the channel policy.
3311
        err := l.canSendHtlc(
46✔
3312
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
46✔
3313
                originalScid, customRecords,
46✔
3314
        )
46✔
3315
        if err != nil {
62✔
3316
                return err
16✔
3317
        }
16✔
3318

3319
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
3320
        // the following constraint: the incoming time-lock minus our time-lock
3321
        // delta should equal the outgoing time lock. Otherwise, whether the
3322
        // sender messed up, or an intermediate node tampered with the HTLC.
3323
        timeDelta := policy.TimeLockDelta
33✔
3324
        if incomingTimeout < outgoingTimeout+timeDelta {
35✔
3325
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
3326
                        "expected at least %v block delta, got %v block delta",
2✔
3327
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
3328

2✔
3329
                // Grab the latest routing policy so the sending node is up to
2✔
3330
                // date with our current policy.
2✔
3331
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
3332
                        return lnwire.NewIncorrectCltvExpiry(
2✔
3333
                                incomingTimeout, *upd,
2✔
3334
                        )
2✔
3335
                }
2✔
3336
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3337
                return NewLinkError(failure)
2✔
3338
        }
3339

3340
        return nil
31✔
3341
}
3342

3343
// CheckHtlcTransit should return a nil error if the passed HTLC details
3344
// satisfy the current channel policy.  Otherwise, a LinkError with a
3345
// valid protocol failure message should be returned in order to signal
3346
// the violation. This call is intended to be used for locally initiated
3347
// payments for which there is no corresponding incoming htlc.
3348
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
3349
        amt lnwire.MilliSatoshi, timeout uint32, heightNow uint32,
3350
        customRecords lnwire.CustomRecords) *LinkError {
409✔
3351

409✔
3352
        l.RLock()
409✔
3353
        policy := l.cfg.FwrdingPolicy
409✔
3354
        l.RUnlock()
409✔
3355

409✔
3356
        // We pass in hop.Source here as this is only used in the Switch when
409✔
3357
        // trying to send over a local link. This causes the fallback mechanism
409✔
3358
        // to occur.
409✔
3359
        return l.canSendHtlc(
409✔
3360
                policy, payHash, amt, timeout, heightNow, hop.Source,
409✔
3361
                customRecords,
409✔
3362
        )
409✔
3363
}
409✔
3364

3365
// canSendHtlc checks whether the given htlc parameters satisfy
3366
// the channel's amount and time lock constraints.
3367
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
3368
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
3369
        heightNow uint32, originalScid lnwire.ShortChannelID,
3370
        customRecords lnwire.CustomRecords) *LinkError {
452✔
3371

452✔
3372
        // As our first sanity check, we'll ensure that the passed HTLC isn't
452✔
3373
        // too small for the next hop. If so, then we'll cancel the HTLC
452✔
3374
        // directly.
452✔
3375
        if amt < policy.MinHTLCOut {
463✔
3376
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
11✔
3377
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
11✔
3378
                        amt)
11✔
3379

11✔
3380
                // As part of the returned error, we'll send our latest routing
11✔
3381
                // policy so the sending node obtains the most up to date data.
11✔
3382
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
22✔
3383
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
11✔
3384
                }
11✔
3385
                failure := l.createFailureWithUpdate(false, originalScid, cb)
11✔
3386
                return NewLinkError(failure)
11✔
3387
        }
3388

3389
        // Next, ensure that the passed HTLC isn't too large. If so, we'll
3390
        // cancel the HTLC directly.
3391
        if policy.MaxHTLC != 0 && amt > policy.MaxHTLC {
450✔
3392
                l.log.Warnf("outgoing htlc(%x) is too large: max_htlc=%v, "+
6✔
3393
                        "htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
6✔
3394

6✔
3395
                // As part of the returned error, we'll send our latest routing
6✔
3396
                // policy so the sending node obtains the most up-to-date data.
6✔
3397
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
12✔
3398
                        return lnwire.NewTemporaryChannelFailure(upd)
6✔
3399
                }
6✔
3400
                failure := l.createFailureWithUpdate(false, originalScid, cb)
6✔
3401
                return NewDetailedLinkError(failure, OutgoingFailureHTLCExceedsMax)
6✔
3402
        }
3403

3404
        // We want to avoid offering an HTLC which will expire in the near
3405
        // future, so we'll reject an HTLC if the outgoing expiration time is
3406
        // too close to the current height.
3407
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
443✔
3408
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
3409
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
3410
                        timeout, heightNow)
2✔
3411

2✔
3412
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
3413
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
3414
                }
2✔
3415
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3416
                return NewLinkError(failure)
2✔
3417
        }
3418

3419
        // Check absolute max delta.
3420
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
440✔
3421
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
3422
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
3423
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
3424

1✔
3425
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
3426
        }
1✔
3427

3428
        // We now check the available bandwidth to see if this HTLC can be
3429
        // forwarded.
3430
        availableBandwidth := l.Bandwidth()
438✔
3431
        auxBandwidth, err := fn.MapOptionZ(
438✔
3432
                l.cfg.AuxTrafficShaper,
438✔
3433
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
438✔
3434
                        var htlcBlob fn.Option[tlv.Blob]
×
3435
                        blob, err := customRecords.Serialize()
×
3436
                        if err != nil {
×
3437
                                return fn.Err[OptionalBandwidth](
×
3438
                                        fmt.Errorf("unable to serialize "+
×
3439
                                                "custom records: %w", err))
×
3440
                        }
×
3441

3442
                        if len(blob) > 0 {
×
3443
                                htlcBlob = fn.Some(blob)
×
3444
                        }
×
3445

3446
                        return l.AuxBandwidth(amt, originalScid, htlcBlob, ts)
×
3447
                },
3448
        ).Unpack()
3449
        if err != nil {
438✔
3450
                l.log.Errorf("Unable to determine aux bandwidth: %v", err)
×
3451
                return NewLinkError(&lnwire.FailTemporaryNodeFailure{})
×
3452
        }
×
3453

3454
        if auxBandwidth.IsHandled && auxBandwidth.Bandwidth.IsSome() {
438✔
3455
                auxBandwidth.Bandwidth.WhenSome(
×
3456
                        func(bandwidth lnwire.MilliSatoshi) {
×
3457
                                availableBandwidth = bandwidth
×
3458
                        },
×
3459
                )
3460
        }
3461

3462
        // Check to see if there is enough balance in this channel.
3463
        if amt > availableBandwidth {
442✔
3464
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
4✔
3465
                        "larger than %v", amt, availableBandwidth)
4✔
3466
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
3467
                        return lnwire.NewTemporaryChannelFailure(upd)
4✔
3468
                }
4✔
3469
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
3470
                return NewDetailedLinkError(
4✔
3471
                        failure, OutgoingFailureInsufficientBalance,
4✔
3472
                )
4✔
3473
        }
3474

3475
        return nil
437✔
3476
}
3477

3478
// AuxBandwidth returns the bandwidth that can be used for a channel, expressed
3479
// in milli-satoshi. This might be different from the regular BTC bandwidth for
3480
// custom channels. This will always return fn.None() for a regular (non-custom)
3481
// channel.
3482
func (l *channelLink) AuxBandwidth(amount lnwire.MilliSatoshi,
3483
        cid lnwire.ShortChannelID, htlcBlob fn.Option[tlv.Blob],
3484
        ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
×
3485

×
3486
        fundingBlob := l.FundingCustomBlob()
×
3487
        shouldHandle, err := ts.ShouldHandleTraffic(cid, fundingBlob, htlcBlob)
×
3488
        if err != nil {
×
3489
                return fn.Err[OptionalBandwidth](fmt.Errorf("traffic shaper "+
×
3490
                        "failed to decide whether to handle traffic: %w", err))
×
3491
        }
×
3492

3493
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
3494
                "traffic: %v", cid, shouldHandle)
×
3495

×
3496
        // If this channel isn't handled by the aux traffic shaper, we'll return
×
3497
        // early.
×
3498
        if !shouldHandle {
×
3499
                return fn.Ok(OptionalBandwidth{
×
3500
                        IsHandled: false,
×
3501
                })
×
3502
        }
×
3503

3504
        // Ask for a specific bandwidth to be used for the channel.
3505
        commitmentBlob := l.CommitmentCustomBlob()
×
3506
        auxBandwidth, err := ts.PaymentBandwidth(
×
3507
                fundingBlob, htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
3508
                l.channel.FetchLatestAuxHTLCView(),
×
3509
        )
×
3510
        if err != nil {
×
3511
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
3512
                        "bandwidth from external traffic shaper: %w", err))
×
3513
        }
×
3514

3515
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
3516
                "bandwidth: %v", cid, auxBandwidth)
×
3517

×
3518
        return fn.Ok(OptionalBandwidth{
×
3519
                IsHandled: true,
×
3520
                Bandwidth: fn.Some(auxBandwidth),
×
3521
        })
×
3522
}
3523

3524
// Stats returns the statistics of channel link.
3525
//
3526
// NOTE: Part of the ChannelLink interface.
3527
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
7✔
3528
        snapshot := l.channel.StateSnapshot()
7✔
3529

7✔
3530
        return snapshot.ChannelCommitment.CommitHeight,
7✔
3531
                snapshot.TotalMSatSent,
7✔
3532
                snapshot.TotalMSatReceived
7✔
3533
}
7✔
3534

3535
// String returns the string representation of channel link.
3536
//
3537
// NOTE: Part of the ChannelLink interface.
3538
func (l *channelLink) String() string {
×
3539
        return l.channel.ChannelPoint().String()
×
3540
}
×
3541

3542
// handleSwitchPacket handles the switch packets. This packets which might be
3543
// forwarded to us from another channel link in case the htlc update came from
3544
// another peer or if the update was created by user
3545
//
3546
// NOTE: Part of the packetHandler interface.
3547
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
482✔
3548
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
482✔
3549
                pkt.inKey(), pkt.outKey())
482✔
3550

482✔
3551
        return l.mailBox.AddPacket(pkt)
482✔
3552
}
482✔
3553

3554
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
3555
// to us from remote peer we have a channel with.
3556
//
3557
// NOTE: Part of the ChannelLink interface.
3558
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3,382✔
3559
        select {
3,382✔
3560
        case <-l.cg.Done():
×
3561
                // Return early if the link is already in the process of
×
3562
                // quitting. It doesn't make sense to hand the message to the
×
3563
                // mailbox here.
×
3564
                return
×
3565
        default:
3,382✔
3566
        }
3567

3568
        err := l.mailBox.AddMessage(message)
3,382✔
3569
        if err != nil {
3,382✔
3570
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
3571
        }
×
3572
}
3573

3574
// updateChannelFee updates the commitment fee-per-kw on this channel by
3575
// committing to an update_fee message.
3576
func (l *channelLink) updateChannelFee(ctx context.Context,
3577
        feePerKw chainfee.SatPerKWeight) error {
3✔
3578

3✔
3579
        l.log.Infof("updating commit fee to %v", feePerKw)
3✔
3580

3✔
3581
        // We skip sending the UpdateFee message if the channel is not
3✔
3582
        // currently eligible to forward messages.
3✔
3583
        if !l.eligibleToUpdate() {
3✔
3584
                l.log.Debugf("skipping fee update for inactive channel")
×
3585
                return nil
×
3586
        }
×
3587

3588
        // Check and see if our proposed fee-rate would make us exceed the fee
3589
        // threshold.
3590
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
3✔
3591
        if err != nil {
3✔
3592
                // This shouldn't typically happen. If it does, it indicates
×
3593
                // something is wrong with our channel state.
×
3594
                return err
×
3595
        }
×
3596

3597
        if thresholdExceeded {
3✔
3598
                return fmt.Errorf("link fee threshold exceeded")
×
3599
        }
×
3600

3601
        // First, we'll update the local fee on our commitment.
3602
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
3603
                return err
×
3604
        }
×
3605

3606
        // The fee passed the channel's validation checks, so we update the
3607
        // mailbox feerate.
3608
        l.mailBox.SetFeeRate(feePerKw)
3✔
3609

3✔
3610
        // We'll then attempt to send a new UpdateFee message, and also lock it
3✔
3611
        // in immediately by triggering a commitment update.
3✔
3612
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
3✔
3613
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
3614
                return err
×
3615
        }
×
3616

3617
        return l.updateCommitTx(ctx)
3✔
3618
}
3619

3620
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3621
// after receiving a revocation from the remote party, and reprocesses them in
3622
// the context of the provided forwarding package. Any settles or fails that
3623
// have already been acknowledged in the forwarding package will not be sent to
3624
// the switch.
3625
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
1,198✔
3626
        if len(fwdPkg.SettleFails) == 0 {
2,081✔
3627
                l.log.Trace("fwd package has no settle/fails to process " +
883✔
3628
                        "exiting early")
883✔
3629

883✔
3630
                return
883✔
3631
        }
883✔
3632

3633
        l.log.Debugf("settle-fail-filter: %v", fwdPkg.SettleFailFilter)
318✔
3634

318✔
3635
        var switchPackets []*htlcPacket
318✔
3636
        for i, update := range fwdPkg.SettleFails {
636✔
3637
                destRef := fwdPkg.DestRef(uint16(i))
318✔
3638

318✔
3639
                // Skip any settles or fails that have already been
318✔
3640
                // acknowledged by the incoming link that originated the
318✔
3641
                // forwarded Add.
318✔
3642
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
318✔
3643
                        continue
×
3644
                }
3645

3646
                // TODO(roasbeef): rework log entries to a shared
3647
                // interface.
3648

3649
                switch msg := update.UpdateMsg.(type) {
318✔
3650
                // A settle for an HTLC we previously forwarded HTLC has been
3651
                // received. So we'll forward the HTLC to the switch which will
3652
                // handle propagating the settle to the prior hop.
3653
                case *lnwire.UpdateFulfillHTLC:
195✔
3654
                        // If hodl.SettleIncoming is requested, we will not
195✔
3655
                        // forward the SETTLE to the switch and will not signal
195✔
3656
                        // a free slot on the commitment transaction.
195✔
3657
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
195✔
3658
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
3659
                                continue
×
3660
                        }
3661

3662
                        settlePacket := &htlcPacket{
195✔
3663
                                outgoingChanID: l.ShortChanID(),
195✔
3664
                                outgoingHTLCID: msg.ID,
195✔
3665
                                destRef:        &destRef,
195✔
3666
                                htlc:           msg,
195✔
3667
                        }
195✔
3668

195✔
3669
                        // Add the packet to the batch to be forwarded, and
195✔
3670
                        // notify the overflow queue that a spare spot has been
195✔
3671
                        // freed up within the commitment state.
195✔
3672
                        switchPackets = append(switchPackets, settlePacket)
195✔
3673

3674
                // A failureCode message for a previously forwarded HTLC has
3675
                // been received. As a result a new slot will be freed up in
3676
                // our commitment state, so we'll forward this to the switch so
3677
                // the backwards undo can continue.
3678
                case *lnwire.UpdateFailHTLC:
126✔
3679
                        // If hodl.SettleIncoming is requested, we will not
126✔
3680
                        // forward the FAIL to the switch and will not signal a
126✔
3681
                        // free slot on the commitment transaction.
126✔
3682
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
126✔
3683
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
3684
                                continue
×
3685
                        }
3686

3687
                        // Fetch the reason the HTLC was canceled so we can
3688
                        // continue to propagate it. This failure originated
3689
                        // from another node, so the linkFailure field is not
3690
                        // set on the packet.
3691
                        failPacket := &htlcPacket{
126✔
3692
                                outgoingChanID: l.ShortChanID(),
126✔
3693
                                outgoingHTLCID: msg.ID,
126✔
3694
                                destRef:        &destRef,
126✔
3695
                                htlc:           msg,
126✔
3696
                        }
126✔
3697

126✔
3698
                        l.log.Debugf("Failed to send HTLC with ID=%d", msg.ID)
126✔
3699

126✔
3700
                        // If the failure message lacks an HMAC (but includes
126✔
3701
                        // the 4 bytes for encoding the message and padding
126✔
3702
                        // lengths, then this means that we received it as an
126✔
3703
                        // UpdateFailMalformedHTLC. As a result, we'll signal
126✔
3704
                        // that we need to convert this error within the switch
126✔
3705
                        // to an actual error, by encrypting it as if we were
126✔
3706
                        // the originating hop.
126✔
3707
                        convertedErrorSize := lnwire.FailureMessageLength + 4
126✔
3708
                        if len(msg.Reason) == convertedErrorSize {
132✔
3709
                                failPacket.convertedError = true
6✔
3710
                        }
6✔
3711

3712
                        // Add the packet to the batch to be forwarded, and
3713
                        // notify the overflow queue that a spare spot has been
3714
                        // freed up within the commitment state.
3715
                        switchPackets = append(switchPackets, failPacket)
126✔
3716
                }
3717
        }
3718

3719
        // Only spawn the task forward packets we have a non-zero number.
3720
        if len(switchPackets) > 0 {
636✔
3721
                go l.forwardBatch(false, switchPackets...)
318✔
3722
        }
318✔
3723
}
3724

3725
// processRemoteAdds serially processes each of the Add payment descriptors
3726
// which have been "locked-in" by receiving a revocation from the remote party.
3727
// The forwarding package provided instructs how to process this batch,
3728
// indicating whether this is the first time these Adds are being processed, or
3729
// whether we are reprocessing as a result of a failure or restart. Adds that
3730
// have already been acknowledged in the forwarding package will be ignored.
3731
//
3732
//nolint:funlen
3733
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
1,200✔
3734
        // Exit early if there are no adds to process.
1,200✔
3735
        if len(fwdPkg.Adds) == 0 {
2,084✔
3736
                l.log.Trace("fwd package has no adds to process exiting early")
884✔
3737

884✔
3738
                return
884✔
3739
        }
884✔
3740

3741
        l.log.Tracef("processing %d remote adds for height %d",
319✔
3742
                len(fwdPkg.Adds), fwdPkg.Height)
319✔
3743

319✔
3744
        decodeReqs := make(
319✔
3745
                []hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds),
319✔
3746
        )
319✔
3747
        for _, update := range fwdPkg.Adds {
771✔
3748
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
904✔
3749
                        // Before adding the new htlc to the state machine,
452✔
3750
                        // parse the onion object in order to obtain the
452✔
3751
                        // routing information with DecodeHopIterator function
452✔
3752
                        // which process the Sphinx packet.
452✔
3753
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
452✔
3754

452✔
3755
                        req := hop.DecodeHopIteratorRequest{
452✔
3756
                                OnionReader:    onionReader,
452✔
3757
                                RHash:          msg.PaymentHash[:],
452✔
3758
                                IncomingCltv:   msg.Expiry,
452✔
3759
                                IncomingAmount: msg.Amount,
452✔
3760
                                BlindingPoint:  msg.BlindingPoint,
452✔
3761
                        }
452✔
3762

452✔
3763
                        decodeReqs = append(decodeReqs, req)
452✔
3764
                }
452✔
3765
        }
3766

3767
        // Atomically decode the incoming htlcs, simultaneously checking for
3768
        // replay attempts. A particular index in the returned, spare list of
3769
        // channel iterators should only be used if the failure code at the
3770
        // same index is lnwire.FailCodeNone.
3771
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
319✔
3772
                fwdPkg.ID(), decodeReqs,
319✔
3773
        )
319✔
3774
        if sphinxErr != nil {
319✔
3775
                l.failf(LinkFailureError{code: ErrInternalError},
×
3776
                        "unable to decode hop iterators: %v", sphinxErr)
×
3777
                return
×
3778
        }
×
3779

3780
        var switchPackets []*htlcPacket
319✔
3781

319✔
3782
        for i, update := range fwdPkg.Adds {
771✔
3783
                idx := uint16(i)
452✔
3784

452✔
3785
                //nolint:forcetypeassert
452✔
3786
                add := *update.UpdateMsg.(*lnwire.UpdateAddHTLC)
452✔
3787
                sourceRef := fwdPkg.SourceRef(idx)
452✔
3788

452✔
3789
                if fwdPkg.State == channeldb.FwdStateProcessed &&
452✔
3790
                        fwdPkg.AckFilter.Contains(idx) {
452✔
3791

×
3792
                        // If this index is already found in the ack filter,
×
3793
                        // the response to this forwarding decision has already
×
3794
                        // been committed by one of our commitment txns. ADDs
×
3795
                        // in this state are waiting for the rest of the fwding
×
3796
                        // package to get acked before being garbage collected.
×
3797
                        continue
×
3798
                }
3799

3800
                // An incoming HTLC add has been full-locked in. As a result we
3801
                // can now examine the forwarding details of the HTLC, and the
3802
                // HTLC itself to decide if: we should forward it, cancel it,
3803
                // or are able to settle it (and it adheres to our fee related
3804
                // constraints).
3805

3806
                // Before adding the new htlc to the state machine, parse the
3807
                // onion object in order to obtain the routing information with
3808
                // DecodeHopIterator function which process the Sphinx packet.
3809
                chanIterator, failureCode := decodeResps[i].Result()
452✔
3810
                if failureCode != lnwire.CodeNone {
457✔
3811
                        // If we're unable to process the onion blob then we
5✔
3812
                        // should send the malformed htlc error to payment
5✔
3813
                        // sender.
5✔
3814
                        l.sendMalformedHTLCError(
5✔
3815
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
5✔
3816
                        )
5✔
3817

5✔
3818
                        l.log.Errorf("unable to decode onion hop "+
5✔
3819
                                "iterator: %v", failureCode)
5✔
3820
                        continue
5✔
3821
                }
3822

3823
                heightNow := l.cfg.BestHeight()
450✔
3824

450✔
3825
                pld, routeRole, pldErr := chanIterator.HopPayload()
450✔
3826
                if pldErr != nil {
453✔
3827
                        // If we're unable to process the onion payload, or we
3✔
3828
                        // received invalid onion payload failure, then we
3✔
3829
                        // should send an error back to the caller so the HTLC
3✔
3830
                        // can be canceled.
3✔
3831
                        var failedType uint64
3✔
3832

3✔
3833
                        // We need to get the underlying error value, so we
3✔
3834
                        // can't use errors.As as suggested by the linter.
3✔
3835
                        //nolint:errorlint
3✔
3836
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
3✔
3837
                                failedType = uint64(e.Type)
×
3838
                        }
×
3839

3840
                        // If we couldn't parse the payload, make our best
3841
                        // effort at creating an error encrypter that knows
3842
                        // what blinding type we were, but if we couldn't
3843
                        // parse the payload we have no way of knowing whether
3844
                        // we were the introduction node or not.
3845
                        //
3846
                        //nolint:ll
3847
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
3✔
3848
                                l.cfg.ExtractErrorEncrypter,
3✔
3849
                                // We need our route role here because we
3✔
3850
                                // couldn't parse or validate the payload.
3✔
3851
                                routeRole == hop.RouteRoleIntroduction,
3✔
3852
                        )
3✔
3853
                        if failCode != lnwire.CodeNone {
3✔
3854
                                l.log.Errorf("could not extract error "+
×
3855
                                        "encrypter: %v", pldErr)
×
3856

×
3857
                                // We can't process this htlc, send back
×
3858
                                // malformed.
×
3859
                                l.sendMalformedHTLCError(
×
3860
                                        add.ID, failureCode, add.OnionBlob,
×
3861
                                        &sourceRef,
×
3862
                                )
×
3863

×
3864
                                continue
×
3865
                        }
3866

3867
                        // TODO: currently none of the test unit infrastructure
3868
                        // is setup to handle TLV payloads, so testing this
3869
                        // would require implementing a separate mock iterator
3870
                        // for TLV payloads that also supports injecting invalid
3871
                        // payloads. Deferring this non-trival effort till a
3872
                        // later date
3873
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
3✔
3874

3✔
3875
                        l.sendHTLCError(
3✔
3876
                                add, sourceRef, NewLinkError(failure),
3✔
3877
                                obfuscator, false,
3✔
3878
                        )
3✔
3879

3✔
3880
                        l.log.Errorf("unable to decode forwarding "+
3✔
3881
                                "instructions: %v", pldErr)
3✔
3882

3✔
3883
                        continue
3✔
3884
                }
3885

3886
                // Retrieve onion obfuscator from onion blob in order to
3887
                // produce initial obfuscation of the onion failureCode.
3888
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
450✔
3889
                        l.cfg.ExtractErrorEncrypter,
450✔
3890
                        routeRole == hop.RouteRoleIntroduction,
450✔
3891
                )
450✔
3892
                if failureCode != lnwire.CodeNone {
451✔
3893
                        // If we're unable to process the onion blob than we
1✔
3894
                        // should send the malformed htlc error to payment
1✔
3895
                        // sender.
1✔
3896
                        l.sendMalformedHTLCError(
1✔
3897
                                add.ID, failureCode, add.OnionBlob,
1✔
3898
                                &sourceRef,
1✔
3899
                        )
1✔
3900

1✔
3901
                        l.log.Errorf("unable to decode onion "+
1✔
3902
                                "obfuscator: %v", failureCode)
1✔
3903

1✔
3904
                        continue
1✔
3905
                }
3906

3907
                fwdInfo := pld.ForwardingInfo()
449✔
3908

449✔
3909
                // Check whether the payload we've just processed uses our
449✔
3910
                // node as the introduction point (gave us a blinding key in
449✔
3911
                // the payload itself) and fail it back if we don't support
449✔
3912
                // route blinding.
449✔
3913
                if fwdInfo.NextBlinding.IsSome() &&
449✔
3914
                        l.cfg.DisallowRouteBlinding {
452✔
3915

3✔
3916
                        failure := lnwire.NewInvalidBlinding(
3✔
3917
                                fn.Some(add.OnionBlob),
3✔
3918
                        )
3✔
3919

3✔
3920
                        l.sendHTLCError(
3✔
3921
                                add, sourceRef, NewLinkError(failure),
3✔
3922
                                obfuscator, false,
3✔
3923
                        )
3✔
3924

3✔
3925
                        l.log.Error("rejected htlc that uses use as an " +
3✔
3926
                                "introduction point when we do not support " +
3✔
3927
                                "route blinding")
3✔
3928

3✔
3929
                        continue
3✔
3930
                }
3931

3932
                switch fwdInfo.NextHop {
449✔
3933
                case hop.Exit:
413✔
3934
                        err := l.processExitHop(
413✔
3935
                                add, sourceRef, obfuscator, fwdInfo,
413✔
3936
                                heightNow, pld,
413✔
3937
                        )
413✔
3938
                        if err != nil {
413✔
3939
                                l.failf(LinkFailureError{
×
3940
                                        code: ErrInternalError,
×
3941
                                }, err.Error()) //nolint
×
3942

×
3943
                                return
×
3944
                        }
×
3945

3946
                // There are additional channels left within this route. So
3947
                // we'll simply do some forwarding package book-keeping.
3948
                default:
39✔
3949
                        // If hodl.AddIncoming is requested, we will not
39✔
3950
                        // validate the forwarded ADD, nor will we send the
39✔
3951
                        // packet to the htlc switch.
39✔
3952
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
39✔
3953
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3954
                                continue
×
3955
                        }
3956

3957
                        endorseValue := l.experimentalEndorsement(
39✔
3958
                                record.CustomSet(add.CustomRecords),
39✔
3959
                        )
39✔
3960
                        endorseType := uint64(
39✔
3961
                                lnwire.ExperimentalEndorsementType,
39✔
3962
                        )
39✔
3963

39✔
3964
                        switch fwdPkg.State {
39✔
3965
                        case channeldb.FwdStateProcessed:
3✔
3966
                                // This add was not forwarded on the previous
3✔
3967
                                // processing phase, run it through our
3✔
3968
                                // validation pipeline to reproduce an error.
3✔
3969
                                // This may trigger a different error due to
3✔
3970
                                // expiring timelocks, but we expect that an
3✔
3971
                                // error will be reproduced.
3✔
3972
                                if !fwdPkg.FwdFilter.Contains(idx) {
3✔
3973
                                        break
×
3974
                                }
3975

3976
                                // Otherwise, it was already processed, we can
3977
                                // can collect it and continue.
3978
                                outgoingAdd := &lnwire.UpdateAddHTLC{
3✔
3979
                                        Expiry:        fwdInfo.OutgoingCTLV,
3✔
3980
                                        Amount:        fwdInfo.AmountToForward,
3✔
3981
                                        PaymentHash:   add.PaymentHash,
3✔
3982
                                        BlindingPoint: fwdInfo.NextBlinding,
3✔
3983
                                }
3✔
3984

3✔
3985
                                endorseValue.WhenSome(func(e byte) {
6✔
3986
                                        custRecords := map[uint64][]byte{
3✔
3987
                                                endorseType: {e},
3✔
3988
                                        }
3✔
3989

3✔
3990
                                        outgoingAdd.CustomRecords = custRecords
3✔
3991
                                })
3✔
3992

3993
                                // Finally, we'll encode the onion packet for
3994
                                // the _next_ hop using the hop iterator
3995
                                // decoded for the current hop.
3996
                                buf := bytes.NewBuffer(
3✔
3997
                                        outgoingAdd.OnionBlob[0:0],
3✔
3998
                                )
3✔
3999

3✔
4000
                                // We know this cannot fail, as this ADD
3✔
4001
                                // was marked forwarded in a previous
3✔
4002
                                // round of processing.
3✔
4003
                                chanIterator.EncodeNextHop(buf)
3✔
4004

3✔
4005
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
4006

3✔
4007
                                //nolint:ll
3✔
4008
                                updatePacket := &htlcPacket{
3✔
4009
                                        incomingChanID:       l.ShortChanID(),
3✔
4010
                                        incomingHTLCID:       add.ID,
3✔
4011
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
4012
                                        sourceRef:            &sourceRef,
3✔
4013
                                        incomingAmount:       add.Amount,
3✔
4014
                                        amount:               outgoingAdd.Amount,
3✔
4015
                                        htlc:                 outgoingAdd,
3✔
4016
                                        obfuscator:           obfuscator,
3✔
4017
                                        incomingTimeout:      add.Expiry,
3✔
4018
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
4019
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
4020
                                        inboundFee:           inboundFee,
3✔
4021
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
4022
                                }
3✔
4023
                                switchPackets = append(
3✔
4024
                                        switchPackets, updatePacket,
3✔
4025
                                )
3✔
4026

3✔
4027
                                continue
3✔
4028
                        }
4029

4030
                        // TODO(roasbeef): ensure don't accept outrageous
4031
                        // timeout for htlc
4032

4033
                        // With all our forwarding constraints met, we'll
4034
                        // create the outgoing HTLC using the parameters as
4035
                        // specified in the forwarding info.
4036
                        addMsg := &lnwire.UpdateAddHTLC{
39✔
4037
                                Expiry:        fwdInfo.OutgoingCTLV,
39✔
4038
                                Amount:        fwdInfo.AmountToForward,
39✔
4039
                                PaymentHash:   add.PaymentHash,
39✔
4040
                                BlindingPoint: fwdInfo.NextBlinding,
39✔
4041
                        }
39✔
4042

39✔
4043
                        endorseValue.WhenSome(func(e byte) {
78✔
4044
                                addMsg.CustomRecords = map[uint64][]byte{
39✔
4045
                                        endorseType: {e},
39✔
4046
                                }
39✔
4047
                        })
39✔
4048

4049
                        // Finally, we'll encode the onion packet for the
4050
                        // _next_ hop using the hop iterator decoded for the
4051
                        // current hop.
4052
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
39✔
4053
                        err := chanIterator.EncodeNextHop(buf)
39✔
4054
                        if err != nil {
39✔
4055
                                l.log.Errorf("unable to encode the "+
×
4056
                                        "remaining route %v", err)
×
4057

×
4058
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
4059
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
4060
                                }
×
4061

4062
                                failure := l.createFailureWithUpdate(
×
4063
                                        true, hop.Source, cb,
×
4064
                                )
×
4065

×
4066
                                l.sendHTLCError(
×
4067
                                        add, sourceRef, NewLinkError(failure),
×
4068
                                        obfuscator, false,
×
4069
                                )
×
4070
                                continue
×
4071
                        }
4072

4073
                        // Now that this add has been reprocessed, only append
4074
                        // it to our list of packets to forward to the switch
4075
                        // this is the first time processing the add. If the
4076
                        // fwd pkg has already been processed, then we entered
4077
                        // the above section to recreate a previous error.  If
4078
                        // the packet had previously been forwarded, it would
4079
                        // have been added to switchPackets at the top of this
4080
                        // section.
4081
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
78✔
4082
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
39✔
4083

39✔
4084
                                //nolint:ll
39✔
4085
                                updatePacket := &htlcPacket{
39✔
4086
                                        incomingChanID:       l.ShortChanID(),
39✔
4087
                                        incomingHTLCID:       add.ID,
39✔
4088
                                        outgoingChanID:       fwdInfo.NextHop,
39✔
4089
                                        sourceRef:            &sourceRef,
39✔
4090
                                        incomingAmount:       add.Amount,
39✔
4091
                                        amount:               addMsg.Amount,
39✔
4092
                                        htlc:                 addMsg,
39✔
4093
                                        obfuscator:           obfuscator,
39✔
4094
                                        incomingTimeout:      add.Expiry,
39✔
4095
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
39✔
4096
                                        inOnionCustomRecords: pld.CustomRecords(),
39✔
4097
                                        inboundFee:           inboundFee,
39✔
4098
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
39✔
4099
                                }
39✔
4100

39✔
4101
                                fwdPkg.FwdFilter.Set(idx)
39✔
4102
                                switchPackets = append(switchPackets,
39✔
4103
                                        updatePacket)
39✔
4104
                        }
39✔
4105
                }
4106
        }
4107

4108
        // Commit the htlcs we are intending to forward if this package has not
4109
        // been fully processed.
4110
        if fwdPkg.State == channeldb.FwdStateLockedIn {
635✔
4111
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
316✔
4112
                if err != nil {
316✔
4113
                        l.failf(LinkFailureError{code: ErrInternalError},
×
4114
                                "unable to set fwd filter: %v", err)
×
4115
                        return
×
4116
                }
×
4117
        }
4118

4119
        if len(switchPackets) == 0 {
602✔
4120
                return
283✔
4121
        }
283✔
4122

4123
        replay := fwdPkg.State != channeldb.FwdStateLockedIn
39✔
4124

39✔
4125
        l.log.Debugf("forwarding %d packets to switch: replay=%v",
39✔
4126
                len(switchPackets), replay)
39✔
4127

39✔
4128
        // NOTE: This call is made synchronous so that we ensure all circuits
39✔
4129
        // are committed in the exact order that they are processed in the link.
39✔
4130
        // Failing to do this could cause reorderings/gaps in the range of
39✔
4131
        // opened circuits, which violates assumptions made by the circuit
39✔
4132
        // trimming.
39✔
4133
        l.forwardBatch(replay, switchPackets...)
39✔
4134
}
4135

4136
// experimentalEndorsement returns the value to set for our outgoing
4137
// experimental endorsement field, and a boolean indicating whether it should
4138
// be populated on the outgoing htlc.
4139
func (l *channelLink) experimentalEndorsement(
4140
        customUpdateAdd record.CustomSet) fn.Option[byte] {
39✔
4141

39✔
4142
        // Only relay experimental signal if we are within the experiment
39✔
4143
        // period.
39✔
4144
        if !l.cfg.ShouldFwdExpEndorsement() {
42✔
4145
                return fn.None[byte]()
3✔
4146
        }
3✔
4147

4148
        // If we don't have any custom records or the experimental field is
4149
        // not set, just forward a zero value.
4150
        if len(customUpdateAdd) == 0 {
78✔
4151
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
39✔
4152
        }
39✔
4153

4154
        t := uint64(lnwire.ExperimentalEndorsementType)
3✔
4155
        value, set := customUpdateAdd[t]
3✔
4156
        if !set {
3✔
4157
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4158
        }
×
4159

4160
        // We expect at least one byte for this field, consider it invalid if
4161
        // it has no data and just forward a zero value.
4162
        if len(value) == 0 {
3✔
4163
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4164
        }
×
4165

4166
        // Only forward endorsed if the incoming link is endorsed.
4167
        if value[0] == lnwire.ExperimentalEndorsed {
6✔
4168
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
3✔
4169
        }
3✔
4170

4171
        // Forward as unendorsed otherwise, including cases where we've
4172
        // received an invalid value that uses more than 3 bits of information.
4173
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
4174
}
4175

4176
// processExitHop handles an htlc for which this link is the exit hop. It
4177
// returns a boolean indicating whether the commitment tx needs an update.
4178
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
4179
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
4180
        fwdInfo hop.ForwardingInfo, heightNow uint32,
4181
        payload invoices.Payload) error {
413✔
4182

413✔
4183
        // If hodl.ExitSettle is requested, we will not validate the final hop's
413✔
4184
        // ADD, nor will we settle the corresponding invoice or respond with the
413✔
4185
        // preimage.
413✔
4186
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
523✔
4187
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
110✔
4188
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
110✔
4189

110✔
4190
                return nil
110✔
4191
        }
110✔
4192

4193
        // In case the traffic shaper is active, we'll check if the HTLC has
4194
        // custom records and skip the amount check in the onion payload below.
4195
        isCustomHTLC := fn.MapOptionZ(
306✔
4196
                l.cfg.AuxTrafficShaper,
306✔
4197
                func(ts AuxTrafficShaper) bool {
306✔
4198
                        return ts.IsCustomHTLC(add.CustomRecords)
×
4199
                },
×
4200
        )
4201

4202
        // As we're the exit hop, we'll double check the hop-payload included in
4203
        // the HTLC to ensure that it was crafted correctly by the sender and
4204
        // is compatible with the HTLC we were extended. If an external
4205
        // validator is active we might bypass the amount check.
4206
        if !isCustomHTLC && add.Amount < fwdInfo.AmountToForward {
406✔
4207
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
100✔
4208
                        "incompatible value: expected <=%v, got %v",
100✔
4209
                        add.PaymentHash, add.Amount, fwdInfo.AmountToForward)
100✔
4210

100✔
4211
                failure := NewLinkError(
100✔
4212
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
100✔
4213
                )
100✔
4214
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
100✔
4215

100✔
4216
                return nil
100✔
4217
        }
100✔
4218

4219
        // We'll also ensure that our time-lock value has been computed
4220
        // correctly.
4221
        if add.Expiry < fwdInfo.OutgoingCTLV {
207✔
4222
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
4223
                        "incompatible time-lock: expected <=%v, got %v",
1✔
4224
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
1✔
4225

1✔
4226
                failure := NewLinkError(
1✔
4227
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
1✔
4228
                )
1✔
4229

1✔
4230
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
1✔
4231

1✔
4232
                return nil
1✔
4233
        }
1✔
4234

4235
        // Notify the invoiceRegistry of the exit hop htlc. If we crash right
4236
        // after this, this code will be re-executed after restart. We will
4237
        // receive back a resolution event.
4238
        invoiceHash := lntypes.Hash(add.PaymentHash)
205✔
4239

205✔
4240
        circuitKey := models.CircuitKey{
205✔
4241
                ChanID: l.ShortChanID(),
205✔
4242
                HtlcID: add.ID,
205✔
4243
        }
205✔
4244

205✔
4245
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
205✔
4246
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
205✔
4247
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
205✔
4248
        )
205✔
4249
        if err != nil {
205✔
4250
                return err
×
4251
        }
×
4252

4253
        // Create a hodlHtlc struct and decide either resolved now or later.
4254
        htlc := hodlHtlc{
205✔
4255
                add:        add,
205✔
4256
                sourceRef:  sourceRef,
205✔
4257
                obfuscator: obfuscator,
205✔
4258
        }
205✔
4259

205✔
4260
        // If the event is nil, the invoice is being held, so we save payment
205✔
4261
        // descriptor for future reference.
205✔
4262
        if event == nil {
264✔
4263
                l.hodlMap[circuitKey] = htlc
59✔
4264
                return nil
59✔
4265
        }
59✔
4266

4267
        // Process the received resolution.
4268
        return l.processHtlcResolution(event, htlc)
149✔
4269
}
4270

4271
// settleHTLC settles the HTLC on the channel.
4272
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
4273
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
200✔
4274

200✔
4275
        hash := preimage.Hash()
200✔
4276

200✔
4277
        l.log.Infof("settling htlc %v as exit hop", hash)
200✔
4278

200✔
4279
        err := l.channel.SettleHTLC(
200✔
4280
                preimage, htlcIndex, &sourceRef, nil, nil,
200✔
4281
        )
200✔
4282
        if err != nil {
200✔
4283
                return fmt.Errorf("unable to settle htlc: %w", err)
×
4284
        }
×
4285

4286
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
4287
        // fake one before sending it to the peer.
4288
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
203✔
4289
                l.log.Warnf(hodl.BogusSettle.Warning())
3✔
4290
                preimage = [32]byte{}
3✔
4291
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
3✔
4292
        }
3✔
4293

4294
        // HTLC was successfully settled locally send notification about it
4295
        // remote peer.
4296
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
200✔
4297
                ChanID:          l.ChanID(),
200✔
4298
                ID:              htlcIndex,
200✔
4299
                PaymentPreimage: preimage,
200✔
4300
        })
200✔
4301

200✔
4302
        // Once we have successfully settled the htlc, notify a settle event.
200✔
4303
        l.cfg.HtlcNotifier.NotifySettleEvent(
200✔
4304
                HtlcKey{
200✔
4305
                        IncomingCircuit: models.CircuitKey{
200✔
4306
                                ChanID: l.ShortChanID(),
200✔
4307
                                HtlcID: htlcIndex,
200✔
4308
                        },
200✔
4309
                },
200✔
4310
                preimage,
200✔
4311
                HtlcEventTypeReceive,
200✔
4312
        )
200✔
4313

200✔
4314
        return nil
200✔
4315
}
4316

4317
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
4318
// err chan for the individual responses. This method is intended to be spawned
4319
// as a goroutine so the responses can be handled in the background.
4320
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
579✔
4321
        // Don't forward packets for which we already have a response in our
579✔
4322
        // mailbox. This could happen if a packet fails and is buffered in the
579✔
4323
        // mailbox, and the incoming link flaps.
579✔
4324
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
579✔
4325
        for _, pkt := range packets {
1,158✔
4326
                if l.mailBox.HasPacket(pkt.inKey()) {
582✔
4327
                        continue
3✔
4328
                }
4329

4330
                filteredPkts = append(filteredPkts, pkt)
579✔
4331
        }
4332

4333
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
579✔
4334
        if err != nil {
590✔
4335
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
4336
                        "settle/fail over htlcswitch: %v", err)
11✔
4337
        }
11✔
4338
}
4339

4340
// sendHTLCError functions cancels HTLC and send cancel message back to the
4341
// peer from which HTLC was received.
4342
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
4343
        sourceRef channeldb.AddRef, failure *LinkError,
4344
        e hop.ErrorEncrypter, isReceive bool) {
108✔
4345

108✔
4346
        reason, err := e.EncryptFirstHop(failure.WireMessage())
108✔
4347
        if err != nil {
108✔
4348
                l.log.Errorf("unable to obfuscate error: %v", err)
×
4349
                return
×
4350
        }
×
4351

4352
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
108✔
4353
        if err != nil {
108✔
4354
                l.log.Errorf("unable cancel htlc: %v", err)
×
4355
                return
×
4356
        }
×
4357

4358
        // Send the appropriate failure message depending on whether we're
4359
        // in a blinded route or not.
4360
        if err := l.sendIncomingHTLCFailureMsg(
108✔
4361
                add.ID, e, reason,
108✔
4362
        ); err != nil {
108✔
4363
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
4364
                return
×
4365
        }
×
4366

4367
        // Notify a link failure on our incoming link. Outgoing htlc information
4368
        // is not available at this point, because we have not decrypted the
4369
        // onion, so it is excluded.
4370
        var eventType HtlcEventType
108✔
4371
        if isReceive {
216✔
4372
                eventType = HtlcEventTypeReceive
108✔
4373
        } else {
111✔
4374
                eventType = HtlcEventTypeForward
3✔
4375
        }
3✔
4376

4377
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
108✔
4378
                HtlcKey{
108✔
4379
                        IncomingCircuit: models.CircuitKey{
108✔
4380
                                ChanID: l.ShortChanID(),
108✔
4381
                                HtlcID: add.ID,
108✔
4382
                        },
108✔
4383
                },
108✔
4384
                HtlcInfo{
108✔
4385
                        IncomingTimeLock: add.Expiry,
108✔
4386
                        IncomingAmt:      add.Amount,
108✔
4387
                },
108✔
4388
                eventType,
108✔
4389
                failure,
108✔
4390
                true,
108✔
4391
        )
108✔
4392
}
4393

4394
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
4395
// peer from which the HTLC was received. This function is primarily used to
4396
// handle the special requirements of route blinding, specifically:
4397
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
4398
// - Introduction nodes should return regular HTLC failure messages.
4399
//
4400
// It accepts the original opaque failure, which will be used in the case
4401
// that we're not part of a blinded route and an error encrypter that'll be
4402
// used if we are the introduction node and need to present an error as if
4403
// we're the failing party.
4404
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
4405
        e hop.ErrorEncrypter,
4406
        originalFailure lnwire.OpaqueReason) error {
124✔
4407

124✔
4408
        var msg lnwire.Message
124✔
4409
        switch {
124✔
4410
        // Our circuit's error encrypter will be nil if this was a locally
4411
        // initiated payment. We can only hit a blinded error for a locally
4412
        // initiated payment if we allow ourselves to be picked as the
4413
        // introduction node for our own payments and in that case we
4414
        // shouldn't reach this code. To prevent the HTLC getting stuck,
4415
        // we fail it back and log an error.
4416
        // code.
4417
        case e == nil:
×
4418
                msg = &lnwire.UpdateFailHTLC{
×
4419
                        ChanID: l.ChanID(),
×
4420
                        ID:     htlcIndex,
×
4421
                        Reason: originalFailure,
×
4422
                }
×
4423

×
4424
                l.log.Errorf("Unexpected blinded failure when "+
×
4425
                        "we are the sending node, incoming htlc: %v(%v)",
×
4426
                        l.ShortChanID(), htlcIndex)
×
4427

4428
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4429
        // transformation on the error message and can just send the original.
4430
        case !e.Type().IsBlinded():
124✔
4431
                msg = &lnwire.UpdateFailHTLC{
124✔
4432
                        ChanID: l.ChanID(),
124✔
4433
                        ID:     htlcIndex,
124✔
4434
                        Reason: originalFailure,
124✔
4435
                }
124✔
4436

4437
        // When we're the introduction node, we need to convert the error to
4438
        // a UpdateFailHTLC.
4439
        case e.Type() == hop.EncrypterTypeIntroduction:
3✔
4440
                l.log.Debugf("Introduction blinded node switching out failure "+
3✔
4441
                        "error: %v", htlcIndex)
3✔
4442

3✔
4443
                // The specification does not require that we set the onion
3✔
4444
                // blob.
3✔
4445
                failureMsg := lnwire.NewInvalidBlinding(
3✔
4446
                        fn.None[[lnwire.OnionPacketSize]byte](),
3✔
4447
                )
3✔
4448
                reason, err := e.EncryptFirstHop(failureMsg)
3✔
4449
                if err != nil {
3✔
4450
                        return err
×
4451
                }
×
4452

4453
                msg = &lnwire.UpdateFailHTLC{
3✔
4454
                        ChanID: l.ChanID(),
3✔
4455
                        ID:     htlcIndex,
3✔
4456
                        Reason: reason,
3✔
4457
                }
3✔
4458

4459
        // If we are a relaying node, we need to switch out any error that
4460
        // we've received to a malformed HTLC error.
4461
        case e.Type() == hop.EncrypterTypeRelaying:
3✔
4462
                l.log.Debugf("Relaying blinded node switching out malformed "+
3✔
4463
                        "error: %v", htlcIndex)
3✔
4464

3✔
4465
                msg = &lnwire.UpdateFailMalformedHTLC{
3✔
4466
                        ChanID:      l.ChanID(),
3✔
4467
                        ID:          htlcIndex,
3✔
4468
                        FailureCode: lnwire.CodeInvalidBlinding,
3✔
4469
                }
3✔
4470

4471
        default:
×
4472
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4473
        }
4474

4475
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
124✔
4476
                l.log.Warnf("Send update fail failed: %v", err)
×
4477
        }
×
4478

4479
        return nil
124✔
4480
}
4481

4482
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4483
// to the payment sender.
4484
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4485
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
4486
        sourceRef *channeldb.AddRef) {
6✔
4487

6✔
4488
        shaOnionBlob := sha256.Sum256(onionBlob[:])
6✔
4489
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
6✔
4490
        if err != nil {
6✔
4491
                l.log.Errorf("unable cancel htlc: %v", err)
×
4492
                return
×
4493
        }
×
4494

4495
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
6✔
4496
                ChanID:       l.ChanID(),
6✔
4497
                ID:           htlcIndex,
6✔
4498
                ShaOnionBlob: shaOnionBlob,
6✔
4499
                FailureCode:  code,
6✔
4500
        })
6✔
4501
}
4502

4503
// failf is a function which is used to encapsulate the action necessary for
4504
// properly failing the link. It takes a LinkFailureError, which will be passed
4505
// to the OnChannelFailure closure, in order for it to determine if we should
4506
// force close the channel, and if we should send an error message to the
4507
// remote peer.
4508
func (l *channelLink) failf(linkErr LinkFailureError, format string,
4509
        a ...interface{}) {
17✔
4510

17✔
4511
        reason := fmt.Errorf(format, a...)
17✔
4512

17✔
4513
        // Return if we have already notified about a failure.
17✔
4514
        if l.failed {
20✔
4515
                l.log.Warnf("ignoring link failure (%v), as link already "+
3✔
4516
                        "failed", reason)
3✔
4517
                return
3✔
4518
        }
3✔
4519

4520
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
17✔
4521

17✔
4522
        // Set failed, such that we won't process any more updates, and notify
17✔
4523
        // the peer about the failure.
17✔
4524
        l.failed = true
17✔
4525
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
17✔
4526
}
4527

4528
// FundingCustomBlob returns the custom funding blob of the channel that this
4529
// link is associated with. The funding blob represents static information about
4530
// the channel that was created at channel funding time.
4531
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
4532
        if l.channel == nil {
×
4533
                return fn.None[tlv.Blob]()
×
4534
        }
×
4535

4536
        if l.channel.State() == nil {
×
4537
                return fn.None[tlv.Blob]()
×
4538
        }
×
4539

4540
        return l.channel.State().CustomBlob
×
4541
}
4542

4543
// CommitmentCustomBlob returns the custom blob of the current local commitment
4544
// of the channel that this link is associated with.
4545
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
4546
        if l.channel == nil {
×
4547
                return fn.None[tlv.Blob]()
×
4548
        }
×
4549

4550
        return l.channel.LocalCommitmentBlob()
×
4551
}
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