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

lightningnetwork / lnd / 16005100421

01 Jul 2025 04:35PM UTC coverage: 57.772% (+0.6%) from 57.216%
16005100421

Pull #10018

github

web-flow
Merge 0b73fe73c into d8a12a5e5
Pull Request #10018: Refactor link's long methods

390 of 746 new or added lines in 1 file covered. (52.28%)

41 existing lines in 11 files now uncovered.

98433 of 170383 relevant lines covered (57.77%)

1.79 hits per line

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

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

53
        // DefaultMinLinkFeeUpdateTimeout represents the minimum interval in
54
        // which a link should propose to update its commitment fee rate.
55
        DefaultMinLinkFeeUpdateTimeout = 10 * time.Minute
56

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

61
        // DefaultMaxLinkFeeAllocation is the highest allocation we'll allow
62
        // a channel's commitment fee to be of its balance. This only applies to
63
        // the initiator of the channel.
64
        DefaultMaxLinkFeeAllocation float64 = 0.5
65
)
66

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

3✔
77
        return f.BaseFee + (htlcAmt*f.FeeRate)/1000000
3✔
78
}
3✔
79

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

90
        // Circuits provides restricted access to the switch's circuit map,
91
        // allowing the link to open and close circuits.
92
        Circuits CircuitModifier
93

94
        // BestHeight returns the best known height.
95
        BestHeight func() uint32
96

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

103
        // DecodeHopIterators facilitates batched decoding of HTLC Sphinx onion
104
        // blobs, which are then used to inform how to forward an HTLC.
105
        //
106
        // NOTE: This function assumes the same set of readers and preimages
107
        // are always presented for the same identifier. The last boolean is
108
        // used to decide whether this is a reforwarding or not - when it's
109
        // reforwarding, we skip the replay check enforced in our decay log.
110
        DecodeHopIterators func([]byte, []hop.DecodeHopIteratorRequest, bool) (
111
                []hop.DecodeHopIteratorResponse, error)
112

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

368
        sync.RWMutex
369

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

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

378
        // log is a link-specific logging instance.
379
        log btclog.Logger
380

381
        // isOutgoingAddBlocked tracks whether the channelLink can send an
382
        // UpdateAddHTLC.
383
        isOutgoingAddBlocked atomic.Bool
384

385
        // isIncomingAddBlocked tracks whether the channelLink can receive an
386
        // UpdateAddHTLC.
387
        isIncomingAddBlocked atomic.Bool
388

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

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

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

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

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

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

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

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

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

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

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

3✔
453
        return hookID
3✔
454
}
455

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

463
        m.transient = make(map[uint64]func())
3✔
464
}
465

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

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

3✔
478
        logPrefix := fmt.Sprintf("ChannelLink(%v):", channel.ChannelPoint())
3✔
479

3✔
480
        // If the max fee exposure isn't set, use the default.
3✔
481
        if cfg.MaxFeeExposure == 0 {
3✔
482
                cfg.MaxFeeExposure = DefaultMaxFeeExposure
×
483
        }
×
484

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

504
        quiescenceReqs := make(
3✔
505
                chan fn.Req[fn.Unit, fn.Result[lntypes.ChannelParty]], 1,
3✔
506
        )
3✔
507

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

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

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

538
        l.log.Info("starting")
3✔
539

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

551
        l.mailBox.ResetMessages()
3✔
552
        l.hodlQueue.Start()
3✔
553

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

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

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

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

596
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
3✔
597

3✔
598
        l.cg.WgAdd(1)
3✔
599
        go l.htlcManager(context.TODO())
3✔
600

3✔
601
        return nil
3✔
602
}
603

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

614
        l.log.Info("stopping")
3✔
615

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

3✔
620
        if l.cfg.ChainEvents.Cancel != nil {
6✔
621
                l.cfg.ChainEvents.Cancel()
3✔
622
        }
3✔
623

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

634
        if l.hodlQueue != nil {
6✔
635
                l.hodlQueue.Stop()
3✔
636
        }
3✔
637

638
        l.cg.Quit()
3✔
639
        l.cg.WgWait()
3✔
640

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

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

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

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

3✔
677
        return l.eligibleToForward()
3✔
678
}
3✔
679

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

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

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

712
        return l.isIncomingAddBlocked.Swap(false)
×
713
}
714

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

723
        return !l.isIncomingAddBlocked.Swap(true)
3✔
724
}
725

726
// IsFlushing returns true when UpdateAddHtlc's are disabled in the direction of
727
// the argument.
728
func (l *channelLink) IsFlushing(linkDirection LinkDirection) bool {
3✔
729
        if linkDirection == Outgoing {
6✔
730
                return l.isOutgoingAddBlocked.Load()
3✔
731
        }
3✔
732

733
        return l.isIncomingAddBlocked.Load()
3✔
734
}
735

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

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

3✔
753
        if direction == Outgoing {
6✔
754
                queue = l.outgoingCommitHooks.newTransients
3✔
755
        } else {
3✔
756
                queue = l.incomingCommitHooks.newTransients
×
757
        }
×
758

759
        select {
3✔
760
        case queue <- hook:
3✔
761
        case <-l.cg.Done():
×
762
        }
763
}
764

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

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

783
        return out
3✔
784
}
785

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

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

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

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

817
        l.log.Debugf("sampled fee rate for 3 block conf: %v sat/kw",
×
818
                int64(feePerKw))
×
819

×
820
        return feePerKw, nil
×
821
}
822

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

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

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

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

847
        // Otherwise, we won't modify our fee.
848
        default:
×
849
                return false
×
850
        }
851
}
852

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

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

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

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

882
        return cb(update)
3✔
883
}
884

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

3✔
892
        l.log.Infof("Attempting to re-synchronize channel: %v", chanState)
3✔
893

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

907
        var msgsToReSend []lnwire.Message
3✔
908

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

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

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

3✔
932
                        l.log.Infof("resending ChannelReady message to peer")
3✔
933

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

940
                        channelReadyMsg := lnwire.NewChannelReady(
3✔
941
                                l.ChanID(), nextRevocation,
3✔
942
                        )
3✔
943

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

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

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

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

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

3✔
983
                var (
3✔
984
                        openedCircuits []CircuitKey
3✔
985
                        closedCircuits []CircuitKey
3✔
986
                )
3✔
987

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

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

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

1011
                if len(msgsToReSend) > 0 {
3✔
1012
                        l.log.Infof("sending %v updates to synchronize the "+
×
1013
                                "state", len(msgsToReSend))
×
1014
                }
×
1015

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

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

1027
        return nil
3✔
1028
}
1029

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

1041
        l.log.Debugf("loaded %d fwd pks", len(fwdPkgs))
3✔
1042

3✔
1043
        for _, fwdPkg := range fwdPkgs {
6✔
1044
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
3✔
1045
                        return err
×
1046
                }
×
1047
        }
1048

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

1055
        return nil
3✔
1056
}
1057

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

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

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

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

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

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

1103
        return nil
3✔
1104
}
1105

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

3✔
1115
        l.cfg.FwdPkgGCTicker.Resume()
3✔
1116
        defer l.cfg.FwdPkgGCTicker.Stop()
3✔
1117

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

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

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

1145
        var removeHeights []uint64
3✔
1146
        for _, fwdPkg := range fwdPkgs {
6✔
1147
                if fwdPkg.State != channeldb.FwdStateCompleted {
6✔
1148
                        continue
3✔
1149
                }
1150

1151
                removeHeights = append(removeHeights, fwdPkg.Height)
3✔
1152
        }
1153

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

1160
        return l.channel.RemoveFwdPkgs(removeHeights...)
3✔
1161
}
1162

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

3✔
1168
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
3✔
1169

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

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

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

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

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

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

1227
        // Other, unspecified error.
1228
        default:
×
1229
        }
1230

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

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

1257
        l.log.Infof("HTLC manager started, bandwidth=%v", l.Bandwidth())
3✔
1258

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

3✔
1266
        // If the link is not started for the first time, we need to take extra
3✔
1267
        // steps to resume its state.
3✔
1268
        l.resumeLink(ctx)
3✔
1269

3✔
1270
        // Now that we've received both channel_ready and channel reestablish,
3✔
1271
        // we can go ahead and send the active channel notification. We'll also
3✔
1272
        // defer the inactive notification for when the link exits to ensure
3✔
1273
        // that every active notification is matched by an inactive one.
3✔
1274
        l.cfg.NotifyActiveChannel(l.ChannelPoint())
3✔
1275
        defer l.cfg.NotifyInactiveChannel(l.ChannelPoint())
3✔
1276

3✔
1277
        for {
6✔
1278
                // We must always check if we failed at some point processing
3✔
1279
                // the last update before processing the next.
3✔
1280
                if l.failed {
6✔
1281
                        l.log.Errorf("link failed, exiting htlcManager")
3✔
1282
                        return
3✔
1283
                }
3✔
1284

1285
                // Pause or resume the batch ticker.
1286
                l.toggleBatchTicker()
3✔
1287

3✔
1288
                select {
3✔
1289
                // We have a new hook that needs to be run when we reach a clean
1290
                // channel state.
1291
                case hook := <-l.flushHooks.newTransients:
3✔
1292
                        if l.channel.IsChannelClean() {
6✔
1293
                                hook()
3✔
1294
                        } else {
6✔
1295
                                l.flushHooks.alloc(hook)
3✔
1296
                        }
3✔
1297

1298
                // We have a new hook that needs to be run when we have
1299
                // committed all of our updates.
1300
                case hook := <-l.outgoingCommitHooks.newTransients:
3✔
1301
                        if !l.channel.OweCommitment() {
6✔
1302
                                hook()
3✔
1303
                        } else {
3✔
1304
                                l.outgoingCommitHooks.alloc(hook)
×
1305
                        }
×
1306

1307
                // We have a new hook that needs to be run when our peer has
1308
                // committed all of their updates.
1309
                case hook := <-l.incomingCommitHooks.newTransients:
×
1310
                        if !l.channel.NeedCommitment() {
×
1311
                                hook()
×
1312
                        } else {
×
1313
                                l.incomingCommitHooks.alloc(hook)
×
1314
                        }
×
1315

1316
                // Our update fee timer has fired, so we'll check the network
1317
                // fee to see if we should adjust our commitment fee.
1318
                case <-l.updateFeeTimer.C:
×
1319
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
×
NEW
1320
                        l.handleUpdateFee(ctx)
×
1321

1322
                // The underlying channel has notified us of a unilateral close
1323
                // carried out by the remote peer. In the case of such an
1324
                // event, we'll wipe the channel state from the peer, and mark
1325
                // the contract as fully settled. Afterwards we can exit.
1326
                //
1327
                // TODO(roasbeef): add force closure? also breach?
1328
                case <-l.cfg.ChainEvents.RemoteUnilateralClosure:
3✔
1329
                        l.log.Warnf("remote peer has closed on-chain")
3✔
1330

3✔
1331
                        // TODO(roasbeef): remove all together
3✔
1332
                        go func() {
6✔
1333
                                chanPoint := l.channel.ChannelPoint()
3✔
1334
                                l.cfg.Peer.WipeChannel(&chanPoint)
3✔
1335
                        }()
3✔
1336

1337
                        return
3✔
1338

1339
                case <-l.cfg.BatchTicker.Ticks():
3✔
1340
                        // Attempt to extend the remote commitment chain
3✔
1341
                        // including all the currently pending entries. If the
3✔
1342
                        // send was unsuccessful, then abandon the update,
3✔
1343
                        // waiting for the revocation window to open up.
3✔
1344
                        if !l.updateCommitTxOrFail(ctx) {
3✔
1345
                                return
×
1346
                        }
×
1347

1348
                case <-l.cfg.PendingCommitTicker.Ticks():
×
1349
                        l.failf(
×
1350
                                LinkFailureError{
×
1351
                                        code:          ErrRemoteUnresponsive,
×
1352
                                        FailureAction: LinkFailureDisconnect,
×
1353
                                },
×
1354
                                "unable to complete dance",
×
1355
                        )
×
1356
                        return
×
1357

1358
                // A message from the switch was just received. This indicates
1359
                // that the link is an intermediate hop in a multi-hop HTLC
1360
                // circuit.
1361
                case pkt := <-l.downstream:
3✔
1362
                        l.handleDownstreamPkt(ctx, pkt)
3✔
1363

1364
                // A message from the connected peer was just received. This
1365
                // indicates that we have a new incoming HTLC, either directly
1366
                // for us, or part of a multi-hop HTLC circuit.
1367
                case msg := <-l.upstream:
3✔
1368
                        l.handleUpstreamMsg(ctx, msg)
3✔
1369

1370
                // A htlc resolution is received. This means that we now have a
1371
                // resolution for a previously accepted htlc.
1372
                case hodlItem := <-l.hodlQueue.ChanOut():
3✔
1373
                        l.handleHtlcResolution(ctx, hodlItem)
3✔
1374

1375
                // A user-initiated quiescence request is received. We now
1376
                // forward it to the quiescer.
1377
                case qReq := <-l.quiescenceReqs:
3✔
1378
                        l.handleQuiescenceReq(qReq)
3✔
1379

1380
                case <-l.cg.Done():
3✔
1381
                        return
3✔
1382
                }
1383
        }
1384
}
1385

1386
// processHodlQueue processes a received htlc resolution and continues reading
1387
// from the hodl queue until no more resolutions remain. When this function
1388
// returns without an error, the commit tx should be updated.
1389
func (l *channelLink) processHodlQueue(ctx context.Context,
1390
        firstResolution invoices.HtlcResolution) error {
3✔
1391

3✔
1392
        // Try to read all waiting resolution messages, so that they can all be
3✔
1393
        // processed in a single commitment tx update.
3✔
1394
        htlcResolution := firstResolution
3✔
1395
loop:
3✔
1396
        for {
6✔
1397
                // Lookup all hodl htlcs that can be failed or settled with this event.
3✔
1398
                // The hodl htlc must be present in the map.
3✔
1399
                circuitKey := htlcResolution.CircuitKey()
3✔
1400
                hodlHtlc, ok := l.hodlMap[circuitKey]
3✔
1401
                if !ok {
3✔
1402
                        return fmt.Errorf("hodl htlc not found: %v", circuitKey)
×
1403
                }
×
1404

1405
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
3✔
1406
                        return err
×
1407
                }
×
1408

1409
                // Clean up hodl map.
1410
                delete(l.hodlMap, circuitKey)
3✔
1411

3✔
1412
                select {
3✔
1413
                case item := <-l.hodlQueue.ChanOut():
3✔
1414
                        htlcResolution = item.(invoices.HtlcResolution)
3✔
1415

1416
                // No need to process it if the link is broken.
1417
                case <-l.cg.Done():
×
1418
                        return ErrLinkShuttingDown
×
1419

1420
                default:
3✔
1421
                        break loop
3✔
1422
                }
1423
        }
1424

1425
        // Update the commitment tx.
1426
        if err := l.updateCommitTx(ctx); err != nil {
3✔
1427
                return err
×
1428
        }
×
1429

1430
        return nil
3✔
1431
}
1432

1433
// processHtlcResolution applies a received htlc resolution to the provided
1434
// htlc. When this function returns without an error, the commit tx should be
1435
// updated.
1436
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1437
        htlc hodlHtlc) error {
3✔
1438

3✔
1439
        circuitKey := resolution.CircuitKey()
3✔
1440

3✔
1441
        // Determine required action for the resolution based on the type of
3✔
1442
        // resolution we have received.
3✔
1443
        switch res := resolution.(type) {
3✔
1444
        // Settle htlcs that returned a settle resolution using the preimage
1445
        // in the resolution.
1446
        case *invoices.HtlcSettleResolution:
3✔
1447
                l.log.Debugf("received settle resolution for %v "+
3✔
1448
                        "with outcome: %v", circuitKey, res.Outcome)
3✔
1449

3✔
1450
                return l.settleHTLC(
3✔
1451
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
3✔
1452
                )
3✔
1453

1454
        // For htlc failures, we get the relevant failure message based
1455
        // on the failure resolution and then fail the htlc.
1456
        case *invoices.HtlcFailResolution:
3✔
1457
                l.log.Debugf("received cancel resolution for "+
3✔
1458
                        "%v with outcome: %v", circuitKey, res.Outcome)
3✔
1459

3✔
1460
                // Get the lnwire failure message based on the resolution
3✔
1461
                // result.
3✔
1462
                failure := getResolutionFailure(res, htlc.add.Amount)
3✔
1463

3✔
1464
                l.sendHTLCError(
3✔
1465
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
3✔
1466
                        true,
3✔
1467
                )
3✔
1468
                return nil
3✔
1469

1470
        // Fail if we do not get a settle of fail resolution, since we
1471
        // are only expecting to handle settles and fails.
1472
        default:
×
1473
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1474
                        resolution)
×
1475
        }
1476
}
1477

1478
// getResolutionFailure returns the wire message that a htlc resolution should
1479
// be failed with.
1480
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1481
        amount lnwire.MilliSatoshi) *LinkError {
3✔
1482

3✔
1483
        // If the resolution has been resolved as part of a MPP timeout,
3✔
1484
        // we need to fail the htlc with lnwire.FailMppTimeout.
3✔
1485
        if resolution.Outcome == invoices.ResultMppTimeout {
3✔
1486
                return NewDetailedLinkError(
×
1487
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1488
                )
×
1489
        }
×
1490

1491
        // If the htlc is not a MPP timeout, we fail it with
1492
        // FailIncorrectDetails. This error is sent for invoice payment
1493
        // failures such as underpayment/ expiry too soon and hodl invoices
1494
        // (which return FailIncorrectDetails to avoid leaking information).
1495
        incorrectDetails := lnwire.NewFailIncorrectDetails(
3✔
1496
                amount, uint32(resolution.AcceptHeight),
3✔
1497
        )
3✔
1498

3✔
1499
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
3✔
1500
}
1501

1502
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
1503
// within the link's configuration that will be used to determine when the link
1504
// should propose an update to its commitment fee rate.
1505
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
3✔
1506
        lower := int64(l.cfg.MinUpdateTimeout)
3✔
1507
        upper := int64(l.cfg.MaxUpdateTimeout)
3✔
1508
        return time.Duration(prand.Int63n(upper-lower) + lower)
3✔
1509
}
3✔
1510

1511
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1512
// downstream HTLC Switch.
1513
func (l *channelLink) handleDownstreamUpdateAdd(ctx context.Context,
1514
        pkt *htlcPacket) error {
3✔
1515

3✔
1516
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
3✔
1517
        if !ok {
3✔
1518
                return errors.New("not an UpdateAddHTLC packet")
×
1519
        }
×
1520

1521
        // If we are flushing the link in the outgoing direction or we have
1522
        // already sent Stfu, then we can't add new htlcs to the link and we
1523
        // need to bounce it.
1524
        if l.IsFlushing(Outgoing) || !l.quiescer.CanSendUpdates() {
3✔
1525
                l.mailBox.FailAdd(pkt)
×
1526

×
1527
                return NewDetailedLinkError(
×
1528
                        &lnwire.FailTemporaryChannelFailure{},
×
1529
                        OutgoingFailureLinkNotEligible,
×
1530
                )
×
1531
        }
×
1532

1533
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1534
        // arbitrary delays between the switch adding an ADD to the
1535
        // mailbox, and the HTLC being added to the commitment state.
1536
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
3✔
1537
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1538
                l.mailBox.AckPacket(pkt.inKey())
×
1539
                return nil
×
1540
        }
×
1541

