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

lightningnetwork / lnd / 15380904630

02 Jun 2025 12:07AM UTC coverage: 58.379% (+0.05%) from 58.327%
15380904630

Pull #9883

github

web-flow
Merge 4109ecb05 into bff2f2440
Pull Request #9883: protofsm: add thread-safe IsRunning method to StateMachine

1 of 6 new or added lines in 1 file covered. (16.67%)

19 existing lines in 6 files now uncovered.

97496 of 167006 relevant lines covered (58.38%)

1.81 hits per line

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

66.83
/htlcswitch/link.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

370
        sync.RWMutex
371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
455
        return hookID
3✔
456
}
457

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
603
        return nil
3✔
604
}
605

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

785
        return out
3✔
786
}
787

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

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

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

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

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

×
822
        return feePerKw, nil
×
823
}
824

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

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

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

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

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

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

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

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

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

884
        return cb(update)
3✔
885
}
886

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

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

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

909
        var msgsToReSend []lnwire.Message
3✔
910

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1029
        return nil
3✔
1030
}
1031

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

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

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

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

1057
        return nil
3✔
1058
}
1059

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

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

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

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

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

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

1105
        return nil
3✔
1106
}
1107

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1448
                                continue
×
1449
                        }
1450

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

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

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

1475
                        return
3✔
1476

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1600
        return nil
3✔
1601
}
1602

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1718
                l.mailBox.FailAdd(pkt)
×
1719

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1791
        return nil
3✔
1792
}
1793

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

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

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

×
1809
                return
×
1810
        }
×
1811

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

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

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

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

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

×
1857
                        return
×
1858
                }
1859

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

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

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

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

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

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

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

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

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

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

3✔
1923
                        return
3✔
1924
                }
1925

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

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

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

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

×
1951
                        return
×
1952
                }
×
1953

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2102
                        return
×
2103
                }
×
2104

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

×
2115
                        return
×
2116
                }
×
2117

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

×
2127
                        return
×
2128
                }
×
2129

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2288
                                return
×
2289
                        }
×
2290
                }
2291

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2510
                select {
3✔
2511
                case <-l.cg.Done():
×
2512
                        return
×
2513
                default:
3✔
2514
                }
2515

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

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

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

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

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

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

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

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

×
2592
                        return
×
2593
                }
×
2594

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

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

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

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

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

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

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

2650
}
2651

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

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

2668
        return nil
×
2669
}
2670

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

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

3✔
2693
        return pendingOnLocal == 0 && pendingOnRemote == 0
3✔
2694
}
3✔
2695

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

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

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

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

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

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

3✔
2750
        return nil
3✔
2751
}
2752

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

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

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

2776
        return true
3✔
2777
}
2778

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

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

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

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

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

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

3✔
2819
                return nil
3✔
2820
        } else if err != nil {
6✔
2821
                return err
×
2822
        }
×
2823

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

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

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

2844
        select {
3✔
2845
        case <-l.cg.Done():
×
2846
                return ErrLinkShuttingDown
×
2847
        default:
3✔
2848
        }
2849

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

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

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

3✔
2870
        return nil
3✔
2871
}
2872

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

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

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

3✔
2896
        return l.channel.ShortChanID()
3✔
2897
}
3✔
2898

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
3029
                return true, nil
×
3030
        }
×
3031

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

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

×
3041
                return true, nil
×
3042
        }
×
3043

3044
        return false, nil
×
3045
}
3046

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

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

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

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

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

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

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

3✔
3079
        if l.getCommitFee(true) > commitFee {
5✔
3080
                commitFee = l.getCommitFee(true)
2✔
3081
        }
2✔
3082

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

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

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

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

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

×
3110
                return true
×
3111
        }
×
3112

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

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

×
3129
                return true
×
3130
        }
×
3131

3132
        return false
3✔
3133
}
3134

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

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

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

3✔
3150
                var dustLimit btcutil.Amount
3✔
3151
                if whoseCommit.IsLocal() {
6✔
3152
                        dustLimit = localDustLimit
3✔
3153
                } else {
6✔
3154
                        dustLimit = remoteDustLimit
3✔
3155
                }
3✔
3156

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

3163
        return isDust
3✔
3164
}
3165

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3340
        return nil
3✔
3341
}
3342

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3475
        return nil
3✔
3476
}
3477

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3617
        return l.updateCommitTx(ctx)
×
3618
}
3619

3620
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3621
// after receiving a revocation from the remote party, and reprocesses them in
3622
// the context of the provided forwarding package. Any settles or fails that
3623
// have already been acknowledged in the forwarding package will not be sent to
3624
// the switch.
3625
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
3✔
3626
        if len(fwdPkg.SettleFails) == 0 {
6✔
3627
                return
3✔
3628
        }