1542
        // Check if we can add the HTLC here without exceededing the max fee
1543
        // exposure threshold.
1544
        if l.isOverexposedWithHtlc(htlc, false) {
3✔
1545
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
×
1546
                        "exposure exceeded")
×
1547

×
1548
                l.mailBox.FailAdd(pkt)
×
1549

×
1550
                return NewDetailedLinkError(
×
1551
                        lnwire.NewTemporaryChannelFailure(nil),
×
1552
                        OutgoingFailureDownstreamHtlcAdd,
×
1553
                )
×
1554
        }
×
1555

1556
        // A new payment has been initiated via the downstream channel,
1557
        // so we add the new HTLC to our local log, then update the
1558
        // commitment chains.
1559
        htlc.ChanID = l.ChanID()
3✔
1560
        openCircuitRef := pkt.inKey()
3✔
1561

3✔
1562
        // We enforce the fee buffer for the commitment transaction because
3✔
1563
        // we are in control of adding this htlc. Nothing has locked-in yet so
3✔
1564
        // we can securely enforce the fee buffer which is only relevant if we
3✔
1565
        // are the initiator of the channel.
3✔
1566
        index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
3✔
1567
        if err != nil {
6✔
1568
                // The HTLC was unable to be added to the state machine,
3✔
1569
                // as a result, we'll signal the switch to cancel the
3✔
1570
                // pending payment.
3✔
1571
                l.log.Warnf("Unable to handle downstream add HTLC: %v",
3✔
1572
                        err)
3✔
1573

3✔
1574
                // Remove this packet from the link's mailbox, this
3✔
1575
                // prevents it from being reprocessed if the link
3✔
1576
                // restarts and resets it mailbox. If this response
3✔
1577
                // doesn't make it back to the originating link, it will
3✔
1578
                // be rejected upon attempting to reforward the Add to
3✔
1579
                // the switch, since the circuit was never fully opened,
3✔
1580
                // and the forwarding package shows it as
3✔
1581
                // unacknowledged.
3✔
1582
                l.mailBox.FailAdd(pkt)
3✔
1583

3✔
1584
                return NewDetailedLinkError(
3✔
1585
                        lnwire.NewTemporaryChannelFailure(nil),
3✔
1586
                        OutgoingFailureDownstreamHtlcAdd,
3✔
1587
                )
3✔
1588
        }
3✔
1589

1590
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
3✔
1591
                "local_log_index=%v, pend_updates=%v",
3✔
1592
                htlc.PaymentHash[:], index,
3✔
1593
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
3✔
1594

3✔
1595
        pkt.outgoingChanID = l.ShortChanID()
3✔
1596
        pkt.outgoingHTLCID = index
3✔
1597
        htlc.ID = index
3✔
1598

3✔
1599
        l.log.Debugf("queueing keystone of ADD open circuit: %s->%s",
3✔
1600
                pkt.inKey(), pkt.outKey())
3✔
1601

3✔
1602
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
3✔
1603
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
3✔
1604

3✔
1605
        _ = l.cfg.Peer.SendMessage(false, htlc)
3✔
1606

3✔
1607
        // Send a forward event notification to htlcNotifier.
3✔
1608
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
3✔
1609
                newHtlcKey(pkt),
3✔
1610
                HtlcInfo{
3✔
1611
                        IncomingTimeLock: pkt.incomingTimeout,
3✔
1612
                        IncomingAmt:      pkt.incomingAmount,
3✔
1613
                        OutgoingTimeLock: htlc.Expiry,
3✔
1614
                        OutgoingAmt:      htlc.Amount,
3✔
1615
                },
3✔
1616
                getEventType(pkt),
3✔
1617
        )
3✔
1618

3✔
1619
        l.tryBatchUpdateCommitTx(ctx)
3✔
1620

3✔
1621
        return nil
3✔
1622
}
1623

1624
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1625
// Switch. Possible messages sent by the switch include requests to forward new
1626
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1627
// cleared HTLCs with the upstream peer.
1628
//
1629
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1630
func (l *channelLink) handleDownstreamPkt(ctx context.Context,
1631
        pkt *htlcPacket) {
3✔
1632

3✔
1633
        if pkt.htlc.MsgType().IsChannelUpdate() &&
3✔
1634
                !l.quiescer.CanSendUpdates() {
3✔
1635

×
1636
                l.log.Warnf("unable to process channel update. "+
×
1637
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1638

×
1639
                return
×
1640
        }
×
1641

1642
        switch htlc := pkt.htlc.(type) {
3✔
1643
        case *lnwire.UpdateAddHTLC:
3✔
1644
                // Handle add message. The returned error can be ignored,
3✔
1645
                // because it is also sent through the mailbox.
3✔
1646
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
3✔
1647

1648
        case *lnwire.UpdateFulfillHTLC:
3✔
1649
                l.processLocalUpdateFulfillHTLC(ctx, pkt, htlc)
3✔
1650

1651
        case *lnwire.UpdateFailHTLC:
3✔
1652
                l.processLocalUpdateFailHTLC(ctx, pkt, htlc)
3✔
1653
        }
1654
}
1655

1656
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1657
// full.
1658
func (l *channelLink) tryBatchUpdateCommitTx(ctx context.Context) {
3✔
1659
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
3✔
1660
        if pending < uint64(l.cfg.BatchSize) {
6✔
1661
                return
3✔
1662
        }
3✔
1663

1664
        l.updateCommitTxOrFail(ctx)
3✔
1665
}
1666

1667
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1668
// associated with this packet. If successful in doing so, it will also purge
1669
// the open circuit from the circuit map and remove the packet from the link's
1670
// mailbox.
1671
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
×
1672
        inKey := pkt.inKey()
×
1673

×
1674
        l.log.Debugf("cleaning up spurious response for incoming "+
×
1675
                "circuit-key=%v", inKey)
×
1676

×
1677
        // If the htlc packet doesn't have a source reference, it is unsafe to
×
1678
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
×
1679
        if pkt.sourceRef == nil {
×
1680
                l.log.Errorf("unable to cleanup response for incoming "+
×
1681
                        "circuit-key=%v, does not contain source reference",
×
1682
                        inKey)
×
1683
                return
×
1684
        }
×
1685

1686
        // If the source reference is present,  we will try to prevent this link
1687
        // from resending the packet to the switch. To do so, we ack the AddRef
1688
        // of the incoming HTLC belonging to this link.
1689
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
×
1690
        if err != nil {
×
1691
                l.log.Errorf("unable to ack AddRef for incoming "+
×
1692
                        "circuit-key=%v: %v", inKey, err)
×
1693

×
1694
                // If this operation failed, it is unsafe to attempt removal of
×
1695
                // the destination reference or circuit, so we exit early. The
×
1696
                // cleanup may proceed with a different packet in the future
×
1697
                // that succeeds on this step.
×
1698
                return
×
1699
        }
×
1700

1701
        // Now that we know this link will stop retransmitting Adds to the
1702
        // switch, we can begin to teardown the response reference and circuit
1703
        // map.
1704
        //
1705
        // If the packet includes a destination reference, then a response for
1706
        // this HTLC was locked into the outgoing channel. Attempt to remove
1707
        // this reference, so we stop retransmitting the response internally.
1708
        // Even if this fails, we will proceed in trying to delete the circuit.
1709
        // When retransmitting responses, the destination references will be
1710
        // cleaned up if an open circuit is not found in the circuit map.
1711
        if pkt.destRef != nil {
×
1712
                err := l.channel.AckSettleFails(*pkt.destRef)
×
1713
                if err != nil {
×
1714
                        l.log.Errorf("unable to ack SettleFailRef "+
×
1715
                                "for incoming circuit-key=%v: %v",
×
1716
                                inKey, err)
×
1717
                }
×
1718
        }
1719

1720
        l.log.Debugf("deleting circuit for incoming circuit-key=%x", inKey)
×
1721

×
1722
        // With all known references acked, we can now safely delete the circuit
×
1723
        // from the switch's circuit map, as the state is no longer needed.
×
1724
        err = l.cfg.Circuits.DeleteCircuits(inKey)
×
1725
        if err != nil {
×
1726
                l.log.Errorf("unable to delete circuit for "+
×
1727
                        "circuit-key=%v: %v", inKey, err)
×
1728
        }
×
1729
}
1730

1731
// handleUpstreamMsg processes wire messages related to commitment state
1732
// updates from the upstream peer. The upstream peer is the peer whom we have a
1733
// direct channel with, updating our respective commitment chains.
1734
func (l *channelLink) handleUpstreamMsg(ctx context.Context,
1735
        msg lnwire.Message) {
3✔
1736

3✔
1737
        l.log.Tracef("receive upstream msg %v, handling now... ", msg.MsgType())
3✔
1738
        defer l.log.Tracef("handled upstream msg %v", msg.MsgType())
3✔
1739

3✔
1740
        // First check if the message is an update and we are capable of
3✔
1741
        // receiving updates right now.
3✔
1742
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
3✔
1743
                l.stfuFailf("update received after stfu: %T", msg)
×
1744
                return
×
1745
        }
×
1746

1747
        switch msg := msg.(type) {
3✔
1748
        case *lnwire.UpdateAddHTLC:
3✔
1749
                l.processRemoteUpdateAddHTLC(msg)
3✔
1750

1751
        case *lnwire.UpdateFulfillHTLC:
3✔
1752
                l.processRemoteUpdateFulfillHTLC(msg)
3✔
1753

1754
        case *lnwire.UpdateFailMalformedHTLC:
3✔
1755
                l.processRemoteUpdateFailMalformedHTLC(msg)
3✔
1756

1757
        case *lnwire.UpdateFailHTLC:
3✔
1758
                l.processRemoteUpdateFailHTLC(msg)
3✔
1759

1760
        case *lnwire.CommitSig:
3✔
1761
                l.processRemoteCommitSig(ctx, msg)
3✔
1762

1763
        case *lnwire.RevokeAndAck:
3✔
1764
                l.processRemoteRevokeAndAck(ctx, msg)
3✔
1765

NEW
1766
        case *lnwire.UpdateFee:
×
NEW
1767
                l.processRemoteUpdateFee(msg)
×
1768

1769
        case *lnwire.Stfu:
3✔
1770
                err := l.handleStfu(msg)
3✔
1771
                if err != nil {
3✔
NEW
1772
                        l.stfuFailf("handleStfu: %v", err.Error())
×
UNCOV
1773
                }
×
1774

1775
        // In the case where we receive a warning message from our peer, just
1776
        // log it and move on. We choose not to disconnect from our peer,
1777
        // although we "MAY" do so according to the specification.
NEW
1778
        case *lnwire.Warning:
×
NEW
1779
                l.log.Warnf("received warning message from peer: %v",
×
NEW
1780
                        msg.Warning())
×
1781

1782
        case *lnwire.Error:
2✔
1783
                l.processRemoteError(msg)
2✔
1784

NEW
1785
        default:
×
NEW
1786
                l.log.Warnf("received unknown message of type %T", msg)
×
1787
        }
1788
}
1789

1790
// handleStfu implements the top-level logic for handling the Stfu message from
1791
// our peer.
1792
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
3✔
1793
        if !l.noDanglingUpdates(lntypes.Remote) {
3✔
NEW
1794
                return ErrPendingRemoteUpdates
×
NEW
1795
        }
×
1796
        err := l.quiescer.RecvStfu(*stfu)
3✔
1797
        if err != nil {
3✔
NEW
1798
                return err
×
NEW
1799
        }
×
1800

1801
        // If we can immediately send an Stfu response back, we will.
1802
        if l.noDanglingUpdates(lntypes.Local) {
6✔
1803
                return l.quiescer.SendOwedStfu()
3✔
1804
        }
3✔
1805

NEW
1806
        return nil
×
1807
}
1808

1809
// stfuFailf fails the link in the case where the requirements of the quiescence
1810
// protocol are violated. In all cases we opt to drop the connection as only
1811
// link state (as opposed to channel state) is affected.
NEW
1812
func (l *channelLink) stfuFailf(format string, args ...interface{}) {
×
NEW
1813
        l.failf(LinkFailureError{
×
NEW
1814
                code:             ErrStfuViolation,
×
NEW
1815
                FailureAction:    LinkFailureDisconnect,
×
NEW
1816
                PermanentFailure: false,
×
NEW
1817
                Warning:          true,
×
NEW
1818
        }, format, args...)
×
NEW
1819
}
×
1820

1821
// noDanglingUpdates returns true when there are 0 updates that were originally
1822
// issued by whose on either the Local or Remote commitment transaction.
1823
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
3✔
1824
        pendingOnLocal := l.channel.NumPendingUpdates(
3✔
1825
                whose, lntypes.Local,
3✔
1826
        )
3✔
1827
        pendingOnRemote := l.channel.NumPendingUpdates(
3✔
1828
                whose, lntypes.Remote,
3✔
1829
        )
3✔
1830

3✔
1831
        return pendingOnLocal == 0 && pendingOnRemote == 0
3✔
1832
}
3✔
1833

1834
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
1835
// for packets delivered from server, and cleaning up any circuits closed by
1836
// signing a previous commitment txn. This method ensures that the circuits are
1837
// removed from the circuit map before removing them from the link's mailbox,
1838
// otherwise it could be possible for some circuit to be missed if this link
1839
// flaps.
1840
func (l *channelLink) ackDownStreamPackets() error {
3✔
1841
        // First, remove the downstream Add packets that were included in the
3✔
1842
        // previous commitment signature. This will prevent the Adds from being
3✔
1843
        // replayed if this link disconnects.
3✔
1844
        for _, inKey := range l.openedCircuits {
6✔
1845
                // In order to test the sphinx replay logic of the remote
3✔
1846
                // party, unsafe replay does not acknowledge the packets from
3✔
1847
                // the mailbox. We can then force a replay of any Add packets
3✔
1848
                // held in memory by disconnecting and reconnecting the link.
3✔
1849
                if l.cfg.UnsafeReplay {
6✔
1850
                        continue
3✔
1851
                }
1852

1853
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
3✔
1854
                l.mailBox.AckPacket(inKey)
3✔
1855
        }
1856

1857
        // Now, we will delete all circuits closed by the previous commitment
1858
        // signature, which is the result of downstream Settle/Fail packets. We
1859
        // batch them here to ensure circuits are closed atomically and for
1860
        // performance.
1861
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
3✔
1862
        switch err {
3✔
1863
        case nil:
3✔
1864
                // Successful deletion.
1865

1866
        default:
×
1867
                l.log.Errorf("unable to delete %d circuits: %v",
×
1868
                        len(l.closedCircuits), err)
×
1869
                return err
×
1870
        }
1871

1872
        // With the circuits removed from memory and disk, we now ack any
1873
        // Settle/Fails in the mailbox to ensure they do not get redelivered
1874
        // after startup. If forgive is enabled and we've reached this point,
1875
        // the circuits must have been removed at some point, so it is now safe
1876
        // to un-queue the corresponding Settle/Fails.
1877
        for _, inKey := range l.closedCircuits {
6✔
1878
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
3✔
1879
                        inKey)
3✔
1880
                l.mailBox.AckPacket(inKey)
3✔
1881
        }
3✔
1882

1883
        // Lastly, reset our buffers to be empty while keeping any acquired
1884
        // growth in the backing array.
1885
        l.openedCircuits = l.openedCircuits[:0]
3✔
1886
        l.closedCircuits = l.closedCircuits[:0]
3✔
1887

3✔
1888
        return nil
3✔
1889
}
1890

1891
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
1892
// the link.
1893
func (l *channelLink) updateCommitTxOrFail(ctx context.Context) bool {
3✔
1894
        err := l.updateCommitTx(ctx)
3✔
1895
        switch {
3✔
1896
        // No error encountered, success.
1897
        case err == nil:
3✔
1898

1899
        // A duplicate keystone error should be resolved and is not fatal, so
1900
        // we won't send an Error message to the peer.
NEW
1901
        case errors.Is(err, ErrDuplicateKeystone):
×
1902
                l.failf(LinkFailureError{code: ErrCircuitError},
×
1903
                        "temporary circuit error: %v", err)
×
1904
                return false
×
1905

1906
        // Any other error is treated results in an Error message being sent to
1907
        // the peer.
1908
        default:
×
1909
                l.failf(LinkFailureError{code: ErrInternalError},
×
1910
                        "unable to update commitment: %v", err)
×
1911
                return false
×
1912
        }
1913

1914
        return true
3✔
1915
}
1916

1917
// updateCommitTx signs, then sends an update to the remote peer adding a new
1918
// commitment to their commitment chain which includes all the latest updates
1919
// we've received+processed up to this point.
1920
func (l *channelLink) updateCommitTx(ctx context.Context) error {
3✔
1921
        // Preemptively write all pending keystones to disk, just in case the
3✔
1922
        // HTLCs we have in memory are included in the subsequent attempt to
3✔
1923
        // sign a commitment state.
3✔
1924
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
3✔
1925
        if err != nil {
3✔
1926
                // If ErrDuplicateKeystone is returned, the caller will catch
×
1927
                // it.
×
1928
                return err
×
1929
        }
×
1930

1931
        // Reset the batch, but keep the backing buffer to avoid reallocating.
1932
        l.keystoneBatch = l.keystoneBatch[:0]
3✔
1933

3✔
1934
        // If hodl.Commit mode is active, we will refrain from attempting to
3✔
1935
        // commit any in-memory modifications to the channel state. Exiting here
3✔
1936
        // permits testing of either the switch or link's ability to trim
3✔
1937
        // circuits that have been opened, but unsuccessfully committed.
3✔
1938
        if l.cfg.HodlMask.Active(hodl.Commit) {
6✔
1939
                l.log.Warnf(hodl.Commit.Warning())
3✔
1940
                return nil
3✔
1941
        }
3✔
1942

1943
        ctx, done := l.cg.Create(ctx)
3✔
1944
        defer done()
3✔
1945

3✔
1946
        newCommit, err := l.channel.SignNextCommitment(ctx)
3✔
1947
        if err == lnwallet.ErrNoWindow {
6✔
1948
                l.cfg.PendingCommitTicker.Resume()
3✔
1949
                l.log.Trace("PendingCommitTicker resumed")
3✔
1950

3✔
1951
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
3✔
1952
                l.log.Tracef("revocation window exhausted, unable to send: "+
3✔
1953
                        "%v, pend_updates=%v, dangling_closes%v", n,
3✔
1954
                        lnutils.SpewLogClosure(l.openedCircuits),
3✔
1955
                        lnutils.SpewLogClosure(l.closedCircuits))
3✔
1956

3✔
1957
                return nil
3✔
1958
        } else if err != nil {
6✔
1959
                return err
×
1960
        }
×
1961

1962
        if err := l.ackDownStreamPackets(); err != nil {
3✔
1963
                return err
×
1964
        }
×
1965

1966
        l.cfg.PendingCommitTicker.Pause()
3✔
1967
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
3✔
1968

3✔
1969
        // The remote party now has a new pending commitment, so we'll update
3✔
1970
        // the contract court to be aware of this new set (the prior old remote
3✔
1971
        // pending).
3✔
1972
        newUpdate := &contractcourt.ContractUpdate{
3✔
1973
                HtlcKey: contractcourt.RemotePendingHtlcSet,
3✔
1974
                Htlcs:   newCommit.PendingHTLCs,
3✔
1975
        }
3✔
1976
        err = l.cfg.NotifyContractUpdate(newUpdate)
3✔
1977
        if err != nil {
3✔
1978
                l.log.Errorf("unable to notify contract update: %v", err)
×
1979
                return err
×
1980
        }
×
1981

1982
        select {
3✔
1983
        case <-l.cg.Done():
×
1984
                return ErrLinkShuttingDown
×
1985
        default:
3✔
1986
        }
1987

1988
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
3✔
1989
        if err != nil {
3✔
1990
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
1991
        }
×
1992

1993
        commitSig := &lnwire.CommitSig{
3✔
1994
                ChanID:        l.ChanID(),
3✔
1995
                CommitSig:     newCommit.CommitSig,
3✔
1996
                HtlcSigs:      newCommit.HtlcSigs,
3✔
1997
                PartialSig:    newCommit.PartialSig,
3✔
1998
                CustomRecords: auxBlobRecords,
3✔
1999
        }
3✔
2000
        l.cfg.Peer.SendMessage(false, commitSig)
3✔
2001

3✔
2002
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
3✔
2003
        // of commit hooks.
3✔
2004
        l.RWMutex.Lock()
3✔
2005
        l.outgoingCommitHooks.invoke()
3✔
2006
        l.RWMutex.Unlock()
3✔
2007

3✔
2008
        return nil
3✔
2009
}
2010

2011
// Peer returns the representation of remote peer with which we have the
2012
// channel link opened.
2013
//
2014
// NOTE: Part of the ChannelLink interface.
2015
func (l *channelLink) PeerPubKey() [33]byte {
3✔
2016
        return l.cfg.Peer.PubKey()
3✔
2017
}
3✔
2018

2019
// ChannelPoint returns the channel outpoint for the channel link.
2020
// NOTE: Part of the ChannelLink interface.
2021
func (l *channelLink) ChannelPoint() wire.OutPoint {
3✔
2022
        return l.channel.ChannelPoint()
3✔
2023
}
3✔
2024

2025
// ShortChanID returns the short channel ID for the channel link. The short
2026
// channel ID encodes the exact location in the main chain that the original
2027
// funding output can be found.
2028
//
2029
// NOTE: Part of the ChannelLink interface.
2030
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
3✔
2031
        l.RLock()
3✔
2032
        defer l.RUnlock()
3✔
2033

3✔
2034
        return l.channel.ShortChanID()
3✔
2035
}
3✔
2036

2037
// UpdateShortChanID updates the short channel ID for a link. This may be
2038
// required in the event that a link is created before the short chan ID for it
2039
// is known, or a re-org occurs, and the funding transaction changes location
2040
// within the chain.
2041
//
2042
// NOTE: Part of the ChannelLink interface.
2043
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
3✔
2044
        chanID := l.ChanID()
3✔
2045

3✔
2046
        // Refresh the channel state's short channel ID by loading it from disk.
3✔
2047
        // This ensures that the channel state accurately reflects the updated
3✔
2048
        // short channel ID.
3✔
2049
        err := l.channel.State().Refresh()
3✔
2050
        if err != nil {
3✔
2051
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2052
                        "%v", chanID, err)
×
2053
                return hop.Source, err
×
2054
        }
×
2055

2056
        return hop.Source, nil
3✔
2057
}
2058

2059
// ChanID returns the channel ID for the channel link. The channel ID is a more
2060
// compact representation of a channel's full outpoint.
2061
//
2062
// NOTE: Part of the ChannelLink interface.
2063
func (l *channelLink) ChanID() lnwire.ChannelID {
3✔
2064
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3✔
2065
}
3✔
2066

2067
// Bandwidth returns the total amount that can flow through the channel link at
2068
// this given instance. The value returned is expressed in millisatoshi and can
2069
// be used by callers when making forwarding decisions to determine if a link
2070
// can accept an HTLC.
2071
//
2072
// NOTE: Part of the ChannelLink interface.
2073
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
3✔
2074
        // Get the balance available on the channel for new HTLCs. This takes
3✔
2075
        // the channel reserve into account so HTLCs up to this value won't
3✔
2076
        // violate it.
3✔
2077
        return l.channel.AvailableBalance()
3✔
2078
}
3✔
2079

2080
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2081
// amount provided to the link. This check does not reserve a space, since
2082
// forwards or other payments may use the available slot, so it should be
2083
// considered best-effort.
2084
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
3✔
2085
        return l.channel.MayAddOutgoingHtlc(amt)
3✔
2086
}
3✔
2087

2088
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2089
// method.
2090
//
2091
// NOTE: Part of the dustHandler interface.
2092
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2093
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
3✔
2094

3✔
2095
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
3✔
2096
}
3✔
2097

2098
// getFeeRate is a wrapper method that retrieves the underlying channel's
2099
// feerate.
2100
//
2101
// NOTE: Part of the dustHandler interface.
2102
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
3✔
2103
        return l.channel.CommitFeeRate()
3✔
2104
}
3✔
2105

2106
// getDustClosure returns a closure that can be used by the switch or mailbox
2107
// to evaluate whether a given HTLC is dust.
2108
//
2109
// NOTE: Part of the dustHandler interface.
2110
func (l *channelLink) getDustClosure() dustClosure {
3✔
2111
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
3✔
2112
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
3✔
2113
        chanType := l.channel.State().ChanType
3✔
2114

3✔
2115
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
3✔
2116
}
3✔
2117

2118
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2119
// is used so that the Switch can have access to the commitment fee without
2120
// needing to have a *LightningChannel. This doesn't include dust.
2121
//
2122
// NOTE: Part of the dustHandler interface.
2123
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
3✔
2124
        if remote {
6✔
2125
                return l.channel.State().RemoteCommitment.CommitFee
3✔
2126
        }
3✔
2127

2128
        return l.channel.State().LocalCommitment.CommitFee
3✔
2129
}
2130

2131
// exceedsFeeExposureLimit returns whether or not the new proposed fee-rate
2132
// increases the total dust and fees within the channel past the configured
2133
// fee threshold. It first calculates the dust sum over every update in the
2134
// update log with the proposed fee-rate and taking into account both the local
2135
// and remote dust limits. It uses every update in the update log instead of
2136
// what is actually on the local and remote commitments because it is assumed
2137
// that in a worst-case scenario, every update in the update log could
2138
// theoretically be on either commitment transaction and this needs to be
2139
// accounted for with this fee-rate. It then calculates the local and remote
2140
// commitment fees given the proposed fee-rate. Finally, it tallies the results
2141
// and determines if the fee threshold has been exceeded.
2142
func (l *channelLink) exceedsFeeExposureLimit(
2143
        feePerKw chainfee.SatPerKWeight) (bool, error) {
×
2144

×
2145
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
×
2146

×
2147
        // Get the sum of dust for both the local and remote commitments using
×
2148
        // this "dry-run" fee.
×
2149
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
×
2150
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
×
2151

×
2152
        // Calculate the local and remote commitment fees using this dry-run
×
2153
        // fee.
×
2154
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
×
2155
        if err != nil {
×
2156
                return false, err
×
2157
        }
×
2158

2159
        // Finally, check whether the max fee exposure was exceeded on either
2160
        // future commitment transaction with the fee-rate.
2161
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
×
2162
        if totalLocalDust > l.cfg.MaxFeeExposure {
×
2163
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2164
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
2165
                        totalLocalDust, localFee)
×
2166

×
2167
                return true, nil
×
2168
        }
×
2169

2170
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
×
2171
                remoteFee,
×
2172
        )
×
2173

×
2174
        if totalRemoteDust > l.cfg.MaxFeeExposure {
×
2175
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2176
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
2177
                        totalRemoteDust, remoteFee)
×
2178

×
2179
                return true, nil
×
2180
        }
×
2181

2182
        return false, nil
×
2183
}
2184

2185
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
2186
// channel exceed the fee threshold. It first fetches the largest fee-rate that
2187
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
2188
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
2189
// the overall dust sum. If it is not dust, it contributes to weight, which
2190
// also adds to the overall dust sum by an increase in fees. If the dust sum on
2191
// either commitment exceeds the configured fee threshold, this function
2192
// returns true.
2193
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
2194
        incoming bool) bool {
3✔
2195

3✔
2196
        dustClosure := l.getDustClosure()
3✔
2197

3✔
2198
        feeRate := l.channel.WorstCaseFeeRate()
3✔
2199

3✔
2200
        amount := htlc.Amount.ToSatoshis()
3✔
2201

3✔
2202
        // See if this HTLC is dust on both the local and remote commitments.
3✔
2203
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
3✔
2204
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
3✔
2205

3✔
2206
        // Calculate the dust sum for the local and remote commitments.
3✔
2207
        localDustSum := l.getDustSum(
3✔
2208
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
3✔
2209
        )
3✔
2210
        remoteDustSum := l.getDustSum(
3✔
2211
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
3✔
2212
        )
3✔
2213

3✔
2214
        // Grab the larger of the local and remote commitment fees w/o dust.
3✔
2215
        commitFee := l.getCommitFee(false)
3✔
2216

3✔
2217
        if l.getCommitFee(true) > commitFee {
4✔
2218
                commitFee = l.getCommitFee(true)
1✔
2219
        }
1✔
2220

2221
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
3✔
2222

3✔
2223
        localDustSum += commitFeeMSat
3✔
2224
        remoteDustSum += commitFeeMSat
3✔
2225

3✔
2226
        // Calculate the additional fee increase if this is a non-dust HTLC.
3✔
2227
        weight := lntypes.WeightUnit(input.HTLCWeight)
3✔
2228
        additional := lnwire.NewMSatFromSatoshis(
3✔
2229
                feeRate.FeeForWeight(weight),
3✔
2230
        )
3✔
2231

3✔
2232
        if isLocalDust {
6✔
2233
                // If this is dust, it doesn't contribute to weight but does
3✔
2234
                // contribute to the overall dust sum.
3✔
2235
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
3✔
2236
        } else {
6✔
2237
                // Account for the fee increase that comes with an increase in
3✔
2238
                // weight.
3✔
2239
                localDustSum += additional
3✔
2240
        }
3✔
2241

2242
        if localDustSum > l.cfg.MaxFeeExposure {
3✔
2243
                // The max fee exposure was exceeded.
×
2244
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
2245
                        "overexposed, total local dust: %v (current commit "+
×
2246
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
×
2247

×
2248
                return true
×
2249
        }
×
2250

2251
        if isRemoteDust {
6✔
2252
                // If this is dust, it doesn't contribute to weight but does
3✔
2253
                // contribute to the overall dust sum.
3✔
2254
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
3✔
2255
        } else {
6✔
2256
                // Account for the fee increase that comes with an increase in
3✔
2257
                // weight.
3✔
2258
                remoteDustSum += additional
3✔
2259
        }
3✔
2260

2261
        if remoteDustSum > l.cfg.MaxFeeExposure {
3✔
2262
                // The max fee exposure was exceeded.
×
2263
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
2264
                        "overexposed, total remote dust: %v (current commit "+
×
2265
                        "fee: %v)", l.ShortChanID(), htlc, remoteDustSum)
×
2266

×
2267
                return true
×
2268
        }
×
2269

2270
        return false
3✔
2271
}
2272

2273
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
2274
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
2275
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
2276
// whether to evaluate on the local or remote commit, and finally an HTLC
2277
// amount to test.
2278
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
2279
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
2280

2281
// dustHelper is used to construct the dustClosure.
2282
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
2283
        remoteDustLimit btcutil.Amount) dustClosure {
3✔
2284

3✔
2285
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
3✔
2286
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
6✔
2287

3✔
2288
                var dustLimit btcutil.Amount
3✔
2289
                if whoseCommit.IsLocal() {
6✔
2290
                        dustLimit = localDustLimit
3✔
2291
                } else {
6✔
2292
                        dustLimit = remoteDustLimit
3✔
2293
                }
3✔
2294

2295
                return lnwallet.HtlcIsDust(
3✔
2296
                        chantype, incoming, whoseCommit, feerate, amt,
3✔
2297
                        dustLimit,
3✔
2298
                )
3✔
2299
        }
2300

2301
        return isDust
3✔
2302
}
2303

2304
// zeroConfConfirmed returns whether or not the zero-conf channel has
2305
// confirmed on-chain.
2306
//
2307
// Part of the scidAliasHandler interface.
2308
func (l *channelLink) zeroConfConfirmed() bool {
3✔
2309
        return l.channel.State().ZeroConfConfirmed()
3✔
2310
}
3✔
2311

2312
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
2313
// should not be called for non-zero-conf channels.
2314
//
2315
// Part of the scidAliasHandler interface.
2316
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
3✔
2317
        return l.channel.State().ZeroConfRealScid()
3✔
2318
}
3✔
2319

2320
// isZeroConf returns whether or not the underlying channel is a zero-conf
2321
// channel.
2322
//
2323
// Part of the scidAliasHandler interface.
2324
func (l *channelLink) isZeroConf() bool {
3✔
2325
        return l.channel.State().IsZeroConf()
3✔
2326
}
3✔
2327

2328
// negotiatedAliasFeature returns whether or not the underlying channel has
2329
// negotiated the option-scid-alias feature bit. This will be true for both
2330
// option-scid-alias and zero-conf channel-types. It will also be true for
2331
// channels with the feature bit but without the above channel-types.
2332
//
2333
// Part of the scidAliasFeature interface.
2334
func (l *channelLink) negotiatedAliasFeature() bool {
3✔
2335
        return l.channel.State().NegotiatedAliasFeature()
3✔
2336
}
3✔
2337

2338
// getAliases returns the set of aliases for the underlying channel.
2339
//
2340
// Part of the scidAliasHandler interface.
2341
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
3✔
2342
        return l.cfg.GetAliases(l.ShortChanID())
3✔
2343
}
3✔
2344

2345
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
2346
//
2347
// Part of the scidAliasHandler interface.
2348
func (l *channelLink) attachFailAliasUpdate(closure func(
2349
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
3✔
2350

3✔
2351
        l.Lock()
3✔
2352
        l.cfg.FailAliasUpdate = closure
3✔
2353
        l.Unlock()
3✔
2354
}
3✔
2355

2356
// AttachMailBox updates the current mailbox used by this link, and hooks up
2357
// the mailbox's message and packet outboxes to the link's upstream and
2358
// downstream chans, respectively.
2359
func (l *channelLink) AttachMailBox(mailbox MailBox) {
3✔
2360
        l.Lock()
3✔
2361
        l.mailBox = mailbox
3✔
2362
        l.upstream = mailbox.MessageOutBox()
3✔
2363
        l.downstream = mailbox.PacketOutBox()
3✔
2364
        l.Unlock()
3✔
2365

3✔
2366
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
3✔
2367
        // never committed.
3✔
2368
        l.mailBox.SetFeeRate(l.getFeeRate())
3✔
2369

3✔
2370
        // Also set the mailbox's dust closure so that it can query whether HTLC's
3✔
2371
        // are dust given the current feerate.
3✔
2372
        l.mailBox.SetDustClosure(l.getDustClosure())
3✔
2373
}
3✔
2374

2375
// UpdateForwardingPolicy updates the forwarding policy for the target
2376
// ChannelLink. Once updated, the link will use the new forwarding policy to
2377
// govern if it an incoming HTLC should be forwarded or not. We assume that
2378
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
2379
// update all of the link's FwrdingPolicy's values.
2380
//
2381
// NOTE: Part of the ChannelLink interface.
2382
func (l *channelLink) UpdateForwardingPolicy(
2383
        newPolicy models.ForwardingPolicy) {
3✔
2384

3✔
2385
        l.Lock()
3✔
2386
        defer l.Unlock()
3✔
2387

3✔
2388
        l.cfg.FwrdingPolicy = newPolicy
3✔
2389
}
3✔
2390

2391
// CheckHtlcForward should return a nil error if the passed HTLC details
2392
// satisfy the current forwarding policy fo the target link. Otherwise,
2393
// a LinkError with a valid protocol failure message should be returned
2394
// in order to signal to the source of the HTLC, the policy consistency
2395
// issue.
2396
//
2397
// NOTE: Part of the ChannelLink interface.
2398
func (l *channelLink) CheckHtlcForward(payHash [32]byte, incomingHtlcAmt,
2399
        amtToForward lnwire.MilliSatoshi, incomingTimeout,
2400
        outgoingTimeout uint32, inboundFee models.InboundFee,
2401
        heightNow uint32, originalScid lnwire.ShortChannelID,
2402
        customRecords lnwire.CustomRecords) *LinkError {
3✔
2403

3✔
2404
        l.RLock()
3✔
2405
        policy := l.cfg.FwrdingPolicy
3✔
2406
        l.RUnlock()
3✔
2407

3✔
2408
        // Using the outgoing HTLC amount, we'll calculate the outgoing
3✔
2409
        // fee this incoming HTLC must carry in order to satisfy the constraints
3✔
2410
        // of the outgoing link.
3✔
2411
        outFee := ExpectedFee(policy, amtToForward)
3✔
2412

3✔
2413
        // Then calculate the inbound fee that we charge based on the sum of
3✔
2414
        // outgoing HTLC amount and outgoing fee.
3✔
2415
        inFee := inboundFee.CalcFee(amtToForward + outFee)
3✔
2416

3✔
2417
        // Add up both fee components. It is important to calculate both fees
3✔
2418
        // separately. An alternative way of calculating is to first determine
3✔
2419
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
3✔
2420
        // rounding may cause the result to be slightly higher than in the case
3✔
2421
        // of separately rounded fee components. This potentially causes failed
3✔
2422
        // forwards for senders and is something to be avoided.
3✔
2423
        expectedFee := inFee + int64(outFee)
3✔
2424

3✔
2425
        // If the actual fee is less than our expected fee, then we'll reject
3✔
2426
        // this HTLC as it didn't provide a sufficient amount of fees, or the
3✔
2427
        // values have been tampered with, or the send used incorrect/dated
3✔
2428
        // information to construct the forwarding information for this hop. In
3✔
2429
        // any case, we'll cancel this HTLC.
3✔
2430
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
3✔
2431
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
6✔
2432
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
3✔
2433
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
3✔
2434
                        "inboundFee=%v",
3✔
2435
                        payHash[:], expectedFee, actualFee,
3✔
2436
                        incomingHtlcAmt, amtToForward, inboundFee,
3✔
2437
                )
3✔
2438

3✔
2439
                // As part of the returned error, we'll send our latest routing
3✔
2440
                // policy so the sending node obtains the most up to date data.
3✔
2441
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
6✔
2442
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
3✔
2443
                }
3✔
2444
                failure := l.createFailureWithUpdate(false, originalScid, cb)
3✔
2445
                return NewLinkError(failure)
3✔
2446
        }
2447

2448
        // Check whether the outgoing htlc satisfies the channel policy.
2449
        err := l.canSendHtlc(
3✔
2450
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
3✔
2451
                originalScid, customRecords,
3✔
2452
        )
3✔
2453
        if err != nil {
6✔
2454
                return err
3✔
2455
        }
3✔
2456

2457
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
2458
        // the following constraint: the incoming time-lock minus our time-lock
2459
        // delta should equal the outgoing time lock. Otherwise, whether the
2460
        // sender messed up, or an intermediate node tampered with the HTLC.
2461
        timeDelta := policy.TimeLockDelta
3✔
2462
        if incomingTimeout < outgoingTimeout+timeDelta {
3✔
2463
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
×
2464
                        "expected at least %v block delta, got %v block delta",
×
2465
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
×
2466

×
2467
                // Grab the latest routing policy so the sending node is up to
×
2468
                // date with our current policy.
×
2469
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
×
2470
                        return lnwire.NewIncorrectCltvExpiry(
×
2471
                                incomingTimeout, *upd,
×
2472
                        )
×
2473
                }