3✔
3629

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

3✔
3632
        var switchPackets []*htlcPacket
3✔
3633
        for i, update := range fwdPkg.SettleFails {
6✔
3634
                destRef := fwdPkg.DestRef(uint16(i))
3✔
3635

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

3643
                // TODO(roasbeef): rework log entries to a shared
3644
                // interface.
3645

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

3659
                        settlePacket := &htlcPacket{
3✔
3660
                                outgoingChanID: l.ShortChanID(),
3✔
3661
                                outgoingHTLCID: msg.ID,
3✔
3662
                                destRef:        &destRef,
3✔
3663
                                htlc:           msg,
3✔
3664
                        }
3✔
3665

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

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

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

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

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

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

3716
        // Only spawn the task forward packets we have a non-zero number.
3717
        if len(switchPackets) > 0 {
6✔
3718
                go l.forwardBatch(false, switchPackets...)
3✔
3719
        }
3✔
3720
}
3721

3722
// processRemoteAdds serially processes each of the Add payment descriptors
3723
// which have been "locked-in" by receiving a revocation from the remote party.
3724
// The forwarding package provided instructs how to process this batch,
3725
// indicating whether this is the first time these Adds are being processed, or
3726
// whether we are reprocessing as a result of a failure or restart. Adds that
3727
// have already been acknowledged in the forwarding package will be ignored.
3728
//
3729
//nolint:funlen
3730
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
3✔
3731
        l.log.Tracef("processing %d remote adds for height %d",
3✔
3732
                len(fwdPkg.Adds), fwdPkg.Height)
3✔
3733

3✔
3734
        decodeReqs := make(
3✔
3735
                []hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds),
3✔
3736
        )
3✔
3737
        for _, update := range fwdPkg.Adds {
6✔
3738
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
6✔
3739
                        // Before adding the new htlc to the state machine,
3✔
3740
                        // parse the onion object in order to obtain the
3✔
3741
                        // routing information with DecodeHopIterator function
3✔
3742
                        // which process the Sphinx packet.
3✔
3743
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
3✔
3744

3✔
3745
                        req := hop.DecodeHopIteratorRequest{
3✔
3746
                                OnionReader:    onionReader,
3✔
3747
                                RHash:          msg.PaymentHash[:],
3✔
3748
                                IncomingCltv:   msg.Expiry,
3✔
3749
                                IncomingAmount: msg.Amount,
3✔
3750
                                BlindingPoint:  msg.BlindingPoint,
3✔
3751
                        }
3✔
3752

3✔
3753
                        decodeReqs = append(decodeReqs, req)
3✔
3754
                }
3✔
3755
        }
3756

3757
        // Atomically decode the incoming htlcs, simultaneously checking for
3758
        // replay attempts. A particular index in the returned, spare list of
3759
        // channel iterators should only be used if the failure code at the
3760
        // same index is lnwire.FailCodeNone.
3761
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
3✔
3762
                fwdPkg.ID(), decodeReqs,
3✔
3763
        )
3✔
3764
        if sphinxErr != nil {
3✔
3765
                l.failf(LinkFailureError{code: ErrInternalError},
×
3766
                        "unable to decode hop iterators: %v", sphinxErr)
×
3767
                return
×
3768
        }
×
3769

3770
        var switchPackets []*htlcPacket
3✔
3771