×
2474
                failure := l.createFailureWithUpdate(false, originalScid, cb)
×
2475
                return NewLinkError(failure)
×
2476
        }
2477

2478
        return nil
3✔
2479
}
2480

2481
// CheckHtlcTransit should return a nil error if the passed HTLC details
2482
// satisfy the current channel policy.  Otherwise, a LinkError with a
2483
// valid protocol failure message should be returned in order to signal
2484
// the violation. This call is intended to be used for locally initiated
2485
// payments for which there is no corresponding incoming htlc.
2486
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
2487
        amt lnwire.MilliSatoshi, timeout uint32, heightNow uint32,
2488
        customRecords lnwire.CustomRecords) *LinkError {
3✔
2489

3✔
2490
        l.RLock()
3✔
2491
        policy := l.cfg.FwrdingPolicy
3✔
2492
        l.RUnlock()
3✔
2493

3✔
2494
        // We pass in hop.Source here as this is only used in the Switch when
3✔
2495
        // trying to send over a local link. This causes the fallback mechanism
3✔
2496
        // to occur.
3✔
2497
        return l.canSendHtlc(
3✔
2498
                policy, payHash, amt, timeout, heightNow, hop.Source,
3✔
2499
                customRecords,
3✔
2500
        )
3✔
2501
}
3✔
2502

2503
// canSendHtlc checks whether the given htlc parameters satisfy
2504
// the channel's amount and time lock constraints.
2505
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
2506
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
2507
        heightNow uint32, originalScid lnwire.ShortChannelID,
2508
        customRecords lnwire.CustomRecords) *LinkError {
3✔
2509

3✔
2510
        // As our first sanity check, we'll ensure that the passed HTLC isn't
3✔
2511
        // too small for the next hop. If so, then we'll cancel the HTLC
3✔
2512
        // directly.
3✔
2513
        if amt < policy.MinHTLCOut {
6✔
2514
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
3✔
2515
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
3✔
2516
                        amt)
3✔
2517

3✔
2518
                // As part of the returned error, we'll send our latest routing
3✔
2519
                // policy so the sending node obtains the most up to date data.
3✔
2520
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
6✔
2521
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
3✔
2522
                }
3✔
2523
                failure := l.createFailureWithUpdate(false, originalScid, cb)
3✔
2524
                return NewLinkError(failure)
3✔
2525
        }
2526

2527
        // Next, ensure that the passed HTLC isn't too large. If so, we'll
2528
        // cancel the HTLC directly.
2529
        if policy.MaxHTLC != 0 && amt > policy.MaxHTLC {
6✔
2530
                l.log.Warnf("outgoing htlc(%x) is too large: max_htlc=%v, "+
3✔
2531
                        "htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
3✔
2532

3✔
2533
                // As part of the returned error, we'll send our latest routing
3✔
2534
                // policy so the sending node obtains the most up-to-date data.
3✔
2535
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
6✔
2536
                        return lnwire.NewTemporaryChannelFailure(upd)
3✔
2537
                }
3✔
2538
                failure := l.createFailureWithUpdate(false, originalScid, cb)
3✔
2539
                return NewDetailedLinkError(failure, OutgoingFailureHTLCExceedsMax)
3✔
2540
        }
2541

2542
        // We want to avoid offering an HTLC which will expire in the near
2543
        // future, so we'll reject an HTLC if the outgoing expiration time is
2544
        // too close to the current height.
2545
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
3✔
2546
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
×
2547
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
×
2548
                        timeout, heightNow)
×
2549

×
2550
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
×
2551
                        return lnwire.NewExpiryTooSoon(*upd)
×
2552
                }
×
2553
                failure := l.createFailureWithUpdate(false, originalScid, cb)
×
2554
                return NewLinkError(failure)
×
2555
        }
2556

2557
        // Check absolute max delta.
2558
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
3✔
2559
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
×
2560
                        "the future: got %v, but maximum is %v", payHash[:],
×
2561
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
×
2562

×
2563
                return NewLinkError(&lnwire.FailExpiryTooFar{})
×
2564
        }
×
2565

2566
        // We now check the available bandwidth to see if this HTLC can be
2567
        // forwarded.
2568
        availableBandwidth := l.Bandwidth()
3✔
2569
        auxBandwidth, err := fn.MapOptionZ(
3✔
2570
                l.cfg.AuxTrafficShaper,
3✔
2571
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
3✔
2572
                        var htlcBlob fn.Option[tlv.Blob]
×
2573
                        blob, err := customRecords.Serialize()
×
2574
                        if err != nil {
×
2575
                                return fn.Err[OptionalBandwidth](
×
2576
                                        fmt.Errorf("unable to serialize "+
×
2577
                                                "custom records: %w", err))
×
2578
                        }
×
2579

2580
                        if len(blob) > 0 {
×
2581
                                htlcBlob = fn.Some(blob)
×
2582
                        }
×
2583

2584
                        return l.AuxBandwidth(amt, originalScid, htlcBlob, ts)
×
2585
                },
2586
        ).Unpack()
2587
        if err != nil {
3✔
2588
                l.log.Errorf("Unable to determine aux bandwidth: %v", err)
×
2589
                return NewLinkError(&lnwire.FailTemporaryNodeFailure{})
×
2590
        }
×
2591

2592
        if auxBandwidth.IsHandled && auxBandwidth.Bandwidth.IsSome() {
3✔
2593
                auxBandwidth.Bandwidth.WhenSome(
×
2594
                        func(bandwidth lnwire.MilliSatoshi) {
×
2595
                                availableBandwidth = bandwidth
×
2596
                        },
×
2597
                )
2598
        }
2599

2600
        // Check to see if there is enough balance in this channel.
2601
        if amt > availableBandwidth {
6✔
2602
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
3✔
2603
                        "larger than %v", amt, availableBandwidth)
3✔
2604
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
6✔
2605
                        return lnwire.NewTemporaryChannelFailure(upd)
3✔
2606
                }
3✔
2607
                failure := l.createFailureWithUpdate(false, originalScid, cb)
3✔
2608
                return NewDetailedLinkError(
3✔
2609
                        failure, OutgoingFailureInsufficientBalance,
3✔
2610
                )
3✔
2611
        }
2612

2613
        return nil
3✔
2614
}
2615

2616
// AuxBandwidth returns the bandwidth that can be used for a channel, expressed
2617
// in milli-satoshi. This might be different from the regular BTC bandwidth for
2618
// custom channels. This will always return fn.None() for a regular (non-custom)
2619
// channel.
2620
func (l *channelLink) AuxBandwidth(amount lnwire.MilliSatoshi,
2621
        cid lnwire.ShortChannelID, htlcBlob fn.Option[tlv.Blob],
2622
        ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
×
2623

×
2624
        fundingBlob := l.FundingCustomBlob()
×
2625
        shouldHandle, err := ts.ShouldHandleTraffic(cid, fundingBlob, htlcBlob)
×
2626
        if err != nil {
×
2627
                return fn.Err[OptionalBandwidth](fmt.Errorf("traffic shaper "+
×
2628
                        "failed to decide whether to handle traffic: %w", err))
×
2629
        }
×
2630

2631
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
2632
                "traffic: %v", cid, shouldHandle)
×
2633

×
2634
        // If this channel isn't handled by the aux traffic shaper, we'll return
×
2635
        // early.
×
2636
        if !shouldHandle {
×
2637
                return fn.Ok(OptionalBandwidth{
×
2638
                        IsHandled: false,
×
2639
                })
×
2640
        }
×
2641

2642
        // Ask for a specific bandwidth to be used for the channel.
2643
        commitmentBlob := l.CommitmentCustomBlob()
×
2644
        auxBandwidth, err := ts.PaymentBandwidth(
×
2645
                fundingBlob, htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
2646
                l.channel.FetchLatestAuxHTLCView(),
×
2647
        )
×
2648
        if err != nil {
×
2649
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
2650
                        "bandwidth from external traffic shaper: %w", err))
×
2651
        }
×
2652

2653
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
2654
                "bandwidth: %v", cid, auxBandwidth)
×
2655

×
2656
        return fn.Ok(OptionalBandwidth{
×
2657
                IsHandled: true,
×
2658
                Bandwidth: fn.Some(auxBandwidth),
×
2659
        })
×
2660
}
2661

2662
// Stats returns the statistics of channel link.
2663
//
2664
// NOTE: Part of the ChannelLink interface.
2665
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
3✔
2666
        snapshot := l.channel.StateSnapshot()
3✔
2667

3✔
2668
        return snapshot.ChannelCommitment.CommitHeight,
3✔
2669
                snapshot.TotalMSatSent,
3✔
2670
                snapshot.TotalMSatReceived
3✔
2671
}
3✔
2672

2673
// String returns the string representation of channel link.
2674
//
2675
// NOTE: Part of the ChannelLink interface.
2676
func (l *channelLink) String() string {
×
2677
        return l.channel.ChannelPoint().String()
×
2678
}
×
2679

2680
// handleSwitchPacket handles the switch packets. This packets which might be
2681
// forwarded to us from another channel link in case the htlc update came from
2682
// another peer or if the update was created by user
2683
//
2684
// NOTE: Part of the packetHandler interface.
2685
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
3✔
2686
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
3✔
2687
                pkt.inKey(), pkt.outKey())
3✔
2688

3✔
2689
        return l.mailBox.AddPacket(pkt)
3✔
2690
}
3✔
2691

2692
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
2693
// to us from remote peer we have a channel with.
2694
//
2695
// NOTE: Part of the ChannelLink interface.
2696
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3✔
2697
        select {
3✔
2698
        case <-l.cg.Done():
×
2699
                // Return early if the link is already in the process of
×
2700
                // quitting. It doesn't make sense to hand the message to the
×
2701
                // mailbox here.
×
2702
                return
×
2703
        default:
3✔
2704
        }
2705

2706
        err := l.mailBox.AddMessage(message)
3✔
2707
        if err != nil {
3✔
2708
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
2709
        }
×
2710
}
2711

2712
// updateChannelFee updates the commitment fee-per-kw on this channel by
2713
// committing to an update_fee message.
2714
func (l *channelLink) updateChannelFee(ctx context.Context,
2715
        feePerKw chainfee.SatPerKWeight) error {
×
2716

×
2717
        l.log.Infof("updating commit fee to %v", feePerKw)
×
2718

×
2719
        // We skip sending the UpdateFee message if the channel is not
×
2720
        // currently eligible to forward messages.
×
2721
        if !l.eligibleToUpdate() {
×
2722
                l.log.Debugf("skipping fee update for inactive channel")
×
2723
                return nil
×
2724
        }
×
2725

2726
        // Check and see if our proposed fee-rate would make us exceed the fee
2727
        // threshold.
2728
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
×
2729
        if err != nil {
×
2730
                // This shouldn't typically happen. If it does, it indicates
×
2731
                // something is wrong with our channel state.
×
2732
                return err
×
2733
        }
×
2734

2735
        if thresholdExceeded {
×
2736
                return fmt.Errorf("link fee threshold exceeded")
×
2737
        }
×
2738

2739
        // First, we'll update the local fee on our commitment.
2740
        if err := l.channel.UpdateFee(feePerKw); err != nil {
×
2741
                return err
×
2742
        }
×
2743

2744
        // The fee passed the channel's validation checks, so we update the
2745
        // mailbox feerate.
2746
        l.mailBox.SetFeeRate(feePerKw)
×
2747

×
2748
        // We'll then attempt to send a new UpdateFee message, and also lock it
×
2749
        // in immediately by triggering a commitment update.
×
2750
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
×
2751
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
×
2752
                return err
×
2753
        }
×
2754

2755
        return l.updateCommitTx(ctx)
×
2756
}
2757

2758
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
2759
// after receiving a revocation from the remote party, and reprocesses them in
2760
// the context of the provided forwarding package. Any settles or fails that
2761
// have already been acknowledged in the forwarding package will not be sent to
2762
// the switch.
2763
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
3✔
2764
        if len(fwdPkg.SettleFails) == 0 {
6✔
2765
                l.log.Trace("fwd package has no settle/fails to process " +
3✔
2766
                        "exiting early")
3✔
2767

3✔
2768
                return
3✔
2769
        }
3✔
2770

2771
        // Exit early if the fwdPkg is already processed.
2772
        if fwdPkg.State == channeldb.FwdStateCompleted {
3✔
2773
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2774

×
2775
                return
×
2776
        }
×
2777

2778
        l.log.Debugf("settle-fail-filter: %v", fwdPkg.SettleFailFilter)
3✔
2779

3✔
2780
        var switchPackets []*htlcPacket
3✔
2781
        for i, update := range fwdPkg.SettleFails {
6✔
2782
                destRef := fwdPkg.DestRef(uint16(i))
3✔
2783

3✔
2784
                // Skip any settles or fails that have already been
3✔
2785
                // acknowledged by the incoming link that originated the
3✔
2786
                // forwarded Add.
3✔
2787
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
3✔
2788
                        continue
×
2789
                }
2790

2791
                // TODO(roasbeef): rework log entries to a shared
2792
                // interface.
2793

2794
                switch msg := update.UpdateMsg.(type) {
3✔
2795
                // A settle for an HTLC we previously forwarded HTLC has been
2796
                // received. So we'll forward the HTLC to the switch which will
2797
                // handle propagating the settle to the prior hop.
2798
                case *lnwire.UpdateFulfillHTLC:
3✔
2799
                        // If hodl.SettleIncoming is requested, we will not
3✔
2800
                        // forward the SETTLE to the switch and will not signal
3✔
2801
                        // a free slot on the commitment transaction.
3✔
2802
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
3✔
2803
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
2804
                                continue
×
2805
                        }
2806

2807
                        settlePacket := &htlcPacket{
3✔
2808
                                outgoingChanID: l.ShortChanID(),
3✔
2809
                                outgoingHTLCID: msg.ID,
3✔
2810
                                destRef:        &destRef,
3✔
2811
                                htlc:           msg,
3✔
2812
                        }
3✔
2813

3✔
2814
                        // Add the packet to the batch to be forwarded, and
3✔
2815
                        // notify the overflow queue that a spare spot has been
3✔
2816
                        // freed up within the commitment state.
3✔
2817
                        switchPackets = append(switchPackets, settlePacket)
3✔
2818

2819
                // A failureCode message for a previously forwarded HTLC has
2820
                // been received. As a result a new slot will be freed up in
2821
                // our commitment state, so we'll forward this to the switch so
2822
                // the backwards undo can continue.
2823
                case *lnwire.UpdateFailHTLC:
3✔
2824
                        // If hodl.SettleIncoming is requested, we will not
3✔
2825
                        // forward the FAIL to the switch and will not signal a
3✔
2826
                        // free slot on the commitment transaction.
3✔
2827
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
3✔
2828
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
2829
                                continue
×
2830
                        }
2831

2832
                        // Fetch the reason the HTLC was canceled so we can
2833
                        // continue to propagate it. This failure originated
2834
                        // from another node, so the linkFailure field is not
2835
                        // set on the packet.
2836
                        failPacket := &htlcPacket{
3✔
2837
                                outgoingChanID: l.ShortChanID(),
3✔
2838
                                outgoingHTLCID: msg.ID,
3✔
2839
                                destRef:        &destRef,
3✔
2840
                                htlc:           msg,
3✔
2841
                        }
3✔
2842

3✔
2843
                        l.log.Debugf("Failed to send HTLC with ID=%d", msg.ID)
3✔
2844

3✔
2845
                        // If the failure message lacks an HMAC (but includes
3✔
2846
                        // the 4 bytes for encoding the message and padding
3✔
2847
                        // lengths, then this means that we received it as an
3✔
2848
                        // UpdateFailMalformedHTLC. As a result, we'll signal
3✔
2849
                        // that we need to convert this error within the switch
3✔
2850
                        // to an actual error, by encrypting it as if we were
3✔
2851
                        // the originating hop.
3✔
2852
                        convertedErrorSize := lnwire.FailureMessageLength + 4
3✔
2853
                        if len(msg.Reason) == convertedErrorSize {
6✔
2854
                                failPacket.convertedError = true
3✔
2855
                        }
3✔
2856

2857
                        // Add the packet to the batch to be forwarded, and
2858
                        // notify the overflow queue that a spare spot has been
2859
                        // freed up within the commitment state.
2860
                        switchPackets = append(switchPackets, failPacket)
3✔
2861
                }
2862
        }
2863

2864
        // Only spawn the task forward packets we have a non-zero number.
2865
        if len(switchPackets) > 0 {
6✔
2866
                go l.forwardBatch(false, switchPackets...)
3✔
2867
        }
3✔
2868
}
2869

2870
// processRemoteAdds serially processes each of the Add payment descriptors
2871
// which have been "locked-in" by receiving a revocation from the remote party.
2872
// The forwarding package provided instructs how to process this batch,
2873
// indicating whether this is the first time these Adds are being processed, or
2874
// whether we are reprocessing as a result of a failure or restart. Adds that
2875
// have already been acknowledged in the forwarding package will be ignored.
2876
//
2877
//nolint:funlen
2878
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
3✔
2879
        // Exit early if there are no adds to process.
3✔
2880
        if len(fwdPkg.Adds) == 0 {
6✔
2881
                l.log.Trace("fwd package has no adds to process exiting early")
3✔
2882

3✔
2883
                return
3✔
2884
        }
3✔
2885

2886
        // Exit early if the fwdPkg is already processed.
2887
        if fwdPkg.State == channeldb.FwdStateCompleted {
3✔
2888
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2889

×
2890
                return
×
2891
        }
×
2892

2893
        l.log.Tracef("processing %d remote adds for height %d",
3✔
2894
                len(fwdPkg.Adds), fwdPkg.Height)
3✔
2895

3✔
2896
        // decodeReqs is a list of requests sent to the onion decoder. We expect
3✔
2897
        // the same length of responses to be returned.
3✔
2898
        decodeReqs := make([]hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds))
3✔
2899

3✔
2900
        // unackedAdds is a list of ADDs that's waiting for the remote's
3✔
2901
        // settle/fail update.
3✔
2902
        unackedAdds := make([]*lnwire.UpdateAddHTLC, 0, len(fwdPkg.Adds))
3✔
2903

3✔
2904
        for i, update := range fwdPkg.Adds {
6✔
2905
                // If this index is already found in the ack filter, the
3✔
2906
                // response to this forwarding decision has already been
3✔
2907
                // committed by one of our commitment txns. ADDs in this state
3✔
2908
                // are waiting for the rest of the fwding package to get acked
3✔
2909
                // before being garbage collected.
3✔
2910
                if fwdPkg.State == channeldb.FwdStateProcessed &&
3✔
2911
                        fwdPkg.AckFilter.Contains(uint16(i)) {
3✔
2912

×
2913
                        continue
×
2914
                }
2915

2916
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
6✔
2917
                        // Before adding the new htlc to the state machine,
3✔
2918
                        // parse the onion object in order to obtain the
3✔
2919
                        // routing information with DecodeHopIterator function
3✔
2920
                        // which process the Sphinx packet.
3✔
2921
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
3✔
2922

3✔
2923
                        req := hop.DecodeHopIteratorRequest{
3✔
2924
                                OnionReader:    onionReader,
3✔
2925
                                RHash:          msg.PaymentHash[:],
3✔
2926
                                IncomingCltv:   msg.Expiry,
3✔
2927
                                IncomingAmount: msg.Amount,
3✔
2928
                                BlindingPoint:  msg.BlindingPoint,
3✔
2929
                        }
3✔
2930

3✔
2931
                        decodeReqs = append(decodeReqs, req)
3✔
2932
                        unackedAdds = append(unackedAdds, msg)
3✔
2933
                }
3✔
2934
        }
2935

2936
        // If the fwdPkg has already been processed, it means we are
2937
        // reforwarding the packets again, which happens only on a restart.
2938
        reforward := fwdPkg.State == channeldb.FwdStateProcessed
3✔
2939

3✔
2940
        // Atomically decode the incoming htlcs, simultaneously checking for
3✔
2941
        // replay attempts. A particular index in the returned, spare list of
3✔
2942
        // channel iterators should only be used if the failure code at the
3✔
2943
        // same index is lnwire.FailCodeNone.
3✔
2944
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
3✔
2945
                fwdPkg.ID(), decodeReqs, reforward,
3✔
2946
        )
3✔
2947
        if sphinxErr != nil {
3✔
2948
                l.failf(LinkFailureError{code: ErrInternalError},
×
2949
                        "unable to decode hop iterators: %v", sphinxErr)
×
2950
                return
×
2951
        }
×
2952

2953
        var switchPackets []*htlcPacket
3✔
2954

3✔
2955
        for i, update := range unackedAdds {
6✔
2956
                idx := uint16(i)
3✔
2957
                sourceRef := fwdPkg.SourceRef(idx)
3✔
2958
                add := *update
3✔
2959

3✔
2960
                // An incoming HTLC add has been full-locked in. As a result we
3✔
2961
                // can now examine the forwarding details of the HTLC, and the
3✔
2962
                // HTLC itself to decide if: we should forward it, cancel it,
3✔
2963
                // or are able to settle it (and it adheres to our fee related
3✔
2964
                // constraints).
3✔
2965

3✔
2966
                // Before adding the new htlc to the state machine, parse the
3✔
2967
                // onion object in order to obtain the routing information with
3✔
2968
                // DecodeHopIterator function which process the Sphinx packet.
3✔
2969
                chanIterator, failureCode := decodeResps[i].Result()
3✔
2970
                if failureCode != lnwire.CodeNone {
6✔
2971
                        // If we're unable to process the onion blob then we
3✔
2972
                        // should send the malformed htlc error to payment
3✔
2973
                        // sender.
3✔
2974
                        l.sendMalformedHTLCError(
3✔
2975
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
3✔
2976
                        )
3✔
2977

3✔
2978
                        l.log.Errorf("unable to decode onion hop iterator "+
3✔
2979
                                "for htlc(id=%v, hash=%x): %v", add.ID,
3✔
2980
                                add.PaymentHash, failureCode)
3✔
2981

3✔
2982
                        continue
3✔
2983
                }
2984

2985
                heightNow := l.cfg.BestHeight()
3✔
2986

3✔
2987
                pld, routeRole, pldErr := chanIterator.HopPayload()
3✔
2988
                if pldErr != nil {
6✔
2989
                        // If we're unable to process the onion payload, or we
3✔
2990
                        // received invalid onion payload failure, then we
3✔
2991
                        // should send an error back to the caller so the HTLC
3✔
2992
                        // can be canceled.
3✔
2993
                        var failedType uint64
3✔
2994

3✔
2995
                        // We need to get the underlying error value, so we
3✔
2996
                        // can't use errors.As as suggested by the linter.
3✔
2997
                        //nolint:errorlint
3✔
2998
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
3✔
2999
                                failedType = uint64(e.Type)
×
3000
                        }
×
3001

3002
                        // If we couldn't parse the payload, make our best
3003
                        // effort at creating an error encrypter that knows
3004
                        // what blinding type we were, but if we couldn't
3005
                        // parse the payload we have no way of knowing whether
3006
                        // we were the introduction node or not.
3007
                        //
3008
                        //nolint:ll
3009
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
3✔
3010
                                l.cfg.ExtractErrorEncrypter,
3✔
3011
                                // We need our route role here because we
3✔
3012
                                // couldn't parse or validate the payload.
3✔
3013
                                routeRole == hop.RouteRoleIntroduction,
3✔
3014
                        )
3✔
3015
                        if failCode != lnwire.CodeNone {
3✔
3016
                                l.log.Errorf("could not extract error "+
×
3017
                                        "encrypter: %v", pldErr)
×
3018

×
3019
                                // We can't process this htlc, send back
×
3020
                                // malformed.
×
3021
                                l.sendMalformedHTLCError(
×
3022
                                        add.ID, failureCode, add.OnionBlob,
×
3023
                                        &sourceRef,
×
3024
                                )
×
3025

×
3026
                                continue
×
3027
                        }
3028

3029
                        // TODO: currently none of the test unit infrastructure
3030
                        // is setup to handle TLV payloads, so testing this
3031
                        // would require implementing a separate mock iterator
3032
                        // for TLV payloads that also supports injecting invalid
3033
                        // payloads. Deferring this non-trival effort till a
3034
                        // later date
3035
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
3✔
3036

3✔
3037
                        l.sendHTLCError(
3✔
3038
                                add, sourceRef, NewLinkError(failure),
3✔
3039
                                obfuscator, false,
3✔
3040
                        )
3✔
3041

3✔
3042
                        l.log.Errorf("unable to decode forwarding "+
3✔
3043
                                "instructions: %v", pldErr)
3✔
3044

3✔
3045
                        continue
3✔
3046
                }
3047

3048
                // Retrieve onion obfuscator from onion blob in order to
3049
                // produce initial obfuscation of the onion failureCode.
3050
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
3✔
3051
                        l.cfg.ExtractErrorEncrypter,
3✔
3052
                        routeRole == hop.RouteRoleIntroduction,
3✔
3053
                )
3✔
3054
                if failureCode != lnwire.CodeNone {
3✔
3055
                        // If we're unable to process the onion blob than we
×
3056
                        // should send the malformed htlc error to payment
×
3057
                        // sender.
×
3058
                        l.sendMalformedHTLCError(
×
3059
                                add.ID, failureCode, add.OnionBlob,
×
3060
                                &sourceRef,
×
3061
                        )
×
3062

×
3063
                        l.log.Errorf("unable to decode onion "+
×
3064
                                "obfuscator: %v", failureCode)
×
3065

×
3066
                        continue
×
3067
                }
3068

3069
                fwdInfo := pld.ForwardingInfo()
3✔
3070

3✔
3071
                // Check whether the payload we've just processed uses our
3✔
3072
                // node as the introduction point (gave us a blinding key in
3✔
3073
                // the payload itself) and fail it back if we don't support
3✔
3074
                // route blinding.
3✔
3075
                if fwdInfo.NextBlinding.IsSome() &&
3✔
3076
                        l.cfg.DisallowRouteBlinding {
6✔
3077

3✔
3078
                        failure := lnwire.NewInvalidBlinding(
3✔
3079
                                fn.Some(add.OnionBlob),
3✔
3080
                        )
3✔
3081

3✔
3082
                        l.sendHTLCError(
3✔
3083
                                add, sourceRef, NewLinkError(failure),
3✔
3084
                                obfuscator, false,
3✔
3085
                        )
3✔
3086

3✔
3087
                        l.log.Error("rejected htlc that uses use as an " +
3✔
3088
                                "introduction point when we do not support " +
3✔
3089
                                "route blinding")
3✔
3090

3✔
3091
                        continue
3✔
3092
                }
3093

3094
                switch fwdInfo.NextHop {
3✔
3095
                case hop.Exit:
3✔
3096
                        err := l.processExitHop(
3✔
3097
                                add, sourceRef, obfuscator, fwdInfo,
3✔
3098
                                heightNow, pld,
3✔
3099
                        )
3✔
3100
                        if err != nil {
3✔
3101
                                l.failf(LinkFailureError{
×
3102
                                        code: ErrInternalError,
×
3103
                                }, err.Error()) //nolint
×
3104

×
3105
                                return
×
3106
                        }
×
3107

3108
                // There are additional channels left within this route. So
3109
                // we'll simply do some forwarding package book-keeping.
3110
                default:
3✔
3111
                        // If hodl.AddIncoming is requested, we will not
3✔
3112
                        // validate the forwarded ADD, nor will we send the
3✔
3113
                        // packet to the htlc switch.
3✔
3114
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
3✔
3115
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3116
                                continue
×
3117
                        }
3118

3119
                        endorseValue := l.experimentalEndorsement(
3✔
3120
                                record.CustomSet(add.CustomRecords),
3✔
3121
                        )
3✔
3122
                        endorseType := uint64(
3✔
3123
                                lnwire.ExperimentalEndorsementType,
3✔
3124
                        )
3✔
3125

3✔
3126
                        switch fwdPkg.State {
3✔
3127
                        case channeldb.FwdStateProcessed:
3✔
3128
                                // This add was not forwarded on the previous
3✔
3129
                                // processing phase, run it through our
3✔
3130
                                // validation pipeline to reproduce an error.
3✔
3131
                                // This may trigger a different error due to
3✔
3132
                                // expiring timelocks, but we expect that an
3✔
3133
                                // error will be reproduced.
3✔
3134
                                if !fwdPkg.FwdFilter.Contains(idx) {
3✔
3135
                                        break
×
3136
                                }
3137

3138
                                // Otherwise, it was already processed, we can
3139
                                // can collect it and continue.
3140
                                outgoingAdd := &lnwire.UpdateAddHTLC{
3✔
3141
                                        Expiry:        fwdInfo.OutgoingCTLV,
3✔
3142
                                        Amount:        fwdInfo.AmountToForward,
3✔
3143
                                        PaymentHash:   add.PaymentHash,
3✔
3144
                                        BlindingPoint: fwdInfo.NextBlinding,
3✔
3145
                                }
3✔
3146

3✔
3147
                                endorseValue.WhenSome(func(e byte) {
6✔
3148
                                        custRecords := map[uint64][]byte{
3✔
3149
                                                endorseType: {e},
3✔
3150
                                        }
3✔
3151

3✔
3152
                                        outgoingAdd.CustomRecords = custRecords
3✔
3153
                                })
3✔
3154

3155
                                // Finally, we'll encode the onion packet for
3156
                                // the _next_ hop using the hop iterator
3157
                                // decoded for the current hop.
3158
                                buf := bytes.NewBuffer(
3✔
3159
                                        outgoingAdd.OnionBlob[0:0],
3✔
3160
                                )
3✔
3161

3✔
3162
                                // We know this cannot fail, as this ADD
3✔
3163
                                // was marked forwarded in a previous
3✔
3164
                                // round of processing.
3✔
3165
                                chanIterator.EncodeNextHop(buf)
3✔
3166

3✔
3167
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
3168

3✔
3169
                                //nolint:ll
3✔
3170
                                updatePacket := &htlcPacket{
3✔
3171
                                        incomingChanID:       l.ShortChanID(),
3✔
3172
                                        incomingHTLCID:       add.ID,
3✔
3173
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
3174
                                        sourceRef:            &sourceRef,
3✔
3175
                                        incomingAmount:       add.Amount,
3✔
3176
                                        amount:               outgoingAdd.Amount,
3✔
3177
                                        htlc:                 outgoingAdd,
3✔
3178
                                        obfuscator:           obfuscator,
3✔
3179
                                        incomingTimeout:      add.Expiry,
3✔
3180
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
3181
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
3182
                                        inboundFee:           inboundFee,
3✔
3183
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
3184
                                }
3✔
3185
                                switchPackets = append(
3✔
3186
                                        switchPackets, updatePacket,
3✔
3187
                                )
3✔
3188

3✔
3189
                                continue
3✔
3190
                        }
3191

3192
                        // TODO(roasbeef): ensure don't accept outrageous
3193
                        // timeout for htlc
3194

3195
                        // With all our forwarding constraints met, we'll
3196
                        // create the outgoing HTLC using the parameters as
3197
                        // specified in the forwarding info.
3198
                        addMsg := &lnwire.UpdateAddHTLC{
3✔
3199
                                Expiry:        fwdInfo.OutgoingCTLV,
3✔
3200
                                Amount:        fwdInfo.AmountToForward,
3✔
3201
                                PaymentHash:   add.PaymentHash,
3✔
3202
                                BlindingPoint: fwdInfo.NextBlinding,
3✔
3203
                        }
3✔
3204

3✔
3205
                        endorseValue.WhenSome(func(e byte) {
6✔
3206
                                addMsg.CustomRecords = map[uint64][]byte{
3✔
3207
                                        endorseType: {e},
3✔
3208
                                }
3✔
3209
                        })
3✔
3210

3211
                        // Finally, we'll encode the onion packet for the
3212
                        // _next_ hop using the hop iterator decoded for the
3213
                        // current hop.
3214
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
3✔
3215
                        err := chanIterator.EncodeNextHop(buf)
3✔
3216
                        if err != nil {
3✔
3217
                                l.log.Errorf("unable to encode the "+
×
3218
                                        "remaining route %v", err)
×
3219

×
3220
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
3221
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
3222
                                }
×
3223

3224
                                failure := l.createFailureWithUpdate(
×
3225
                                        true, hop.Source, cb,
×
3226
                                )
×
3227

×
3228
                                l.sendHTLCError(
×
3229
                                        add, sourceRef, NewLinkError(failure),
×
3230
                                        obfuscator, false,
×
3231
                                )
×
3232
                                continue
×
3233
                        }
3234

3235
                        // Now that this add has been reprocessed, only append
3236
                        // it to our list of packets to forward to the switch
3237
                        // this is the first time processing the add. If the
3238
                        // fwd pkg has already been processed, then we entered
3239
                        // the above section to recreate a previous error.  If
3240
                        // the packet had previously been forwarded, it would
3241
                        // have been added to switchPackets at the top of this
3242
                        // section.
3243
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
6✔
3244
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
3245

3✔
3246
                                //nolint:ll
3✔
3247
                                updatePacket := &htlcPacket{
3✔
3248
                                        incomingChanID:       l.ShortChanID(),
3✔
3249
                                        incomingHTLCID:       add.ID,
3✔
3250
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
3251
                                        sourceRef:            &sourceRef,
3✔
3252
                                        incomingAmount:       add.Amount,
3✔
3253
                                        amount:               addMsg.Amount,
3✔
3254
                                        htlc:                 addMsg,
3✔
3255
                                        obfuscator:           obfuscator,
3✔
3256
                                        incomingTimeout:      add.Expiry,
3✔
3257
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
3258
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
3259
                                        inboundFee:           inboundFee,
3✔
3260
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
3261
                                }
3✔
3262

3✔
3263
                                fwdPkg.FwdFilter.Set(idx)
3✔
3264
                                switchPackets = append(switchPackets,
3✔
3265
                                        updatePacket)
3✔
3266
                        }
3✔
3267
                }
3268
        }
3269

3270
        // Commit the htlcs we are intending to forward if this package has not
3271
        // been fully processed.
3272
        if fwdPkg.State == channeldb.FwdStateLockedIn {
6✔
3273
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
3✔
3274
                if err != nil {
3✔
3275
                        l.failf(LinkFailureError{code: ErrInternalError},
×
3276
                                "unable to set fwd filter: %v", err)
×
3277
                        return
×
3278
                }
×
3279
        }
3280

3281
        if len(switchPackets) == 0 {
6✔
3282
                return
3✔
3283
        }
3✔
3284

3285
        l.log.Debugf("forwarding %d packets to switch: reforward=%v",
3✔
3286
                len(switchPackets), reforward)
3✔
3287

3✔
3288
        // NOTE: This call is made synchronous so that we ensure all circuits
3✔
3289
        // are committed in the exact order that they are processed in the link.
3✔
3290
        // Failing to do this could cause reorderings/gaps in the range of
3✔
3291
        // opened circuits, which violates assumptions made by the circuit
3✔
3292
        // trimming.
3✔
3293
        l.forwardBatch(reforward, switchPackets...)
3✔
3294
}
3295

3296
// experimentalEndorsement returns the value to set for our outgoing
3297
// experimental endorsement field, and a boolean indicating whether it should
3298
// be populated on the outgoing htlc.
3299
func (l *channelLink) experimentalEndorsement(
3300
        customUpdateAdd record.CustomSet) fn.Option[byte] {
3✔
3301

3✔
3302
        // Only relay experimental signal if we are within the experiment
3✔
3303
        // period.
3✔
3304
        if !l.cfg.ShouldFwdExpEndorsement() {
6✔
3305
                return fn.None[byte]()
3✔
3306
        }
3✔
3307

3308
        // If we don't have any custom records or the experimental field is
3309
        // not set, just forward a zero value.
3310
        if len(customUpdateAdd) == 0 {
6✔
3311
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
3312
        }
3✔
3313

3314
        t := uint64(lnwire.ExperimentalEndorsementType)
3✔
3315
        value, set := customUpdateAdd[t]
3✔
3316
        if !set {
3✔
3317
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3318
        }
×
3319

3320
        // We expect at least one byte for this field, consider it invalid if
3321
        // it has no data and just forward a zero value.
3322
        if len(value) == 0 {
3✔
3323
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3324
        }
×
3325

3326
        // Only forward endorsed if the incoming link is endorsed.
3327
        if value[0] == lnwire.ExperimentalEndorsed {
6✔
3328
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
3✔
3329
        }
3✔
3330

3331
        // Forward as unendorsed otherwise, including cases where we've
3332
        // received an invalid value that uses more than 3 bits of information.
3333
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
3334
}
3335

3336
// processExitHop handles an htlc for which this link is the exit hop. It
3337
// returns a boolean indicating whether the commitment tx needs an update.
3338
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
3339
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
3340
        fwdInfo hop.ForwardingInfo, heightNow uint32,
3341
        payload invoices.Payload) error {
3✔
3342

3✔
3343
        // If hodl.ExitSettle is requested, we will not validate the final hop's
3✔
3344
        // ADD, nor will we settle the corresponding invoice or respond with the
3✔
3345
        // preimage.
3✔
3346
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
6✔
3347
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
3✔
3348
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
3✔
3349

3✔
3350
                return nil
3✔
3351
        }
3✔
3352

3353
        // In case the traffic shaper is active, we'll check if the HTLC has
3354
        // custom records and skip the amount check in the onion payload below.
3355
        isCustomHTLC := fn.MapOptionZ(
3✔
3356
                l.cfg.AuxTrafficShaper,
3✔
3357
                func(ts AuxTrafficShaper) bool {
3✔
3358
                        return ts.IsCustomHTLC(add.CustomRecords)
×
3359
                },
×
3360
        )
3361

3362
        // As we're the exit hop, we'll double check the hop-payload included in
3363
        // the HTLC to ensure that it was crafted correctly by the sender and
3364
        // is compatible with the HTLC we were extended. If an external
3365
        // validator is active we might bypass the amount check.
3366
        if !isCustomHTLC && add.Amount < fwdInfo.AmountToForward {
3✔
3367
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
×
3368
                        "incompatible value: expected <=%v, got %v",
×
3369
                        add.PaymentHash, add.Amount, fwdInfo.AmountToForward)
×
3370

×
3371
                failure := NewLinkError(
×
3372
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
×
3373
                )
×
3374
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
3375

×
3376
                return nil
×
3377
        }
×
3378

3379
        // We'll also ensure that our time-lock value has been computed
3380
        // correctly.
3381
        if add.Expiry < fwdInfo.OutgoingCTLV {
3✔
3382
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
×
3383
                        "incompatible time-lock: expected <=%v, got %v",
×
3384
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
×
3385

×
3386
                failure := NewLinkError(
×
3387
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
×
3388
                )
×
3389

×
3390
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
3391

×
3392
                return nil
×
3393
        }