3✔
3772
        for i, update := range fwdPkg.Adds {
6✔
3773
                idx := uint16(i)
3✔
3774

3✔
3775
                //nolint:forcetypeassert
3✔
3776
                add := *update.UpdateMsg.(*lnwire.UpdateAddHTLC)
3✔
3777
                sourceRef := fwdPkg.SourceRef(idx)
3✔
3778

3✔
3779
                if fwdPkg.State == channeldb.FwdStateProcessed &&
3✔
3780
                        fwdPkg.AckFilter.Contains(idx) {
3✔
3781

×
3782
                        // If this index is already found in the ack filter,
×
3783
                        // the response to this forwarding decision has already
×
3784
                        // been committed by one of our commitment txns. ADDs
×
3785
                        // in this state are waiting for the rest of the fwding
×
3786
                        // package to get acked before being garbage collected.
×
3787
                        continue
×
3788
                }
3789

3790
                // An incoming HTLC add has been full-locked in. As a result we
3791
                // can now examine the forwarding details of the HTLC, and the
3792
                // HTLC itself to decide if: we should forward it, cancel it,
3793
                // or are able to settle it (and it adheres to our fee related
3794
                // constraints).
3795

3796
                // Before adding the new htlc to the state machine, parse the
3797
                // onion object in order to obtain the routing information with
3798
                // DecodeHopIterator function which process the Sphinx packet.
3799
                chanIterator, failureCode := decodeResps[i].Result()
3✔
3800
                if failureCode != lnwire.CodeNone {
6✔
3801
                        // If we're unable to process the onion blob then we
3✔
3802
                        // should send the malformed htlc error to payment
3✔
3803
                        // sender.
3✔
3804
                        l.sendMalformedHTLCError(
3✔
3805
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
3✔
3806
                        )
3✔
3807

3✔
3808
                        l.log.Errorf("unable to decode onion hop "+
3✔
3809
                                "iterator: %v", failureCode)
3✔
3810
                        continue
3✔
3811
                }
3812

3813
                heightNow := l.cfg.BestHeight()
3✔
3814

3✔
3815
                pld, routeRole, pldErr := chanIterator.HopPayload()
3✔
3816
                if pldErr != nil {
6✔
3817
                        // If we're unable to process the onion payload, or we
3✔
3818
                        // received invalid onion payload failure, then we
3✔
3819
                        // should send an error back to the caller so the HTLC
3✔
3820
                        // can be canceled.
3✔
3821
                        var failedType uint64
3✔
3822

3✔
3823
                        // We need to get the underlying error value, so we
3✔
3824
                        // can't use errors.As as suggested by the linter.
3✔
3825
                        //nolint:errorlint
3✔
3826
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
3✔
3827
                                failedType = uint64(e.Type)
×
3828
                        }
×
3829

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

×
3847
                                // We can't process this htlc, send back
×
3848
                                // malformed.
×
3849
                                l.sendMalformedHTLCError(
×
3850
                                        add.ID, failureCode, add.OnionBlob,
×
3851
                                        &sourceRef,
×
3852
                                )
×
3853

×
3854
                                continue
×
3855
                        }
3856

3857
                        // TODO: currently none of the test unit infrastructure
3858
                        // is setup to handle TLV payloads, so testing this
3859
                        // would require implementing a separate mock iterator
3860
                        // for TLV payloads that also supports injecting invalid
3861
                        // payloads. Deferring this non-trival effort till a
3862
                        // later date
3863
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
3✔
3864

3✔
3865
                        l.sendHTLCError(
3✔
3866
                                add, sourceRef, NewLinkError(failure),
3✔
3867
                                obfuscator, false,
3✔
3868
                        )
3✔
3869

3✔
3870
                        l.log.Errorf("unable to decode forwarding "+
3✔
3871
                                "instructions: %v", pldErr)
3✔
3872

3✔
3873
                        continue
3✔
3874
                }
3875

3876
                // Retrieve onion obfuscator from onion blob in order to
3877
                // produce initial obfuscation of the onion failureCode.
3878
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
3✔
3879
                        l.cfg.ExtractErrorEncrypter,
3✔
3880
                        routeRole == hop.RouteRoleIntroduction,
3✔
3881
                )
3✔
3882
                if failureCode != lnwire.CodeNone {
3✔
3883
                        // If we're unable to process the onion blob than we
×
3884
                        // should send the malformed htlc error to payment
×
3885
                        // sender.
×
3886
                        l.sendMalformedHTLCError(
×
3887
                                add.ID, failureCode, add.OnionBlob,
×
3888
                                &sourceRef,
×
3889
                        )
×
3890

×
3891
                        l.log.Errorf("unable to decode onion "+
×
3892
                                "obfuscator: %v", failureCode)
×
3893

×
3894
                        continue
×
3895
                }
3896

3897
                fwdInfo := pld.ForwardingInfo()
3✔
3898

3✔
3899
                // Check whether the payload we've just processed uses our
3✔
3900
                // node as the introduction point (gave us a blinding key in
3✔
3901
                // the payload itself) and fail it back if we don't support
3✔
3902
                // route blinding.
3✔
3903
                if fwdInfo.NextBlinding.IsSome() &&
3✔
3904
                        l.cfg.DisallowRouteBlinding {
6✔
3905

3✔
3906
                        failure := lnwire.NewInvalidBlinding(
3✔
3907
                                fn.Some(add.OnionBlob),
3✔
3908
                        )
3✔
3909

3✔
3910
                        l.sendHTLCError(
3✔
3911
                                add, sourceRef, NewLinkError(failure),
3✔
3912
                                obfuscator, false,
3✔
3913
                        )
3✔
3914

3✔
3915
                        l.log.Error("rejected htlc that uses use as an " +
3✔
3916
                                "introduction point when we do not support " +
3✔
3917
                                "route blinding")
3✔
3918

3✔
3919
                        continue
3✔
3920
                }
3921