×
3394

3395
        // Notify the invoiceRegistry of the exit hop htlc. If we crash right
3396
        // after this, this code will be re-executed after restart. We will
3397
        // receive back a resolution event.
3398
        invoiceHash := lntypes.Hash(add.PaymentHash)
3✔
3399

3✔
3400
        circuitKey := models.CircuitKey{
3✔
3401
                ChanID: l.ShortChanID(),
3✔
3402
                HtlcID: add.ID,
3✔
3403
        }
3✔
3404

3✔
3405
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
3✔
3406
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
3✔
3407
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
3✔
3408
        )
3✔
3409
        if err != nil {
3✔
3410
                return err
×
3411
        }
×
3412

3413
        // Create a hodlHtlc struct and decide either resolved now or later.
3414
        htlc := hodlHtlc{
3✔
3415
                add:        add,
3✔
3416
                sourceRef:  sourceRef,
3✔
3417
                obfuscator: obfuscator,
3✔
3418
        }
3✔
3419

3✔
3420
        // If the event is nil, the invoice is being held, so we save payment
3✔
3421
        // descriptor for future reference.
3✔
3422
        if event == nil {
6✔
3423
                l.hodlMap[circuitKey] = htlc
3✔
3424
                return nil
3✔
3425
        }
3✔
3426

3427
        // Process the received resolution.
3428
        return l.processHtlcResolution(event, htlc)
3✔
3429
}
3430

3431
// settleHTLC settles the HTLC on the channel.
3432
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
3433
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
3✔
3434

3✔
3435
        hash := preimage.Hash()
3✔
3436

3✔
3437
        l.log.Infof("settling htlc %v as exit hop", hash)
3✔
3438

3✔
3439
        err := l.channel.SettleHTLC(
3✔
3440
                preimage, htlcIndex, &sourceRef, nil, nil,
3✔
3441
        )
3✔
3442
        if err != nil {
3✔
3443
                return fmt.Errorf("unable to settle htlc: %w", err)
×
3444
        }
×
3445

3446
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
3447
        // fake one before sending it to the peer.
3448
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
6✔
3449
                l.log.Warnf(hodl.BogusSettle.Warning())
3✔
3450
                preimage = [32]byte{}
3✔
3451
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
3✔
3452
        }
3✔
3453

3454
        // HTLC was successfully settled locally send notification about it
3455
        // remote peer.
3456
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
3✔
3457
                ChanID:          l.ChanID(),
3✔
3458
                ID:              htlcIndex,
3✔
3459
                PaymentPreimage: preimage,
3✔
3460
        })
3✔
3461

3✔
3462
        // Once we have successfully settled the htlc, notify a settle event.
3✔
3463
        l.cfg.HtlcNotifier.NotifySettleEvent(
3✔
3464
                HtlcKey{
3✔
3465
                        IncomingCircuit: models.CircuitKey{
3✔
3466
                                ChanID: l.ShortChanID(),
3✔
3467
                                HtlcID: htlcIndex,
3✔
3468
                        },
3✔
3469
                },
3✔
3470
                preimage,
3✔
3471
                HtlcEventTypeReceive,
3✔
3472
        )
3✔
3473

3✔
3474
        return nil
3✔
3475
}
3476

3477
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
3478
// err chan for the individual responses. This method is intended to be spawned
3479
// as a goroutine so the responses can be handled in the background.
3480
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
3✔
3481
        // Don't forward packets for which we already have a response in our
3✔
3482
        // mailbox. This could happen if a packet fails and is buffered in the
3✔
3483
        // mailbox, and the incoming link flaps.
3✔
3484
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
3✔
3485
        for _, pkt := range packets {
6✔
3486
                if l.mailBox.HasPacket(pkt.inKey()) {
6✔
3487
                        continue
3✔
3488
                }
3489

3490
                filteredPkts = append(filteredPkts, pkt)
3✔
3491
        }
3492

3493
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
3✔
3494
        if err != nil {
3✔
3495
                log.Errorf("Unhandled error while reforwarding htlc "+
×
3496
                        "settle/fail over htlcswitch: %v", err)
×
3497
        }
×
3498
}
3499

3500
// sendHTLCError functions cancels HTLC and send cancel message back to the
3501
// peer from which HTLC was received.
3502
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
3503
        sourceRef channeldb.AddRef, failure *LinkError,
3504
        e hop.ErrorEncrypter, isReceive bool) {
3✔
3505

3✔
3506
        reason, err := e.EncryptFirstHop(failure.WireMessage())
3✔
3507
        if err != nil {
3✔
3508
                l.log.Errorf("unable to obfuscate error: %v", err)
×
3509
                return
×
3510
        }
×
3511

3512
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
3✔
3513
        if err != nil {
3✔
3514
                l.log.Errorf("unable cancel htlc: %v", err)
×
3515
                return
×
3516
        }
×
3517

3518
        // Send the appropriate failure message depending on whether we're
3519
        // in a blinded route or not.
3520
        if err := l.sendIncomingHTLCFailureMsg(
3✔
3521
                add.ID, e, reason,
3✔
3522
        ); err != nil {
3✔
3523
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
3524
                return
×
3525
        }
×
3526

3527
        // Notify a link failure on our incoming link. Outgoing htlc information
3528
        // is not available at this point, because we have not decrypted the
3529
        // onion, so it is excluded.
3530
        var eventType HtlcEventType
3✔
3531
        if isReceive {
6✔
3532
                eventType = HtlcEventTypeReceive
3✔
3533
        } else {
6✔
3534
                eventType = HtlcEventTypeForward
3✔
3535
        }
3✔
3536

3537
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
3✔
3538
                HtlcKey{
3✔
3539
                        IncomingCircuit: models.CircuitKey{
3✔
3540
                                ChanID: l.ShortChanID(),
3✔
3541
                                HtlcID: add.ID,
3✔
3542
                        },
3✔
3543
                },
3✔
3544
                HtlcInfo{
3✔
3545
                        IncomingTimeLock: add.Expiry,
3✔
3546
                        IncomingAmt:      add.Amount,
3✔
3547
                },
3✔
3548
                eventType,
3✔
3549
                failure,
3✔
3550
                true,
3✔
3551
        )
3✔
3552
}
3553

3554
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
3555
// peer from which the HTLC was received. This function is primarily used to
3556
// handle the special requirements of route blinding, specifically:
3557
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
3558
// - Introduction nodes should return regular HTLC failure messages.
3559
//
3560
// It accepts the original opaque failure, which will be used in the case
3561
// that we're not part of a blinded route and an error encrypter that'll be
3562
// used if we are the introduction node and need to present an error as if
3563
// we're the failing party.
3564
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
3565
        e hop.ErrorEncrypter,
3566
        originalFailure lnwire.OpaqueReason) error {
3✔
3567

3✔
3568
        var msg lnwire.Message
3✔
3569
        switch {
3✔
3570
        // Our circuit's error encrypter will be nil if this was a locally
3571
        // initiated payment. We can only hit a blinded error for a locally
3572
        // initiated payment if we allow ourselves to be picked as the
3573
        // introduction node for our own payments and in that case we
3574
        // shouldn't reach this code. To prevent the HTLC getting stuck,
3575
        // we fail it back and log an error.
3576
        // code.
3577
        case e == nil:
×
3578
                msg = &lnwire.UpdateFailHTLC{
×
3579
                        ChanID: l.ChanID(),
×
3580
                        ID:     htlcIndex,
×
3581
                        Reason: originalFailure,
×
3582
                }
×
3583

×
3584
                l.log.Errorf("Unexpected blinded failure when "+
×
3585
                        "we are the sending node, incoming htlc: %v(%v)",
×
3586
                        l.ShortChanID(), htlcIndex)
×
3587

3588
        // For cleartext hops (ie, non-blinded/normal) we don't need any
3589
        // transformation on the error message and can just send the original.
3590
        case !e.Type().IsBlinded():
3✔
3591
                msg = &lnwire.UpdateFailHTLC{
3✔
3592
                        ChanID: l.ChanID(),
3✔
3593
                        ID:     htlcIndex,
3✔
3594
                        Reason: originalFailure,
3✔
3595
                }
3✔
3596

3597
        // When we're the introduction node, we need to convert the error to
3598
        // a UpdateFailHTLC.
3599
        case e.Type() == hop.EncrypterTypeIntroduction:
3✔
3600
                l.log.Debugf("Introduction blinded node switching out failure "+
3✔
3601
                        "error: %v", htlcIndex)
3✔
3602

3✔
3603
                // The specification does not require that we set the onion
3✔
3604
                // blob.
3✔
3605
                failureMsg := lnwire.NewInvalidBlinding(
3✔
3606
                        fn.None[[lnwire.OnionPacketSize]byte](),
3✔
3607
                )
3✔
3608
                reason, err := e.EncryptFirstHop(failureMsg)
3✔
3609
                if err != nil {
3✔
3610
                        return err
×
3611
                }
×
3612

3613
                msg = &lnwire.UpdateFailHTLC{
3✔
3614
                        ChanID: l.ChanID(),
3✔
3615
                        ID:     htlcIndex,
3✔
3616
                        Reason: reason,
3✔
3617
                }
3✔
3618

3619
        // If we are a relaying node, we need to switch out any error that
3620
        // we've received to a malformed HTLC error.
3621
        case e.Type() == hop.EncrypterTypeRelaying:
3✔
3622
                l.log.Debugf("Relaying blinded node switching out malformed "+
3✔
3623
                        "error: %v", htlcIndex)
3✔
3624

3✔
3625
                msg = &lnwire.UpdateFailMalformedHTLC{
3✔
3626
                        ChanID:      l.ChanID(),
3✔
3627
                        ID:          htlcIndex,
3✔
3628
                        FailureCode: lnwire.CodeInvalidBlinding,
3✔
3629
                }
3✔
3630

3631
        default:
×
3632
                return fmt.Errorf("unexpected encrypter: %d", e)
×
3633
        }
3634

3635
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
3636
                l.log.Warnf("Send update fail failed: %v", err)
×
3637
        }
×
3638

3639
        return nil
3✔
3640
}
3641

3642
// sendMalformedHTLCError helper function which sends the malformed HTLC update
3643
// to the payment sender.
3644
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
3645
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
3646
        sourceRef *channeldb.AddRef) {
3✔
3647

3✔
3648
        shaOnionBlob := sha256.Sum256(onionBlob[:])
3✔
3649
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
3✔
3650
        if err != nil {
3✔
3651
                l.log.Errorf("unable cancel htlc: %v", err)
×
3652
                return
×
3653
        }
×
3654

3655
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
3✔
3656
                ChanID:       l.ChanID(),
3✔
3657
                ID:           htlcIndex,
3✔
3658
                ShaOnionBlob: shaOnionBlob,
3✔
3659
                FailureCode:  code,
3✔
3660
        })
3✔
3661
}
3662

3663
// failf is a function which is used to encapsulate the action necessary for
3664
// properly failing the link. It takes a LinkFailureError, which will be passed
3665
// to the OnChannelFailure closure, in order for it to determine if we should
3666
// force close the channel, and if we should send an error message to the
3667
// remote peer.
3668
func (l *channelLink) failf(linkErr LinkFailureError, format string,
3669
        a ...interface{}) {
3✔
3670

3✔
3671
        reason := fmt.Errorf(format, a...)
3✔
3672

3✔
3673
        // Return if we have already notified about a failure.
3✔
3674
        if l.failed {
6✔
3675
                l.log.Warnf("ignoring link failure (%v), as link already "+
3✔
3676
                        "failed", reason)
3✔
3677
                return
3✔
3678
        }
3✔
3679

3680
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
3✔
3681

3✔
3682
        // Set failed, such that we won't process any more updates, and notify
3✔
3683
        // the peer about the failure.
3✔
3684
        l.failed = true
3✔
3685
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
3✔
3686
}
3687

3688
// FundingCustomBlob returns the custom funding blob of the channel that this
3689
// link is associated with. The funding blob represents static information about
3690
// the channel that was created at channel funding time.
3691
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
3692
        if l.channel == nil {
×
3693
                return fn.None[tlv.Blob]()
×
3694
        }
×
3695

3696
        if l.channel.State() == nil {
×
3697
                return fn.None[tlv.Blob]()
×
3698
        }
×
3699

3700
        return l.channel.State().CustomBlob
×
3701
}
3702

3703
// CommitmentCustomBlob returns the custom blob of the current local commitment
3704
// of the channel that this link is associated with.
3705
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
3706
        if l.channel == nil {
×
3707
                return fn.None[tlv.Blob]()
×
3708
        }
×
3709

3710
        return l.channel.LocalCommitmentBlob()
×
3711
}
3712

3713
// handleHtlcResolution takes an HTLC resolution and processes it by draining
3714
// the hodlQueue. Once processed, a commit_sig is sent to the remote to update
3715
// their commitment.
3716
func (l *channelLink) handleHtlcResolution(ctx context.Context, hodlItem any) {
3✔
3717
        htlcResolution, ok := hodlItem.(invoices.HtlcResolution)
3✔
3718
        if !ok {
3✔
NEW
3719
                l.log.Errorf("expect HtlcResolution, got %T", hodlItem)
×
NEW
3720
                return
×
NEW
3721
        }
×
3722

3723
        err := l.processHodlQueue(ctx, htlcResolution)
3✔
3724
        switch {
3✔
3725
        // No error, success.
3726
        case err == nil:
3✔
3727

3728
        // If the duplicate keystone error was encountered, fail back
3729
        // gracefully.
NEW
3730
        case errors.Is(err, ErrDuplicateKeystone):
×
NEW
3731
                l.failf(
×
NEW
3732
                        LinkFailureError{
×
NEW
3733
                                code: ErrCircuitError,
×
NEW
3734
                        },
×
NEW
3735
                        "process hodl queue: temporary circuit error: %v", err,
×
NEW
3736
                )
×
3737

3738
        // Send an Error message to the peer.
NEW
3739
        default:
×
NEW
3740
                l.failf(
×
NEW
3741
                        LinkFailureError{
×
NEW
3742
                                code: ErrInternalError,
×
NEW
3743
                        },
×
NEW
3744
                        "process hodl queue: unable to update commitment: %v",
×
NEW
3745
                        err,
×
NEW
3746
                )
×
3747
        }
3748
}
3749

3750
// handleQuiescenceReq takes a locally initialized (RPC) quiescence request and
3751
// forwards it to the quiescer for further processing.
3752
func (l *channelLink) handleQuiescenceReq(req StfuReq) {
3✔
3753
        l.quiescer.InitStfu(req)
3✔
3754

3✔
3755
        if l.noDanglingUpdates(lntypes.Local) {
6✔
3756
                err := l.quiescer.SendOwedStfu()
3✔
3757
                if err != nil {
3✔
NEW
3758
                        l.stfuFailf("SendOwedStfu: %s", err.Error())
×
NEW
3759
                        res := fn.Err[lntypes.ChannelParty](err)
×
NEW
3760
                        req.Resolve(res)
×
NEW
3761
                }
×
3762
        }
3763
}
3764

3765
// handleUpdateFee is called whenever the `updateFeeTimer` ticks. It is used to
3766
// decide whether we should send an `update_fee` msg to update the commitment's
3767
// feerate.
NEW
3768
func (l *channelLink) handleUpdateFee(ctx context.Context) {
×
NEW
3769
        // If we're not the initiator of the channel, don't we don't control the
×
NEW
3770
        // fees, so we can ignore this.
×
NEW
3771
        if !l.channel.IsInitiator() {
×
NEW
3772
                return
×
NEW
3773
        }
×
3774

3775
        // If we are the initiator, then we'll sample the current fee rate to
3776
        // get into the chain within 3 blocks.
NEW
3777
        netFee, err := l.sampleNetworkFee()
×
NEW
3778
        if err != nil {
×
NEW
3779
                l.log.Errorf("unable to sample network fee: %v", err)
×
NEW
3780

×
NEW
3781
                return
×
NEW
3782
        }
×
3783

NEW
3784
        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
×
NEW
3785

×
NEW
3786
        newCommitFee := l.channel.IdealCommitFeeRate(
×
NEW
3787
                netFee, minRelayFee,
×
NEW
3788
                l.cfg.MaxAnchorsCommitFeeRate,
×
NEW
3789
                l.cfg.MaxFeeAllocation,
×
NEW
3790
        )
×
NEW
3791

×
NEW
3792
        // We determine if we should adjust the commitment fee based on the
×
NEW
3793
        // current commitment fee, the suggested new commitment fee and the
×
NEW
3794
        // current minimum relay fee rate.
×
NEW
3795
        commitFee := l.channel.CommitFeeRate()
×
NEW
3796
        if !shouldAdjustCommitFee(newCommitFee, commitFee, minRelayFee) {
×
NEW
3797
                return
×
NEW
3798
        }
×
3799

3800
        // If we do, then we'll send a new UpdateFee message to the remote
3801
        // party, to be locked in with a new update.
NEW
3802
        err = l.updateChannelFee(ctx, newCommitFee)
×
NEW
3803
        if err != nil {
×
NEW
3804
                l.log.Errorf("unable to update fee rate: %v", err)
×
NEW
3805
        }
×
3806
}
3807

3808
// toggleBatchTicker checks whether we need to resume or pause the batch ticker.
3809
// When we have no pending updates, the ticker is paused, otherwise resumed.
3810
func (l *channelLink) toggleBatchTicker() {
3✔
3811
        // If the previous event resulted in a non-empty batch, resume the batch
3✔
3812
        // ticker so that it can be cleared. Otherwise pause the ticker to
3✔
3813
        // prevent waking up the htlcManager while the batch is empty.
3✔
3814
        numUpdates := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
3✔
3815
        if numUpdates > 0 {
6✔
3816
                l.cfg.BatchTicker.Resume()
3✔
3817
                l.log.Tracef("BatchTicker resumed, NumPendingUpdates(Local, "+
3✔
3818
                        "Remote)=%d", numUpdates)
3✔
3819
        } else {
6✔
3820
                l.cfg.BatchTicker.Pause()
3✔
3821
                l.log.Trace("BatchTicker paused due to zero NumPendingUpdates" +
3✔
3822
                        "(Local, Remote)")
3✔
3823
        }
3✔
3824
}
3825

3826
// resumeLink is called when starting a previous link. It will go through the
3827
// reestablishment protocol and reforwarding packets that are yet resolved.
3828
func (l *channelLink) resumeLink(ctx context.Context) {
3✔
3829
        // If this isn't the first time that this channel link has been created,
3✔
3830
        // then we'll need to check to see if we need to re-synchronize state
3✔
3831
        // with the remote peer. settledHtlcs is a map of HTLC's that we
3✔
3832
        // re-settled as part of the channel state sync.
3✔
3833
        if l.cfg.SyncStates {
6✔
3834
                err := l.syncChanStates(ctx)
3✔
3835
                if err != nil {
6✔
3836
                        l.handleChanSyncErr(err)
3✔
3837
                        return
3✔
3838
                }
3✔
3839
        }
3840

3841
        // If a shutdown message has previously been sent on this link, then we
3842
        // need to make sure that we have disabled any HTLC adds on the outgoing
3843
        // direction of the link and that we re-resend the same shutdown message
3844
        // that we previously sent.
3845
        //
3846
        // TODO(yy): we should either move this to chanCloser, or move all
3847
        // shutdown handling logic to be managed by the link, but not a mixed of
3848
        // partial management by two subsystems.
3849
        l.cfg.PreviouslySentShutdown.WhenSome(func(shutdown lnwire.Shutdown) {
6✔
3850
                // Immediately disallow any new outgoing HTLCs.
3✔
3851
                if !l.DisableAdds(Outgoing) {
3✔
NEW
3852
                        l.log.Warnf("Outgoing link adds already disabled")
×
NEW
3853
                }
×
3854

3855
                // Re-send the shutdown message the peer. Since syncChanStates
3856
                // would have sent any outstanding CommitSig, it is fine for us
3857
                // to immediately queue the shutdown message now.
3858
                err := l.cfg.Peer.SendMessage(false, &shutdown)
3✔
3859
                if err != nil {
3✔
NEW
3860
                        l.log.Warnf("Error sending shutdown message: %v", err)
×
NEW
3861
                }
×
3862
        })
3863

3864
        // We've successfully reestablished the channel, mark it as such to
3865
        // allow the switch to forward HTLCs in the outbound direction.
3866
        l.markReestablished()
3✔
3867

3✔
3868
        // With the channel states synced, we now reset the mailbox to ensure we
3✔
3869
        // start processing all unacked packets in order. This is done here to
3✔
3870
        // ensure that all acknowledgments that occur during channel
3✔
3871
        // resynchronization have taken affect, causing us only to pull unacked
3✔
3872
        // packets after starting to read from the downstream mailbox.
3✔
3873
        err := l.mailBox.ResetPackets()
3✔
3874
        if err != nil {
3✔
NEW
3875
                l.log.Errorf("failed to reset packets: %v", err)
×
NEW
3876
        }
×
3877

3878
        // After cleaning up any memory pertaining to incoming packets, we now
3879
        // replay our forwarding packages to handle any htlcs that can be
3880
        // processed locally, or need to be forwarded out to the switch. We will
3881
        // only attempt to resolve packages if our short chan id indicates that
3882
        // the channel is not pending, otherwise we should have no htlcs to
3883
        // reforward.
3884
        if l.ShortChanID() != hop.Source {
6✔
3885
                err := l.resolveFwdPkgs(ctx)
3✔
3886
                switch {
3✔
3887
                // No error was encountered, success.
3888
                case err == nil:
3✔
3889

3890
                // If the duplicate keystone error was encountered, we'll fail
3891
                // without sending an Error message to the peer.
NEW
3892
                case errors.Is(err, ErrDuplicateKeystone):
×
NEW
3893
                        l.failf(LinkFailureError{code: ErrCircuitError},
×
NEW
3894
                                "temporary circuit error: %v", err)
×
NEW
3895
                        return
×
3896

3897
                // A non-nil error was encountered, send an Error message to the
3898
                // peer.
NEW
3899
                default:
×
NEW
3900
                        l.failf(LinkFailureError{code: ErrInternalError},
×
NEW
3901
                                "unable to resolve fwd pkgs: %v", err)
×
NEW
3902
                        return
×
3903
                }
3904

3905
                // With our link's in-memory state fully reconstructed, spawn a
3906
                // goroutine to manage the reclamation of disk space occupied by
3907
                // completed forwarding packages.
3908
                l.cg.WgAdd(1)
3✔
3909
                go l.fwdPkgGarbager()
3✔
3910
        }
3911
}
3912

3913
// processRemoteUpdateAddHTLC takes an `UpdateAddHTLC` msg sent from the remote
3914
// and processes it.
3915
func (l *channelLink) processRemoteUpdateAddHTLC(msg *lnwire.UpdateAddHTLC) {
3✔
3916
        if l.IsFlushing(Incoming) {
3✔
NEW
3917
                // This is forbidden by the protocol specification. The best
×
NEW
3918
                // chance we have to deal with this is to drop the connection.
×
NEW
3919
                // This should roll back the channel state to the last
×
NEW
3920
                // CommitSig. If the remote has already sent a CommitSig we
×
NEW
3921
                // haven't received yet, channel state will be re-synchronized
×
NEW
3922
                // with a ChannelReestablish message upon reconnection and the
×
NEW
3923
                // protocol state that caused us to flush the link will be
×
NEW
3924
                // rolled back. In the event that there was some
×
NEW
3925
                // non-deterministic behavior in the remote that caused them to
×
NEW
3926
                // violate the protocol, we have a decent shot at correcting it
×
NEW
3927
                // this way, since reconnecting will put us in the cleanest
×
NEW
3928
                // possible state to try again.
×
NEW
3929
                //
×
NEW
3930
                // In addition to the above, it is possible for us to hit this
×
NEW
3931
                // case in situations where we improperly handle message
×
NEW
3932
                // ordering due to concurrency choices. An issue has been filed
×
NEW
3933
                // to address this here:
×
NEW
3934
                // https://github.com/lightningnetwork/lnd/issues/8393
×
NEW
3935
                l.failf(
×
NEW
3936
                        LinkFailureError{
×
NEW
3937
                                code:             ErrInvalidUpdate,
×
NEW
3938
                                FailureAction:    LinkFailureDisconnect,
×
NEW
3939
                                PermanentFailure: false,
×
NEW
3940
                                Warning:          true,
×
NEW
3941
                        },
×
NEW
3942
                        "received add while link is flushing",
×
NEW
3943
                )
×
NEW
3944

×
NEW
3945
                return
×
NEW
3946
        }
×
3947

3948
        // Disallow htlcs with blinding points set if we haven't enabled the
3949
        // feature. This saves us from having to process the onion at all, but
3950
        // will only catch blinded payments where we are a relaying node (as the
3951
        // blinding point will be in the payload when we're the introduction
3952
        // node).
3953
        if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
3✔
NEW
3954
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
3955
                        "blinding point included when route blinding "+
×
NEW
3956
                                "is disabled")
×
NEW
3957

×
NEW
3958
                return
×
NEW
3959
        }
×
3960

3961
        // We have to check the limit here rather than later in the switch
3962
        // because the counterparty can keep sending HTLC's without sending a
3963
        // revoke. This would mean that the switch check would only occur later.
3964
        if l.isOverexposedWithHtlc(msg, true) {
3✔
NEW
3965
                l.failf(LinkFailureError{code: ErrInternalError},
×
NEW
3966
                        "peer sent us an HTLC that exceeded our max "+
×
NEW
3967
                                "fee exposure")
×
NEW
3968

×
NEW
3969
                return
×
NEW
3970
        }
×
3971

3972
        // We just received an add request from an upstream peer, so we add it
3973
        // to our state machine, then add the HTLC to our "settle" list in the
3974
        // event that we know the preimage.
3975
        index, err := l.channel.ReceiveHTLC(msg)
3✔
3976
        if err != nil {
3✔
NEW
3977
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
3978
                        "unable to handle upstream add HTLC: %v", err)
×
NEW
3979
                return
×
NEW
3980
        }
×
3981

3982
        l.log.Tracef("receive upstream htlc with payment hash(%x), "+
3✔
3983
                "assigning index: %v", msg.PaymentHash[:], index)
3✔
3984
}
3985

3986
// processRemoteUpdateFulfillHTLC takes an `UpdateFulfillHTLC` msg sent from the
3987
// remote and processes it.
3988
func (l *channelLink) processRemoteUpdateFulfillHTLC(
3989
        msg *lnwire.UpdateFulfillHTLC) {
3✔
3990

3✔
3991
        pre := msg.PaymentPreimage
3✔
3992
        idx := msg.ID
3✔
3993

3✔
3994
        // Before we pipeline the settle, we'll check the set of active htlc's
3✔
3995
        // to see if the related UpdateAddHTLC has been fully locked-in.
3✔
3996
        var lockedin bool
3✔
3997
        htlcs := l.channel.ActiveHtlcs()
3✔
3998
        for _, add := range htlcs {
6✔
3999
                // The HTLC will be outgoing and match idx.
3✔
4000
                if !add.Incoming && add.HtlcIndex == idx {
6✔
4001
                        lockedin = true
3✔
4002
                        break
3✔
4003
                }
4004
        }
4005

4006
        if !lockedin {
3✔
NEW
4007
                l.failf(
×
NEW
4008
                        LinkFailureError{code: ErrInvalidUpdate},
×
NEW
4009
                        "unable to handle upstream settle",
×
NEW
4010
                )
×
NEW
4011

×
NEW
4012
                return
×
NEW
4013
        }
×
4014

4015
        if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
6✔
4016
                l.failf(
3✔
4017
                        LinkFailureError{
3✔
4018
                                code:          ErrInvalidUpdate,
3✔
4019
                                FailureAction: LinkFailureForceClose,
3✔
4020
                        },
3✔
4021
                        "unable to handle upstream settle HTLC: %v", err,
3✔
4022
                )
3✔
4023

3✔
4024
                return
3✔
4025
        }
3✔
4026

4027
        settlePacket := &htlcPacket{
3✔
4028
                outgoingChanID: l.ShortChanID(),
3✔
4029
                outgoingHTLCID: idx,
3✔
4030
                htlc: &lnwire.UpdateFulfillHTLC{
3✔
4031
                        PaymentPreimage: pre,
3✔
4032
                },
3✔
4033
        }
3✔
4034

3✔
4035
        // Add the newly discovered preimage to our growing list of uncommitted
3✔
4036
        // preimage. These will be written to the witness cache just before
3✔
4037
        // accepting the next commitment signature from the remote peer.
3✔
4038
        l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
3✔
4039

3✔
4040
        // Pipeline this settle, send it to the switch.
3✔
4041
        go l.forwardBatch(false, settlePacket)
3✔
4042
}
4043

4044
// processRemoteUpdateFailMalformedHTLC takes an `UpdateFailMalformedHTLC` msg
4045
// sent from the remote and processes it.
4046
func (l *channelLink) processRemoteUpdateFailMalformedHTLC(
4047
        msg *lnwire.UpdateFailMalformedHTLC) {
3✔
4048

3✔
4049
        // Convert the failure type encoded within the HTLC fail message to the
3✔
4050
        // proper generic lnwire error code.
3✔
4051
        var failure lnwire.FailureMessage
3✔
4052
        switch msg.FailureCode {
3✔
4053
        case lnwire.CodeInvalidOnionVersion:
3✔
4054
                failure = &lnwire.FailInvalidOnionVersion{
3✔
4055
                        OnionSHA256: msg.ShaOnionBlob,
3✔
4056
                }
3✔
NEW
4057
        case lnwire.CodeInvalidOnionHmac:
×
NEW
4058
                failure = &lnwire.FailInvalidOnionHmac{
×
NEW
4059
                        OnionSHA256: msg.ShaOnionBlob,
×
NEW
4060
                }
×
4061

NEW
4062
        case lnwire.CodeInvalidOnionKey:
×
NEW
4063
                failure = &lnwire.FailInvalidOnionKey{
×
NEW
4064
                        OnionSHA256: msg.ShaOnionBlob,
×
NEW
4065
                }
×
4066

4067
        // Handle malformed errors that are part of a blinded route. This case
4068
        // is slightly different, because we expect every relaying node in the
4069
        // blinded portion of the route to send malformed errors. If we're also
4070
        // a relaying node, we're likely going to switch this error out anyway
4071
        // for our own malformed error, but we handle the case here for
4072
        // completeness.
4073
        case lnwire.CodeInvalidBlinding:
3✔
4074
                failure = &lnwire.FailInvalidBlinding{
3✔
4075
                        OnionSHA256: msg.ShaOnionBlob,
3✔
4076
                }
3✔
4077

NEW
4078
        default:
×
NEW
4079
                l.log.Warnf("unexpected failure code received in "+
×
NEW
4080
                        "UpdateFailMailformedHTLC: %v", msg.FailureCode)
×
NEW
4081

×
NEW
4082
                // We don't just pass back the error we received from our
×
NEW
4083
                // successor. Otherwise we might report a failure that penalizes
×
NEW
4084
                // us more than needed. If the onion that we forwarded was
×
NEW
4085
                // correct, the node should have been able to send back its own
×
NEW
4086
                // failure. The node did not send back its own failure, so we
×
NEW
4087
                // assume there was a problem with the onion and report that
×
NEW
4088
                // back. We reuse the invalid onion key failure because there is
×
NEW
4089
                // no specific error for this case.
×
NEW
4090
                failure = &lnwire.FailInvalidOnionKey{
×
NEW
4091
                        OnionSHA256: msg.ShaOnionBlob,
×
NEW
4092
                }
×
4093
        }
4094

4095
        // With the error parsed, we'll convert the into it's opaque form.
4096
        var b bytes.Buffer
3✔
4097
        if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
3✔
NEW
4098
                l.log.Errorf("unable to encode malformed error: %v", err)
×
NEW
4099
                return
×
NEW
4100
        }
×
4101

4102
        // If remote side have been unable to parse the onion blob we have sent
4103
        // to it, than we should transform the malformed HTLC message to the
4104
        // usual HTLC fail message.
4105
        err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
3✔
4106
        if err != nil {
3✔
NEW
4107
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
4108
                        "unable to handle upstream fail HTLC: %v", err)
×
NEW
4109

×
NEW
4110
                return
×
NEW
4111
        }
×
4112
}
4113

4114
// processRemoteUpdateFailHTLC takes an `UpdateFailHTLC` msg sent from the
4115
// remote and processes it.
4116
func (l *channelLink) processRemoteUpdateFailHTLC(msg *lnwire.UpdateFailHTLC) {
3✔
4117
        // Verify that the failure reason is at least 256 bytes plus overhead.
3✔
4118
        const minimumFailReasonLength = lnwire.FailureMessageLength + 2 + 2 + 32
3✔
4119

3✔
4120
        if len(msg.Reason) < minimumFailReasonLength {
3✔
NEW
4121
                // We've received a reason with a non-compliant length. Older
×
NEW
4122
                // nodes happily relay back these failures that may originate
×
NEW
4123
                // from a node further downstream. Therefore we can't just fail
×
NEW
4124
                // the channel.
×
NEW
4125
                //
×
NEW
4126
                // We want to be compliant ourselves, so we also can't pass back
×
NEW
4127
                // the reason unmodified. And we must make sure that we don't
×
NEW
4128
                // hit the magic length check of 260 bytes in
×
NEW
4129
                // processRemoteSettleFails either.
×
NEW
4130
                //
×
NEW
4131
                // Because the reason is unreadable for the payer anyway, we
×
NEW
4132
                // just replace it by a compliant-length series of random bytes.
×
NEW
4133
                msg.Reason = make([]byte, minimumFailReasonLength)
×
NEW
4134
                _, err := crand.Read(msg.Reason[:])
×
NEW
4135
                if err != nil {
×
NEW
4136
                        l.log.Errorf("Random generation error: %v", err)
×
NEW
4137

×
NEW
4138
                        return
×
NEW
4139
                }
×
4140
        }
4141

4142
        // Add fail to the update log.
4143
        idx := msg.ID
3✔
4144
        err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
3✔
4145
        if err != nil {
3✔
NEW
4146
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
4147
                        "unable to handle upstream fail HTLC: %v", err)
×
NEW
4148

×
NEW
4149
                return
×
NEW
4150
        }
×
4151
}
4152

4153
// processRemoteCommitSig takes a `CommitSig` msg sent from the remote and
4154
// processes it.
4155
func (l *channelLink) processRemoteCommitSig(ctx context.Context,
4156
        msg *lnwire.CommitSig) {
3✔
4157

3✔
4158
        // Since we may have learned new preimages for the first time, we'll add
3✔
4159
        // them to our preimage cache. By doing this, we ensure any contested
3✔
4160
        // contracts watched by any on-chain arbitrators can now sweep this HTLC
3✔
4161
        // on-chain. We delay committing the preimages until just before
3✔
4162
        // accepting the new remote commitment, as afterwards the peer won't
3✔
4163
        // resend the Settle messages on the next channel reestablishment. Doing
3✔
4164
        // so allows us to more effectively batch this operation, instead of
3✔
4165
        // doing a single write per preimage.
3✔
4166
        err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
3✔
4167
        if err != nil {
3✔
NEW
4168
                l.failf(
×
NEW
4169
                        LinkFailureError{code: ErrInternalError},
×
NEW
4170
                        "unable to add preimages=%v to cache: %v",
×
NEW
4171
                        l.uncommittedPreimages, err,
×
NEW
4172
                )
×
NEW
4173

×
NEW
4174
                return
×
NEW
4175
        }
×
4176

4177
        // Instead of truncating the slice to conserve memory allocations, we
4178
        // simply set the uncommitted preimage slice to nil so that a new one
4179
        // will be initialized if any more witnesses are discovered. We do this
4180
        // because the maximum size that the slice can occupy is 15KB, and we
4181
        // want to ensure we release that memory back to the runtime.
4182
        l.uncommittedPreimages = nil
3✔
4183

3✔
4184
        // We just received a new updates to our local commitment chain,
3✔
4185
        // validate this new commitment, closing the link if invalid.
3✔
4186
        auxSigBlob, err := msg.CustomRecords.Serialize()
3✔
4187
        if err != nil {
3✔
NEW
4188
                l.failf(
×
NEW
4189
                        LinkFailureError{code: ErrInvalidCommitment},
×
NEW
4190
                        "unable to serialize custom records: %v", err,
×
NEW
4191
                )
×
NEW
4192

×
NEW
4193
                return
×
NEW
4194
        }
×
4195
        err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
3✔
4196
                CommitSig:  msg.CommitSig,
3✔
4197
                HtlcSigs:   msg.HtlcSigs,
3✔
4198
                PartialSig: msg.PartialSig,
3✔
4199
                AuxSigBlob: auxSigBlob,
3✔
4200
        })
3✔
4201
        if err != nil {
3✔
NEW
4202
                // If we were unable to reconstruct their proposed commitment,
×
NEW
4203
                // then we'll examine the type of error. If it's an
×
NEW
4204
                // InvalidCommitSigError, then we'll send a direct error.
×
NEW
4205
                var sendData []byte
×
NEW
4206
                switch {
×
NEW
4207
                case lnutils.ErrorAs[*lnwallet.InvalidCommitSigError](err):
×
NEW
4208
                        sendData = []byte(err.Error())
×
NEW
4209
                case lnutils.ErrorAs[*lnwallet.InvalidHtlcSigError](err):
×
NEW
4210
                        sendData = []byte(err.Error())
×
4211
                }
NEW
4212
                l.failf(
×
NEW
4213
                        LinkFailureError{
×
NEW
4214
                                code:          ErrInvalidCommitment,
×
NEW
4215
                                FailureAction: LinkFailureForceClose,
×
NEW
4216
                                SendData:      sendData,
×
NEW
4217
                        },
×
NEW
4218
                        "ChannelPoint(%v): unable to accept new "+
×
NEW
4219
                                "commitment: %v",
×
NEW
4220
                        l.channel.ChannelPoint(), err,
×
NEW
4221
                )
×
NEW
4222

×
NEW
4223
                return
×
4224
        }
4225

4226
        // As we've just accepted a new state, we'll now immediately send the
4227
        // remote peer a revocation for our prior state.
4228
        nextRevocation, currentHtlcs, finalHTLCs, err :=
3✔
4229
                l.channel.RevokeCurrentCommitment()