3922
                switch fwdInfo.NextHop {
3✔
3923
                case hop.Exit:
3✔
3924
                        err := l.processExitHop(
3✔
3925
                                add, sourceRef, obfuscator, fwdInfo,
3✔
3926
                                heightNow, pld,
3✔
3927
                        )
3✔
3928
                        if err != nil {
3✔
3929
                                l.failf(LinkFailureError{
×
3930
                                        code: ErrInternalError,
×
3931
                                }, err.Error()) //nolint
×
3932

×
3933
                                return
×
3934
                        }
×
3935

3936
                // There are additional channels left within this route. So
3937
                // we'll simply do some forwarding package book-keeping.
3938
                default:
3✔
3939
                        // If hodl.AddIncoming is requested, we will not
3✔
3940
                        // validate the forwarded ADD, nor will we send the
3✔
3941
                        // packet to the htlc switch.
3✔
3942
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
3✔
3943
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3944
                                continue
×
3945
                        }
3946

3947
                        endorseValue := l.experimentalEndorsement(
3✔
3948
                                record.CustomSet(add.CustomRecords),
3✔
3949
                        )
3✔
3950
                        endorseType := uint64(
3✔
3951
                                lnwire.ExperimentalEndorsementType,
3✔
3952
                        )
3✔
3953

3✔
3954
                        switch fwdPkg.State {
3✔
3955
                        case channeldb.FwdStateProcessed:
3✔
3956
                                // This add was not forwarded on the previous
3✔
3957
                                // processing phase, run it through our
3✔
3958
                                // validation pipeline to reproduce an error.
3✔
3959
                                // This may trigger a different error due to
3✔
3960
                                // expiring timelocks, but we expect that an
3✔
3961
                                // error will be reproduced.
3✔
3962
                                if !fwdPkg.FwdFilter.Contains(idx) {
3✔
3963
                                        break
×
3964
                                }
3965

3966
                                // Otherwise, it was already processed, we can
3967
                                // can collect it and continue.
3968
                                outgoingAdd := &lnwire.UpdateAddHTLC{
3✔
3969
                                        Expiry:        fwdInfo.OutgoingCTLV,
3✔
3970
                                        Amount:        fwdInfo.AmountToForward,
3✔
3971
                                        PaymentHash:   add.PaymentHash,
3✔
3972
                                        BlindingPoint: fwdInfo.NextBlinding,
3✔
3973
                                }
3✔
3974

3✔
3975
                                endorseValue.WhenSome(func(e byte) {
6✔
3976
                                        custRecords := map[uint64][]byte{
3✔
3977
                                                endorseType: {e},
3✔
3978
                                        }
3✔
3979

3✔
3980
                                        outgoingAdd.CustomRecords = custRecords
3✔
3981
                                })
3✔
3982

3983
                                // Finally, we'll encode the onion packet for
3984
                                // the _next_ hop using the hop iterator
3985
                                // decoded for the current hop.
3986
                                buf := bytes.NewBuffer(
3✔
3987
                                        outgoingAdd.OnionBlob[0:0],
3✔
3988
                                )
3✔
3989

3✔
3990
                                // We know this cannot fail, as this ADD
3✔
3991
                                // was marked forwarded in a previous
3✔
3992
                                // round of processing.
3✔
3993
                                chanIterator.EncodeNextHop(buf)
3✔
3994

3✔
3995
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
3996

3✔
3997
                                //nolint:ll
3✔
3998
                                updatePacket := &htlcPacket{
3✔
3999
                                        incomingChanID:       l.ShortChanID(),
3✔
4000
                                        incomingHTLCID:       add.ID,
3✔
4001
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
4002
                                        sourceRef:            &sourceRef,
3✔
4003
                                        incomingAmount:       add.Amount,
3✔
4004
                                        amount:               outgoingAdd.Amount,
3✔
4005
                                        htlc:                 outgoingAdd,
3✔
4006
                                        obfuscator:           obfuscator,
3✔
4007
                                        incomingTimeout:      add.Expiry,
3✔
4008
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
4009
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
4010
                                        inboundFee:           inboundFee,
3✔
4011
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
4012
                                }
3✔
4013
                                switchPackets = append(
3✔
4014
                                        switchPackets, updatePacket,
3✔
4015
                                )
3✔
4016

3✔
4017
                                continue
3✔
4018
                        }
4019

4020
                        // TODO(roasbeef): ensure don't accept outrageous
4021
                        // timeout for htlc
4022

4023
                        // With all our forwarding constraints met, we'll
4024
                        // create the outgoing HTLC using the parameters as
4025
                        // specified in the forwarding info.
4026
                        addMsg := &lnwire.UpdateAddHTLC{
3✔
4027
                                Expiry:        fwdInfo.OutgoingCTLV,
3✔
4028
                                Amount:        fwdInfo.AmountToForward,
3✔
4029
                                PaymentHash:   add.PaymentHash,
3✔
4030
                                BlindingPoint: fwdInfo.NextBlinding,
3✔
4031
                        }
3✔
4032

3✔
4033
                        endorseValue.WhenSome(func(e byte) {
6✔
4034
                                addMsg.CustomRecords = map[uint64][]byte{
3✔
4035
                                        endorseType: {e},
3✔
4036
                                }
3✔
4037
                        })
3✔
4038

4039
                        // Finally, we'll encode the onion packet for the
4040
                        // _next_ hop using the hop iterator decoded for the
4041
                        // current hop.
4042
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
3✔
4043
                        err := chanIterator.EncodeNextHop(buf)
3✔
4044
                        if err != nil {
3✔
4045
                                l.log.Errorf("unable to encode the "+
×
4046
                                        "remaining route %v", err)
×
4047

×
4048
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
4049
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
4050
                                }
×
4051

4052
                                failure := l.createFailureWithUpdate(
×
4053
                                        true, hop.Source, cb,
×
4054
                                )
×
4055

×
4056
                                l.sendHTLCError(
×
4057
                                        add, sourceRef, NewLinkError(failure),
×
4058
                                        obfuscator, false,
×
4059
                                )
×
4060
                                continue
×
4061
                        }
4062

4063
                        // Now that this add has been reprocessed, only append
4064
                        // it to our list of packets to forward to the switch
4065
                        // this is the first time processing the add. If the
4066
                        // fwd pkg has already been processed, then we entered
4067
                        // the above section to recreate a previous error.  If
4068
                        // the packet had previously been forwarded, it would
4069
                        // have been added to switchPackets at the top of this
4070
                        // section.
4071
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
6✔
4072
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
4073

3✔
4074
                                //nolint:ll
3✔
4075
                                updatePacket := &htlcPacket{
3✔
4076
                                        incomingChanID:       l.ShortChanID(),
3✔
4077
                                        incomingHTLCID:       add.ID,
3✔
4078
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
4079
                                        sourceRef:            &sourceRef,
3✔
4080
                                        incomingAmount:       add.Amount,
3✔
4081
                                        amount:               addMsg.Amount,
3✔
4082
                                        htlc:                 addMsg,
3✔
4083
                                        obfuscator:           obfuscator,
3✔
4084
                                        incomingTimeout:      add.Expiry,
3✔
4085
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
4086
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
4087
                                        inboundFee:           inboundFee,
3✔
4088
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
4089
                                }
3✔
4090

3✔
4091
                                fwdPkg.FwdFilter.Set(idx)
3✔
4092
                                switchPackets = append(switchPackets,
3✔
4093
                                        updatePacket)
3✔
4094
                        }
3✔
4095
                }
4096
        }
4097

4098
        // Commit the htlcs we are intending to forward if this package has not
4099
        // been fully processed.
4100
        if fwdPkg.State == channeldb.FwdStateLockedIn {
6✔
4101
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
3✔
4102
                if err != nil {
3✔
4103
                        l.failf(LinkFailureError{code: ErrInternalError},
×
4104
                                "unable to set fwd filter: %v", err)
×
4105
                        return
×
4106
                }
×
4107
        }
4108

4109
        if len(switchPackets) == 0 {
6✔
4110
                return
3✔
4111
        }
3✔
4112

4113
        replay := fwdPkg.State != channeldb.FwdStateLockedIn
3✔
4114

3✔
4115
        l.log.Debugf("forwarding %d packets to switch: replay=%v",
3✔
4116
                len(switchPackets), replay)
3✔
4117

3✔
4118
        // NOTE: This call is made synchronous so that we ensure all circuits
3✔
4119
        // are committed in the exact order that they are processed in the link.
3✔
4120
        // Failing to do this could cause reorderings/gaps in the range of
3✔
4121
        // opened circuits, which violates assumptions made by the circuit
3✔
4122
        // trimming.
3✔
4123
        l.forwardBatch(replay, switchPackets...)
3✔
4124
}
4125

4126
// experimentalEndorsement returns the value to set for our outgoing
4127
// experimental endorsement field, and a boolean indicating whether it should
4128
// be populated on the outgoing htlc.
4129
func (l *channelLink) experimentalEndorsement(
4130
        customUpdateAdd record.CustomSet) fn.Option[byte] {
3✔
4131

3✔
4132
        // Only relay experimental signal if we are within the experiment
3✔
4133
        // period.
3✔
4134
        if !l.cfg.ShouldFwdExpEndorsement() {
6✔
4135
                return fn.None[byte]()
3✔
4136
        }
3✔
4137

4138
        // If we don't have any custom records or the experimental field is
4139
        // not set, just forward a zero value.
4140
        if len(customUpdateAdd) == 0 {
6✔
4141
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
4142
        }
3✔
4143

4144
        t := uint64(lnwire.ExperimentalEndorsementType)
3✔
4145
        value, set := customUpdateAdd[t]
3✔
4146
        if !set {
3✔
4147
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4148
        }
×
4149

4150
        // We expect at least one byte for this field, consider it invalid if
4151
        // it has no data and just forward a zero value.
4152
        if len(value) == 0 {
3✔
4153
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4154
        }
×
4155

4156
        // Only forward endorsed if the incoming link is endorsed.
4157
        if value[0] == lnwire.ExperimentalEndorsed {
6✔
4158
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
3✔
4159
        }
3✔
4160

4161
        // Forward as unendorsed otherwise, including cases where we've
4162
        // received an invalid value that uses more than 3 bits of information.
4163
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
4164
}
4165