3✔
4230
        if err != nil {
3✔
NEW
4231
                l.log.Errorf("unable to revoke commitment: %v", err)
×
NEW
4232

×
NEW
4233
                // We need to fail the channel in case revoking our local
×
NEW
4234
                // commitment does not succeed. We might have already advanced
×
NEW
4235
                // our channel state which would lead us to proceed with an
×
NEW
4236
                // unclean state.
×
NEW
4237
                //
×
NEW
4238
                // NOTE: We do not trigger a force close because this could
×
NEW
4239
                // resolve itself in case our db was just busy not accepting new
×
NEW
4240
                // transactions.
×
NEW
4241
                l.failf(
×
NEW
4242
                        LinkFailureError{
×
NEW
4243
                                code:          ErrInternalError,
×
NEW
4244
                                Warning:       true,
×
NEW
4245
                                FailureAction: LinkFailureDisconnect,
×
NEW
4246
                        },
×
NEW
4247
                        "ChannelPoint(%v): unable to accept new "+
×
NEW
4248
                                "commitment: %v",
×
NEW
4249
                        l.channel.ChannelPoint(), err,
×
NEW
4250
                )
×
NEW
4251

×
NEW
4252
                return
×
NEW
4253
        }
×
4254

4255
        // As soon as we are ready to send our next revocation, we can invoke
4256
        // the incoming commit hooks.
4257
        l.Lock()
3✔
4258
        l.incomingCommitHooks.invoke()
3✔
4259
        l.Unlock()
3✔
4260

3✔
4261
        err = l.cfg.Peer.SendMessage(false, nextRevocation)
3✔
4262
        if err != nil {
3✔
NEW
4263
                l.log.Errorf("failed to send RevokeAndAck: %v", err)
×
NEW
4264
        }
×
4265

4266
        // Notify the incoming htlcs of which the resolutions were locked in.
4267
        for id, settled := range finalHTLCs {
6✔
4268
                l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
3✔
4269
                        models.CircuitKey{
3✔
4270
                                ChanID: l.ShortChanID(),
3✔
4271
                                HtlcID: id,
3✔
4272
                        },
3✔
4273
                        channeldb.FinalHtlcInfo{
3✔
4274
                                Settled:  settled,
3✔
4275
                                Offchain: true,
3✔
4276
                        },
3✔
4277
                )
3✔
4278
        }
3✔
4279

4280
        // Since we just revoked our commitment, we may have a new set of HTLC's
4281
        // on our commitment, so we'll send them using our function closure
4282
        // NotifyContractUpdate.
4283
        newUpdate := &contractcourt.ContractUpdate{
3✔
4284
                HtlcKey: contractcourt.LocalHtlcSet,
3✔
4285
                Htlcs:   currentHtlcs,
3✔
4286
        }
3✔
4287
        err = l.cfg.NotifyContractUpdate(newUpdate)
3✔
4288
        if err != nil {
3✔
NEW
4289
                l.log.Errorf("unable to notify contract update: %v", err)
×
NEW
4290
                return
×
NEW
4291
        }
×
4292

4293
        select {
3✔
NEW
4294
        case <-l.cg.Done():
×
NEW
4295
                return
×
4296
        default:
3✔
4297
        }
4298

4299
        // If the remote party initiated the state transition, we'll reply with
4300
        // a signature to provide them with their version of the latest
4301
        // commitment. Otherwise, both commitment chains are fully synced from
4302
        // our PoV, then we don't need to reply with a signature as both sides
4303
        // already have a commitment with the latest accepted.
4304
        if l.channel.OweCommitment() {
6✔
4305
                if !l.updateCommitTxOrFail(ctx) {
3✔
NEW
4306
                        return
×
NEW
4307
                }
×
4308
        }
4309

4310
        // If we need to send out an Stfu, this would be the time to do so.
4311
        if l.noDanglingUpdates(lntypes.Local) {
6✔
4312
                err = l.quiescer.SendOwedStfu()
3✔
4313
                if err != nil {
3✔
NEW
4314
                        l.stfuFailf("sendOwedStfu: %v", err.Error())
×
NEW
4315
                }
×
4316
        }
4317

4318
        // Now that we have finished processing the incoming CommitSig and sent
4319
        // out our RevokeAndAck, we invoke the flushHooks if the channel state
4320
        // is clean.
4321
        l.Lock()
3✔
4322
        if l.channel.IsChannelClean() {
6✔
4323
                l.flushHooks.invoke()
3✔
4324
        }
3✔
4325
        l.Unlock()
3✔
4326
}
4327

4328
// processRemoteRevokeAndAck takes a `RevokeAndAck` msg sent from the remote and
4329
// processes it.
4330
func (l *channelLink) processRemoteRevokeAndAck(ctx context.Context,
4331
        msg *lnwire.RevokeAndAck) {
3✔
4332

3✔
4333
        // We've received a revocation from the remote chain, if valid, this
3✔
4334
        // moves the remote chain forward, and expands our revocation window.
3✔
4335

3✔
4336
        // We now process the message and advance our remote commit chain.
3✔
4337
        fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
3✔
4338
        if err != nil {
3✔
NEW
4339
                // TODO(halseth): force close?
×
NEW
4340
                l.failf(
×
NEW
4341
                        LinkFailureError{
×
NEW
4342
                                code:          ErrInvalidRevocation,
×
NEW
4343
                                FailureAction: LinkFailureDisconnect,
×
NEW
4344
                        },
×
NEW
4345
                        "unable to accept revocation: %v", err,
×
NEW
4346
                )
×
NEW
4347

×
NEW
4348
                return
×
NEW
4349
        }
×
4350

4351
        // The remote party now has a new primary commitment, so we'll update
4352
        // the contract court to be aware of this new set (the prior old remote
4353
        // pending).
4354
        newUpdate := &contractcourt.ContractUpdate{
3✔
4355
                HtlcKey: contractcourt.RemoteHtlcSet,
3✔
4356
                Htlcs:   remoteHTLCs,
3✔
4357
        }
3✔
4358
        err = l.cfg.NotifyContractUpdate(newUpdate)
3✔
4359
        if err != nil {
3✔
NEW
4360
                l.log.Errorf("unable to notify contract update: %v", err)
×
NEW
4361
                return
×
NEW
4362
        }
×
4363

4364
        select {
3✔
NEW
4365
        case <-l.cg.Done():
×
NEW
4366
                return
×
4367
        default:
3✔
4368
        }
4369

4370
        // If we have a tower client for this channel type, we'll create a
4371
        // backup for the current state.
4372
        if l.cfg.TowerClient != nil {
6✔
4373
                state := l.channel.State()
3✔
4374
                chanID := l.ChanID()
3✔
4375

3✔
4376
                err = l.cfg.TowerClient.BackupState(
3✔
4377
                        &chanID, state.RemoteCommitment.CommitHeight-1,
3✔
4378
                )
3✔
4379
                if err != nil {
3✔
NEW
4380
                        l.failf(LinkFailureError{
×
NEW
4381
                                code: ErrInternalError,
×
NEW
4382
                        }, "unable to queue breach backup: %v", err)
×
NEW
4383

×
NEW
4384
                        return
×
NEW
4385
                }
×
4386
        }
4387

4388
        // If we can send updates then we can process adds in case we are the
4389
        // exit hop and need to send back resolutions, or in case there are
4390
        // validity issues with the packets. Otherwise we defer the action until
4391
        // resume.
4392
        //
4393
        // We are free to process the settles and fails without this check since
4394
        // processing those can't result in further updates to this channel
4395
        // link.
4396
        if l.quiescer.CanSendUpdates() {
6✔
4397
                l.processRemoteAdds(fwdPkg)
3✔
4398
        } else {
3✔
NEW
4399
                l.quiescer.OnResume(func() {
×
NEW
4400
                        l.processRemoteAdds(fwdPkg)
×
NEW
4401
                })
×
4402
        }
4403
        l.processRemoteSettleFails(fwdPkg)
3✔
4404

3✔
4405
        // If the link failed during processing the adds, we must return to
3✔
4406
        // ensure we won't attempted to update the state further.
3✔
4407
        if l.failed {
3✔
NEW
4408
                return
×
NEW
4409
        }
×
4410

4411
        // The revocation window opened up. If there are pending local updates,
4412
        // try to update the commit tx. Pending updates could already have been
4413
        // present because of a previously failed update to the commit tx or
4414
        // freshly added in by processRemoteAdds. Also in case there are no
4415
        // local updates, but there are still remote updates that are not in the
4416
        // remote commit tx yet, send out an update.
4417
        if l.channel.OweCommitment() {
6✔
4418
                if !l.updateCommitTxOrFail(ctx) {
3✔
NEW
4419
                        return
×
NEW
4420
                }
×
4421
        }
4422

4423
        // Now that we have finished processing the RevokeAndAck, we can invoke
4424
        // the flushHooks if the channel state is clean.
4425
        l.Lock()
3✔
4426
        if l.channel.IsChannelClean() {
6✔
4427
                l.flushHooks.invoke()
3✔
4428
        }
3✔
4429
        l.Unlock()
3✔
4430
}
4431

4432
// processRemoteUpdateFee takes an `UpdateFee` msg sent from the remote and
4433
// processes it.
NEW
4434
func (l *channelLink) processRemoteUpdateFee(msg *lnwire.UpdateFee) {
×
NEW
4435
        // Check and see if their proposed fee-rate would make us exceed the fee
×
NEW
4436
        // threshold.
×
NEW
4437
        fee := chainfee.SatPerKWeight(msg.FeePerKw)
×
NEW
4438

×
NEW
4439
        isDust, err := l.exceedsFeeExposureLimit(fee)
×
NEW
4440
        if err != nil {
×
NEW
4441
                // This shouldn't typically happen. If it does, it indicates
×
NEW
4442
                // something is wrong with our channel state.
×
NEW
4443
                l.log.Errorf("Unable to determine if fee threshold " +
×
NEW
4444
                        "exceeded")
×
NEW
4445
                l.failf(LinkFailureError{code: ErrInternalError},
×
NEW
4446
                        "error calculating fee exposure: %v", err)
×
NEW
4447

×
NEW
4448
                return
×
NEW
4449
        }
×
4450

NEW
4451
        if isDust {
×
NEW
4452
                // The proposed fee-rate makes us exceed the fee threshold.
×
NEW
4453
                l.failf(LinkFailureError{code: ErrInternalError},
×
NEW
4454
                        "fee threshold exceeded: %v", err)
×
NEW
4455
                return
×
NEW
4456
        }
×
4457

4458
        // We received fee update from peer. If we are the initiator we will
4459
        // fail the channel, if not we will apply the update.
NEW
4460
        if err := l.channel.ReceiveUpdateFee(fee); err != nil {
×
NEW
4461
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
4462
                        "error receiving fee update: %v", err)
×
NEW
4463
                return
×
NEW
4464
        }
×
4465

4466
        // Update the mailbox's feerate as well.
NEW
4467
        l.mailBox.SetFeeRate(fee)
×
4468
}
4469

4470
// processRemoteError takes an `Error` msg sent from the remote and fails the
4471
// channel link.
4472
func (l *channelLink) processRemoteError(msg *lnwire.Error) {
2✔
4473
        // Error received from remote, MUST fail channel, but should only print
2✔
4474
        // the contents of the error message if all characters are printable
2✔
4475
        // ASCII.
2✔
4476
        l.failf(
2✔
4477
                // TODO(halseth): we currently don't fail the channel
2✔
4478
                // permanently, as there are some sync issues with other
2✔
4479
                // implementations that will lead to them sending an
2✔
4480
                // error message, but we can recover from on next
2✔
4481
                // connection. See
2✔
4482
                // https://github.com/ElementsProject/lightning/issues/4212
2✔
4483
                LinkFailureError{
2✔
4484
                        code:             ErrRemoteError,
2✔
4485
                        PermanentFailure: false,
2✔
4486
                },
2✔
4487
                "ChannelPoint(%v): received error from peer: %v",
2✔
4488
                l.channel.ChannelPoint(), msg.Error(),
2✔
4489
        )
2✔
4490
}
2✔
4491

4492
// processLocalUpdateFulfillHTLC takes an `UpdateFulfillHTLC` from the local and
4493
// processes it.
4494
func (l *channelLink) processLocalUpdateFulfillHTLC(ctx context.Context,
4495
        pkt *htlcPacket, htlc *lnwire.UpdateFulfillHTLC) {
3✔
4496

3✔
4497
        // If hodl.SettleOutgoing mode is active, we exit early to simulate
3✔
4498
        // arbitrary delays between the switch adding the SETTLE to the mailbox,
3✔
4499
        // and the HTLC being added to the commitment state.
3✔
4500
        if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
3✔
NEW
4501
                l.log.Warnf(hodl.SettleOutgoing.Warning())
×
NEW
4502
                l.mailBox.AckPacket(pkt.inKey())
×
NEW
4503

×
NEW
4504
                return
×
NEW
4505
        }
×
4506

4507
        // An HTLC we forward to the switch has just settled somewhere upstream.
4508
        // Therefore we settle the HTLC within the our local state machine.
4509
        inKey := pkt.inKey()
3✔
4510
        err := l.channel.SettleHTLC(
3✔
4511
                htlc.PaymentPreimage, pkt.incomingHTLCID, pkt.sourceRef,
3✔
4512
                pkt.destRef, &inKey,
3✔
4513
        )
3✔
4514
        if err != nil {
3✔
NEW
4515
                l.log.Errorf("unable to settle incoming HTLC for "+
×
NEW
4516
                        "circuit-key=%v: %v", inKey, err)
×
NEW
4517

×
NEW
4518
                // If the HTLC index for Settle response was not known to our
×
NEW
4519
                // commitment state, it has already been cleaned up by a prior
×
NEW
4520
                // response. We'll thus try to clean up any lingering state to
×
NEW
4521
                // ensure we don't continue reforwarding.
×
NEW
4522
                if lnutils.ErrorAs[lnwallet.ErrUnknownHtlcIndex](err) {
×
NEW
4523
                        l.cleanupSpuriousResponse(pkt)
×
NEW
4524
                }
×
4525

4526
                // Remove the packet from the link's mailbox to ensure it
4527
                // doesn't get replayed after a reconnection.
NEW
4528
                l.mailBox.AckPacket(inKey)
×
NEW
4529

×
NEW
4530
                return
×
4531
        }
4532

4533
        l.log.Debugf("queueing removal of SETTLE closed circuit: %s->%s",
3✔
4534
                pkt.inKey(), pkt.outKey())
3✔
4535

3✔
4536
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
3✔
4537

3✔
4538
        // With the HTLC settled, we'll need to populate the wire message to
3✔
4539
        // target the specific channel and HTLC to be canceled.
3✔
4540
        htlc.ChanID = l.ChanID()
3✔
4541
        htlc.ID = pkt.incomingHTLCID
3✔
4542

3✔
4543
        // Then we send the HTLC settle message to the connected peer so we can
3✔
4544
        // continue the propagation of the settle message.
3✔
4545
        err = l.cfg.Peer.SendMessage(false, htlc)
3✔
4546
        if err != nil {
3✔
NEW
4547
                l.log.Errorf("failed to send UpdateFulfillHTLC: %v", err)
×
NEW
4548
        }
×
4549

4550
        // Send a settle event notification to htlcNotifier.
4551
        l.cfg.HtlcNotifier.NotifySettleEvent(
3✔
4552
                newHtlcKey(pkt), htlc.PaymentPreimage, getEventType(pkt),
3✔
4553
        )
3✔
4554

3✔
4555
        // Immediately update the commitment tx to minimize latency.
3✔
4556
        l.updateCommitTxOrFail(ctx)
3✔
4557
}
4558

4559
// processLocalUpdateFailHTLC takes an `UpdateFailHTLC` from the local and
4560
// processes it.
4561
func (l *channelLink) processLocalUpdateFailHTLC(ctx context.Context,
4562
        pkt *htlcPacket, htlc *lnwire.UpdateFailHTLC) {
3✔
4563

3✔
4564
        // If hodl.FailOutgoing mode is active, we exit early to simulate
3✔
4565
        // arbitrary delays between the switch adding a FAIL to the mailbox, and
3✔
4566
        // the HTLC being added to the commitment state.
3✔
4567
        if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
3✔
NEW
4568
                l.log.Warnf(hodl.FailOutgoing.Warning())
×
NEW
4569
                l.mailBox.AckPacket(pkt.inKey())
×
NEW
4570

×
NEW
4571
                return
×
NEW
4572
        }
×
4573

4574
        // An HTLC cancellation has been triggered somewhere upstream, we'll
4575
        // remove then HTLC from our local state machine.
4576
        inKey := pkt.inKey()
3✔
4577
        err := l.channel.FailHTLC(
3✔
4578
                pkt.incomingHTLCID, htlc.Reason, pkt.sourceRef, pkt.destRef,
3✔
4579
                &inKey,
3✔
4580
        )
3✔
4581
        if err != nil {
6✔
4582
                l.log.Errorf("unable to cancel incoming HTLC for "+
3✔
4583
                        "circuit-key=%v: %v", inKey, err)
3✔
4584

3✔
4585
                // If the HTLC index for Fail response was not known to our
3✔
4586
                // commitment state, it has already been cleaned up by a prior
3✔
4587
                // response. We'll thus try to clean up any lingering state to
3✔
4588
                // ensure we don't continue reforwarding.
3✔
4589
                if lnutils.ErrorAs[lnwallet.ErrUnknownHtlcIndex](err) {
3✔
NEW
4590
                        l.cleanupSpuriousResponse(pkt)
×
NEW
4591
                }
×
4592

4593
                // Remove the packet from the link's mailbox to ensure it
4594
                // doesn't get replayed after a reconnection.
4595
                l.mailBox.AckPacket(inKey)
3✔
4596

3✔
4597
                return
3✔
4598
        }
4599

4600
        l.log.Debugf("queueing removal of FAIL closed circuit: %s->%s",
3✔
4601
                pkt.inKey(), pkt.outKey())
3✔
4602

3✔
4603
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
3✔
4604

3✔
4605
        // With the HTLC removed, we'll need to populate the wire message to
3✔
4606
        // target the specific channel and HTLC to be canceled. The "Reason"
3✔
4607
        // field will have already been set within the switch.
3✔
4608
        htlc.ChanID = l.ChanID()
3✔
4609
        htlc.ID = pkt.incomingHTLCID
3✔
4610

3✔
4611
        // We send the HTLC message to the peer which initially created the
3✔
4612
        // HTLC. If the incoming blinding point is non-nil, we know that we are
3✔
4613
        // a relaying node in a blinded path. Otherwise, we're either an
3✔
4614
        // introduction node or not part of a blinded path at all.
3✔
4615
        err = l.sendIncomingHTLCFailureMsg(htlc.ID, pkt.obfuscator, htlc.Reason)
3✔
4616
        if err != nil {
3✔
NEW
4617
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
NEW
4618

×
NEW
4619
                return
×
NEW
4620
        }
×
4621

4622
        // If the packet does not have a link failure set, it failed further
4623
        // down the route so we notify a forwarding failure. Otherwise, we
4624
        // notify a link failure because it failed at our node.
4625
        if pkt.linkFailure != nil {
6✔
4626
                l.cfg.HtlcNotifier.NotifyLinkFailEvent(
3✔
4627
                        newHtlcKey(pkt), newHtlcInfo(pkt), getEventType(pkt),
3✔
4628
                        pkt.linkFailure, false,
3✔
4629
                )
3✔
4630
        } else {
6✔
4631
                l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
3✔
4632
                        newHtlcKey(pkt), getEventType(pkt),
3✔
4633
                )
3✔
4634
        }
3✔
4635

4636
        // Immediately update the commitment tx to minimize latency.
4637
        l.updateCommitTxOrFail(ctx)
3✔
4638
}
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