4166
// processExitHop handles an htlc for which this link is the exit hop. It
4167
// returns a boolean indicating whether the commitment tx needs an update.
4168
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
4169
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
4170
        fwdInfo hop.ForwardingInfo, heightNow uint32,
4171
        payload invoices.Payload) error {
3✔
4172

3✔
4173
        // If hodl.ExitSettle is requested, we will not validate the final hop's
3✔
4174
        // ADD, nor will we settle the corresponding invoice or respond with the
3✔
4175
        // preimage.
3✔
4176
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
6✔
4177
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
3✔
4178
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
3✔
4179

3✔
4180
                return nil
3✔
4181
        }
3✔
4182

4183
        // In case the traffic shaper is active, we'll check if the HTLC has
4184
        // custom records and skip the amount check in the onion payload below.
4185
        isCustomHTLC := fn.MapOptionZ(
3✔
4186
                l.cfg.AuxTrafficShaper,
3✔
4187
                func(ts AuxTrafficShaper) bool {
3✔
4188
                        return ts.IsCustomHTLC(add.CustomRecords)
×
4189
                },
×
4190
        )
4191

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

×
4201
                failure := NewLinkError(
×
4202
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
×
4203
                )
×
4204
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
4205

×
4206
                return nil
×
4207
        }
×
4208

4209
        // We'll also ensure that our time-lock value has been computed
4210
        // correctly.
4211
        if add.Expiry < fwdInfo.OutgoingCTLV {
3✔
4212
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
×
4213
                        "incompatible time-lock: expected <=%v, got %v",
×
4214
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
×
4215

×
4216
                failure := NewLinkError(
×
4217
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
×
4218
                )
×
4219

×
4220
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
4221

×
4222
                return nil
×
4223
        }
×
4224

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

3✔
4230
        circuitKey := models.CircuitKey{
3✔
4231
                ChanID: l.ShortChanID(),
3✔
4232
                HtlcID: add.ID,
3✔
4233
        }
3✔
4234

3✔
4235
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
3✔
4236
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
3✔
4237
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
3✔
4238
        )
3✔
4239
        if err != nil {
3✔
4240
                return err
×
4241
        }
×
4242

4243
        // Create a hodlHtlc struct and decide either resolved now or later.
4244
        htlc := hodlHtlc{
3✔
4245
                add:        add,
3✔
4246
                sourceRef:  sourceRef,
3✔
4247
                obfuscator: obfuscator,
3✔
4248
        }
3✔
4249

3✔
4250
        // If the event is nil, the invoice is being held, so we save payment
3✔
4251
        // descriptor for future reference.
3✔
4252
        if event == nil {
6✔
4253
                l.hodlMap[circuitKey] = htlc
3✔
4254
                return nil
3✔
4255
        }
3✔
4256

4257
        // Process the received resolution.
4258
        return l.processHtlcResolution(event, htlc)
3✔
4259
}
4260

4261
// settleHTLC settles the HTLC on the channel.
4262
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
4263
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
3✔
4264

3✔
4265
        hash := preimage.Hash()
3✔
4266

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

3✔
4269
        err := l.channel.SettleHTLC(
3✔
4270
                preimage, htlcIndex, &sourceRef, nil, nil,
3✔
4271
        )
3✔
4272
        if err != nil {
3✔
4273
                return fmt.Errorf("unable to settle htlc: %w", err)
×
4274
        }
×
4275

4276
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
4277
        // fake one before sending it to the peer.
4278
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
6✔
4279
                l.log.Warnf(hodl.BogusSettle.Warning())
3✔
4280
                preimage = [32]byte{}
3✔
4281
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
3✔
4282
        }
3✔
4283

4284
        // HTLC was successfully settled locally send notification about it
4285
        // remote peer.
4286
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
3✔
4287
                ChanID:          l.ChanID(),
3✔
4288
                ID:              htlcIndex,
3✔
4289
                PaymentPreimage: preimage,
3✔
4290
        })
3✔
4291

3✔
4292
        // Once we have successfully settled the htlc, notify a settle event.
3✔
4293
        l.cfg.HtlcNotifier.NotifySettleEvent(
3✔
4294
                HtlcKey{
3✔
4295
                        IncomingCircuit: models.CircuitKey{
3✔
4296
                                ChanID: l.ShortChanID(),
3✔
4297
                                HtlcID: htlcIndex,
3✔
4298
                        },
3✔
4299
                },
3✔
4300
                preimage,
3✔
4301
                HtlcEventTypeReceive,
3✔
4302
        )
3✔
4303

3✔
4304
        return nil
3✔
4305
}
4306

4307
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
4308
// err chan for the individual responses. This method is intended to be spawned
4309
// as a goroutine so the responses can be handled in the background.
4310
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
3✔
4311
        // Don't forward packets for which we already have a response in our
3✔
4312
        // mailbox. This could happen if a packet fails and is buffered in the
3✔
4313
        // mailbox, and the incoming link flaps.
3✔
4314
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
3✔
4315
        for _, pkt := range packets {
6✔
4316
                if l.mailBox.HasPacket(pkt.inKey()) {
6✔
4317
                        continue
3✔
4318
                }
4319

4320
                filteredPkts = append(filteredPkts, pkt)
3✔
4321
        }
4322

4323
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
3✔
4324
        if err != nil {
3✔
4325
                log.Errorf("Unhandled error while reforwarding htlc "+
×
4326
                        "settle/fail over htlcswitch: %v", err)
×
4327
        }
×
4328
}
4329

4330
// sendHTLCError functions cancels HTLC and send cancel message back to the
4331
// peer from which HTLC was received.
4332
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
4333
        sourceRef channeldb.AddRef, failure *LinkError,
4334
        e hop.ErrorEncrypter, isReceive bool) {
3✔
4335

3✔
4336
        reason, err := e.EncryptFirstHop(failure.WireMessage())
3✔
4337
        if err != nil {
3✔
4338
                l.log.Errorf("unable to obfuscate error: %v", err)
×
4339
                return
×
4340
        }
×
4341

4342
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
3✔
4343
        if err != nil {
3✔
4344
                l.log.Errorf("unable cancel htlc: %v", err)
×
4345
                return
×
4346
        }
×
4347

4348
        // Send the appropriate failure message depending on whether we're
4349
        // in a blinded route or not.
4350
        if err := l.sendIncomingHTLCFailureMsg(
3✔
4351
                add.ID, e, reason,
3✔
4352
        ); err != nil {
3✔
4353
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
4354
                return
×
4355
        }
×
4356

4357
        // Notify a link failure on our incoming link. Outgoing htlc information
4358
        // is not available at this point, because we have not decrypted the
4359
        // onion, so it is excluded.
4360
        var eventType HtlcEventType
3✔
4361
        if isReceive {
6✔
4362
                eventType = HtlcEventTypeReceive
3✔
4363
        } else {
6✔
4364
                eventType = HtlcEventTypeForward
3✔
4365
        }
3✔
4366

4367
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
3✔
4368
                HtlcKey{
3✔
4369
                        IncomingCircuit: models.CircuitKey{
3✔
4370
                                ChanID: l.ShortChanID(),
3✔
4371
                                HtlcID: add.ID,
3✔
4372
                        },
3✔
4373
                },
3✔
4374
                HtlcInfo{
3✔
4375
                        IncomingTimeLock: add.Expiry,
3✔
4376
                        IncomingAmt:      add.Amount,
3✔
4377
                },
3✔
4378
                eventType,
3✔
4379
                failure,
3✔
4380
                true,
3✔
4381
        )
3✔
4382
}
4383

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

3✔
4398
        var msg lnwire.Message
3✔
4399
        switch {
3✔
4400
        // Our circuit's error encrypter will be nil if this was a locally
4401
        // initiated payment. We can only hit a blinded error for a locally
4402
        // initiated payment if we allow ourselves to be picked as the
4403
        // introduction node for our own payments and in that case we
4404
        // shouldn't reach this code. To prevent the HTLC getting stuck,
4405
        // we fail it back and log an error.
4406
        // code.
4407
        case e == nil:
×
4408
                msg = &lnwire.UpdateFailHTLC{
×
4409
                        ChanID: l.ChanID(),
×
4410
                        ID:     htlcIndex,
×
4411
                        Reason: originalFailure,
×
4412
                }
×
4413

×
4414
                l.log.Errorf("Unexpected blinded failure when "+
×
4415
                        "we are the sending node, incoming htlc: %v(%v)",
×
4416
                        l.ShortChanID(), htlcIndex)
×
4417

4418
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4419
        // transformation on the error message and can just send the original.
4420
        case !e.Type().IsBlinded():
3✔
4421
                msg = &lnwire.UpdateFailHTLC{
3✔
4422
                        ChanID: l.ChanID(),
3✔
4423
                        ID:     htlcIndex,
3✔
4424
                        Reason: originalFailure,
3✔
4425
                }
3✔
4426

4427
        // When we're the introduction node, we need to convert the error to
4428
        // a UpdateFailHTLC.
4429
        case e.Type() == hop.EncrypterTypeIntroduction:
3✔
4430
                l.log.Debugf("Introduction blinded node switching out failure "+
3✔
4431
                        "error: %v", htlcIndex)
3✔
4432

3✔
4433
                // The specification does not require that we set the onion
3✔
4434
                // blob.
3✔
4435
                failureMsg := lnwire.NewInvalidBlinding(
3✔
4436
                        fn.None[[lnwire.OnionPacketSize]byte](),
3✔
4437
                )
3✔
4438
                reason, err := e.EncryptFirstHop(failureMsg)
3✔
4439
                if err != nil {
3✔
4440
                        return err
×
4441
                }
×
4442

4443
                msg = &lnwire.UpdateFailHTLC{
3✔
4444
                        ChanID: l.ChanID(),
3✔
4445
                        ID:     htlcIndex,
3✔
4446
                        Reason: reason,
3✔
4447
                }
3✔
4448

4449
        // If we are a relaying node, we need to switch out any error that
4450
        // we've received to a malformed HTLC error.
4451
        case e.Type() == hop.EncrypterTypeRelaying:
3✔
4452
                l.log.Debugf("Relaying blinded node switching out malformed "+
3✔
4453
                        "error: %v", htlcIndex)
3✔
4454

3✔
4455
                msg = &lnwire.UpdateFailMalformedHTLC{
3✔
4456
                        ChanID:      l.ChanID(),
3✔
4457
                        ID:          htlcIndex,
3✔
4458
                        FailureCode: lnwire.CodeInvalidBlinding,
3✔
4459
                }
3✔
4460

4461
        default:
×
4462
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4463
        }
4464

4465
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
4466
                l.log.Warnf("Send update fail failed: %v", err)
×
4467
        }
×
4468

4469
        return nil
3✔
4470
}
4471

4472
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4473
// to the payment sender.
4474
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4475
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
4476
        sourceRef *channeldb.AddRef) {
3✔
4477

3✔
4478
        shaOnionBlob := sha256.Sum256(onionBlob[:])
3✔
4479
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
3✔
4480
        if err != nil {
3✔
4481
                l.log.Errorf("unable cancel htlc: %v", err)
×
4482
                return
×
4483
        }
×
4484

4485
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
3✔
4486
                ChanID:       l.ChanID(),
3✔
4487
                ID:           htlcIndex,
3✔
4488
                ShaOnionBlob: shaOnionBlob,
3✔
4489
                FailureCode:  code,
3✔
4490
        })
3✔
4491
}
4492

4493
// failf is a function which is used to encapsulate the action necessary for
4494
// properly failing the link. It takes a LinkFailureError, which will be passed
4495
// to the OnChannelFailure closure, in order for it to determine if we should
4496
// force close the channel, and if we should send an error message to the
4497
// remote peer.
4498
func (l *channelLink) failf(linkErr LinkFailureError, format string,
4499
        a ...interface{}) {
3✔
4500

3✔
4501
        reason := fmt.Errorf(format, a...)
3✔
4502

3✔
4503
        // Return if we have already notified about a failure.
3✔
4504
        if l.failed {
6✔
4505
                l.log.Warnf("ignoring link failure (%v), as link already "+
3✔
4506
                        "failed", reason)
3✔
4507
                return
3✔
4508
        }
3✔
4509

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

3✔
4512
        // Set failed, such that we won't process any more updates, and notify
3✔
4513
        // the peer about the failure.
3✔
4514
        l.failed = true
3✔
4515
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
3✔
4516
}
4517

4518
// FundingCustomBlob returns the custom funding blob of the channel that this
4519
// link is associated with. The funding blob represents static information about
4520
// the channel that was created at channel funding time.
4521
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
4522
        if l.channel == nil {
×
4523
                return fn.None[tlv.Blob]()
×
4524
        }
×
4525

4526
        if l.channel.State() == nil {
×
4527
                return fn.None[tlv.Blob]()
×
4528
        }
×
4529

4530
        return l.channel.State().CustomBlob
×
4531
}
4532

4533
// CommitmentCustomBlob returns the custom blob of the current local commitment
4534
// of the channel that this link is associated with.
4535
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
4536
        if l.channel == nil {
×
4537
                return fn.None[tlv.Blob]()
×
4538
        }
×
4539

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